0

I have this code written, every think is working fine and query1 is executed successfully. but checkbox values are showing only second selected value.

form action="inputform.php" method="post">
        Select skills
        PHP
        <input type="checkbox" value="PHP" name="skills[]">
        JAVA
        <input type="checkbox" value="Java" name="skills[]"> <br>
        <input type="submit" value="submit">
    </form>

  <?php
$con1 = mysqli_connect("localhost","root","","php_practice"); 
if(!$con1){
die("fail");
}

$skills=$_POST['skills'];
for($i=0; $i<sizeof($skills);$i++){
    $query1= "INSERT INTO practice (skills) VALUES ('$skills[$i]')";   
}
$execute1 = mysqli_query($con1,$query1);
If($execute1){
    echo "query1 executed";
}
else
{
    echo "query not executed";
}
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
  • 1
    You make queries for all values of `$skills`, but you only `mysqli_query()` the last one, because `mysqli_query()` is outside the `for ()` loop. – KIKO Software Mar 07 '20 at 09:24
  • 2
    Please read the chapter [SQL Injection](https://www.php.net/manual/en/security.database.sql-injection.php) in the PHP manual before you continue. – KIKO Software Mar 07 '20 at 09:27
  • what is the solution code? – Yasir Altaf Mar 07 '20 at 09:33
  • You have to put `mysqli_query()` inside the `for ()` loop. – KIKO Software Mar 07 '20 at 09:38
  • i tried but it adds two rows instead of adding values to one column, – Yasir Altaf Mar 07 '20 at 09:51
  • I see what you mean, you want to insert all values of the `$skills` array into one row. In that case you can do `$skills = implode(',',$_POST['skills']);` and forget about the `for ()` loop. Just use one query: `$query1 = "INSERT INTO practice (skills) VALUES ('$skills')";`. I don't provide this as an answer because it doesn't solve the SQL injection problem. – KIKO Software Mar 07 '20 at 10:04
  • 1
    **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Mar 07 '20 at 11:14
  • Only checked checkboxes are send to the server. This is how HTML works. You need to have a list in PHP and then you compare which ones you received from HTML and which ones are missing. – Dharman Mar 07 '20 at 11:15

1 Answers1

-2

Change Checkbox Value to String then it will Store in Single row but if you Want 2-row skill row for a single I don't think that the write way.

Guarav
  • 11
  • 2