0

I have a site where users can input multiple values in the text fields, so I created an array for the post values and have successfully inserted the values of the array into the database.

I have a problem updating these values that I have stored in the database. I tried this but it's not working.

<?php
if (!empty($_POST['sub_cat'])) {
    $cat_id = $_GET['c_id'];
    $subcat_title_array = $_POST['sub_cat'];
    for ($i = 0; $i < count($subcat_title_array); $i++) {
        $subcat_title = mysqli_real_escape_string($connection, $subcat_title_array[$i]);
        $query = "UPDATE sub_categories SET subcat_title =  '{$subcat_title}' WHERE subcat_id = $cat_id";
        $update_sub_category = mysqli_query($connection, $query);
        if (!$update_sub_category) {
            die("Query Failed " . mysqli_error($connection));
        }
    }          
} 
?>

Is there anything am doing wrong?

Any help will be appreciated.

chrki
  • 6,143
  • 6
  • 35
  • 55
Daniel
  • 67
  • 1
  • 7
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! [Don't believe it?](http://stackoverflow.com/q/38297105/1011527) – Jay Blanchard Nov 17 '16 at 22:30
  • What happens if you run echo query and run that through php my admin? – atoms Nov 17 '16 at 22:30
  • Welcome to Stack Overflow! It looks like you need to learn to use a debugger. Please help yourself to some [complementary debugging techniques](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). If you still have issues afterwards, please feel free to come back with more details. – Joe C Nov 17 '16 at 22:34
  • You're repeatedly updating the same record with `WHERE subcat_id = $cat_id`. – Barmar Nov 17 '16 at 22:49
  • I echo the values am getting from the form, they displayed correctly. My problem now is updating the database. – Daniel Nov 17 '16 at 23:08
  • your where clause is wrong , you updating the same record. you should have to update the record one by one using $i – Amit Chauhan Nov 18 '16 at 05:19
  • You are updating the same record in the loop. So it will have the the value of late item in the array. Your category id should also be an array. – T.Shah Nov 18 '16 at 06:32
  • Where are you defining $connection? – deChristo Nov 18 '16 at 10:14
  • @LuizEduardodeChristo I included a file at the top, the $connection is defined in that file. – Daniel Nov 18 '16 at 19:04
  • Please, insert ini_set('display_errors','on') right after – deChristo Nov 18 '16 at 19:50

0 Answers0