4

I have been struggling with this for several days now. I have searched on how to update tables and have managed to get as far as to update rows, but only the last one in the table. So now i am trying to get a loop that loops through all the inputs and updates the database with the inputted values. I think the code that needs to be corrected is located near the end of the code

What i want to do:

  • Get/display database in html table
  • Change values of certain columns
  • Update the database table using a submit button which updates every row in database

Here is a picture of what the table looks like in web view:

Table as it would look in web view

<?php
//Connect to database
include '../db/connect.php';
?>
   <form action='test7.php' method="post">
      <table border='1'>
         <?php
            $result = $MySQLi_CON->query("SELECT * FROM users");
               echo "<tr>";
               echo "<td colspan='3'>CLASS 1</td>";
               echo "</tr>";
               //All table rows in database presented in html table
               while($row = $result->fetch_array()){
                  echo "<tr>";
                  echo "<td><input type='hidden' name='user_id[]' value='".$row['user_id']."' /></td>";
                  echo "<td>username  :<input type='text' name='username[]' value='".$row['username']."' /></td>";
                  echo "<td>email  :<input type='text' name='email[]' value='".$row['email']."' /></td>";
                  echo "<td>rank  :<input type='number' name='rank[]' value='".$row['rank']."' /></td>";
                  echo "</tr>";
               }
            echo "<input type='submit' name='update' value='UPDATE' />";
         ?>
      <table>
   </form>
<?php
   if(isset($_POST['update'])){ 
      $total = count($_POST['rank']); 
      $user_id_arr = $_POST['user_id']; 
      $rank_arr = $_POST['rank']; 
      for($i = 0; $i < $total; $i++){ 
         $user_id = $user_id_arr[$i]; 
         $rank = $rank_arr[$i]; 
         $query = "UPDATE users SET `rank`= '".$rank."' WHERE `user_id`= '".$user_id."'"; 
         $MySQLi_CON->query($query); 
         header('Location: test7.php');
      } 
   }
?>

When I press the UPDATE button, i get PHP Notice: Array to string conversion in....

It refers to line 30 which is this line:

$query = "UPDATE user SET rank=$_POST[rank][$row] WHERE user_id=$value ";

EDIT: Edited the code above to the working code. Thank you @Frayne Konok for your help.

3
  • 1
    So.. var_dump($_POST[rank][$row]) and var_dump($value) Commented Apr 3, 2016 at 10:49
  • your update query may be doing wrong, try with quota. Commented Apr 3, 2016 at 11:29
  • you make a mistake here, you use the same resource to the foreach loop, so you face some unknown problem. Commented Apr 3, 2016 at 15:22

2 Answers 2

3

You are very close.

The issue is that in this code $_POST[rank][$row] - rank is an undefined constant. You need it to be a string, like so $_POST['rank'][$row]. Also, pull the $POST variable out of the query directly to allow typecasting - you should always be very uncomfortable when you see a query that has $_POST data directly:

if(isset($_POST['update'])){
    foreach ($result as $row => $value) { 
        // typecast to a number with decimals below.  If you only need integers, than use (int)
        $rank = (float)$_POST['rank'][$row];
        $query = "UPDATE user SET rank={$rank} WHERE user_id={$value}";
        $MySQLi_CON->query($query);
    }
}

However, it would be better to use mysqli prepared statements rather than insert the variables directly - as it stand, the above code is vulnerable to SQL Injection attacks.

Your code should be modified to look something like so to prevent sql injection attacks:

if(isset($_POST['update'])) {
    $stmt = $MySQLi_CON->prepare("UPDATE user SET rank= ? WHERE user_id= ?");
    foreach ($result as $row => $value){      
        $stmt->bind_param('di', $_POST['rank'][$row], $value); 
        $stmt->execute(); 
    }
    $stmt->close();
}
Sign up to request clarification or add additional context in comments.

2 Comments

I did what you said and modified the last chunk of code to: <br/> if(isset($_POST['update'])) { $stmt = $MySQLi_CON->prepare("$query = "UPDATE user SET rank= ? WHERE user_id= ?"); foreach ($result as $row => $value){ $stmt->bind_param('di', $_POST['rank'][$row], $value); $stmt->execute(); } $stmt->close(); } It now returns this error: Call to a member function bind_param() on boolean
@cale_b, did you notice? The user use the same $result to the loop which is a resource of query.
1

You did a great mistake here, Why you use the $result in foreach loop?? FRom where the $result comes?? The $result is the resource of the sql query.

Try this:

if(isset($_POST['update'])){
    $total = count($_POST['rank']);
    $user_id_arr = $_POST['user_id'];
    $rank_arr = $_POST['rank'];
    for($i = 0; $i < $total; $i++){
        $user_id = $user_id_arr[$i];
        $rank = $rank_arr[$i];
        $query = "UPDATE users SET `rank`= '".$rank."' WHERE `user_id`= '".$user_id."'";  
        $MySQLi_CON->query($query);
    }
}

Try with this and let me know if there is any problem.

8 Comments

I tried it and it doesn't give any errors. However, when I press the update button, none of the fields are being updated in the database. When I press the button, all the values just return to what they were before I changed them.
if you can make a sqlfiddle then i can try or find out the real problem.
I have never used sqlfiddle before but I am trying now. I will write another comment if I manage to make one.
Okay I think I've made an sqlfiddle. The link is sqlfiddle.com/#!9/2d1cd/2/0. Hope you can help me find this problem
Thank you so much, I am staying tuned.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.