user4943236
user4943236

Reputation: 6344

PHP:mySQL: Not able to update all the rows in the data base. Table is getting partially updated

I'm experiencing a strange behavior, where I'm not able to update all the rows successfully in the database.

I have a PHP web page that displays some data after fetching it from MYSQL. The webpage also gives flexibility to the user to make any edits, and after making changes and clicking Update button, the values in the text boxes gets updated in the database. The problem that I'm getting is that only first 60 rows are being updated instead of all 177.

This is a small web page having the values after user made the updates. Lets say, user updated Rihaana to Eminem.

ID      FieldText
01      Slim Shady
02      Dr. Dre
05      Rihaana -->> 'Eminem'

Using AJAX, I have sent the json file to the php file, where I'm extracting the values and updating it in the database. My JSON looks like:

array(2) {
["fieldText"]=>
array(177) {
[0]=>
string(55) "Slim Shady"
[1]=>
string(24) "Dr Dre"
[2]=>
string(27) "Eminem"
}
["ID"]=>
array(177) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "5"
}}

JSON generated is valid one. The actual length of JSON is 177

Once the json is being sent to php file, I'm splitting the json code into 2 arrays and length of both the arrays is 177.

Now what I'm doing next is for every ID, I'm fetching field Text and would like to update it in the database.

$jsonData = json_decode($_POST['postData'],true);
$length = count($jsonData['ID']); ## The length is 177 in my json
$ID = $jsonData['ID']; ## The length is 177 in my json
$fieldText = $jsonData['fieldText']; ## The length is 177 in my json

Now, with below code, I'm updating all the values in the row using for loop, but this loop is running for 60 iterations only not 177(as expected):

for($j=0; $j< count($jsonData['ID']); $j++) {

$langText = $fieldText[$j];
$id = (int) $ID[$j];

$update = "UPDATE languageUpdate  SET fieldText = '$langText'
                WHERE ID = $id";
                //echo "$update";
$mysqli->query($update) or die(mysql_error());}}

I tried doing debugging, but not able to do so. Can someone please help out.

Upvotes: 0

Views: 80

Answers (1)

Mateo Barahona
Mateo Barahona

Reputation: 1391

If you have 177 items, the problem lies with the query, not the loop. It probably fails and then go to the die statement.

Display $update and check the last one before it fails (but you should be able to find the error by looking at mysql_error()). My guess is you have a simple quote in $langText or any other bad character. Escape your variable, it's a good practice :

$update = "UPDATE languageUpdate
SET fieldText = '".$mysqli->real_escape_string($langText)."'
WHERE ID = $id";

Upvotes: 1

Related Questions