lolace lolace - 1 year ago 42
PHP Question

Update array into sql database

I want to update my array into my database with the data from the form. Below is my form:

$query = "SELECT category FROM `$tablename`";
$result2 = mysqli_query($link, $query);

$rowcount = mysqli_num_rows($result2);
if ($rowcount > 0) {

<div class="center_content">

<div id="right_wrap">
<div id="right_content">

<ul id="tabsmenu" class="tabsmenu">
<li class="active"><a href="#tab1">Update Category</a></li>
<li class=""><a href="#tab2">Add Category</a></li>
<li class=""><a href="#tab3">View All Category</a></li>

<div id="tab1" class="tabcontent">
<div style="margin:0 auto" align=center>

<div class="form">
<form action="editCatB.php" method="post">

<div class="form_row">
<label>Outlet Name:</label>
<input type="text" class="form_input" name="tablename" value="<?php echo $name; ?>"readonly/>

<div class ="form_row">
<label>Outlet Category/Stalls :</label>
<div class="form_row">

<div class="input_fields_wrap">
mysqli_data_seek($result2, 0);

while ($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {

<div><input class="form_input" type="text" name="mytext[]"value="<?php echo $row2['category']; ?>

And here is my sql. I want to know how to update the respectively row. Because right now it just update all of my
into the first value

$tableName = $_POST['tablename'];
$values = $_POST['mytext'];

$tableCat = $tableName . "categoryList";

$newString = preg_replace('/\s+/', '', $values);

for ($i = 0; $i < count($newString); $i++) {
$cat = $newString[$i];
$sql = "UPDATE `$tableCat` SET category = `$cat`";

$result = mysqli_query($link, $sql) or die(mysqli_error($link));

It also returns me with the error 'Unknown column 'abc' in 'field list'


1) Backticks are for table names and column names, not column values. You'll want to use regular quotes, or take advantage of mysqli's bindings, which is recommended to prevent sql injection.

2) You want to use a WHERE clause when updating. I'd suggest using the id value for the row when creating the table

<div><input class="form_input" type="text" name="mytext[<?php echo $row2['id']?>]" value="<?php echo $row2['category']; ?>"></div>

Then when you iterate through the values, you can pull out the id:

foreach($newString as $id=>$cat) {
    $sql = "UPDATE `$tableCat` SET category = '$cat' WHERE id = '$id'";

    $result = mysqli_query($link, $sql) or die(mysqli_error($link));