PHP MySQL update only updating one row

Asked
Active3 hr before
Viewed126 times

9 Answers

update
90%

This could come in handy if you're expecting to be running multiple queries with the same ID, but its not really ideal to run two queries if you're only performing one update operation., 7 This will fail with MySQL error #1093: You can't specify target table 'table' for update in FROM clause. MySQL does not support updating a table while reading from it with a subquery. – iblue Feb 9 '12 at 23:37 ,Using PHP I tend to do run a mysqli_num_rows then put the result into a variable, then do an UPDATE statement saying where ID = the newly created variable. Some people have posted there is no need to use LIMIT 1 on the end however I like to do this as it doesn't cause any trivial delay but could prevent any unforeseen actions from being taken.,If you have only just inserted the row you can use PHP's mysqli_insert_id function to return this id automatically to you without needing to run the mysqli_num_rows query.

The use of MAX() is not possible at this position. But you can do this:

UPDATE table SET name = 'test_name'
ORDER BY id DESC LIMIT 1;
load more v
88%

Notice that the WHERE clause is so important that you should not forget. Sometimes, you may want to update just one row; However, you may forget the WHERE clause and accidentally update all rows of the table.,Third, specify which rows to be updated using a condition in the WHERE clause. The WHERE clause is optional. If you omit it, the UPDATE statement will modify all rows in the table.,The UPDATE statement updates data in a table. It allows you to change the values in one or more columns of a single row or multiple rows.,Summary: updating data is one of the most important tasks when you work with the database. In this tutorial, you will learn how to use the MySQL UPDATE statement to update data in a table.

The following illustrates the basic syntax of the UPDATE statement:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
UPDATE[LOW_PRIORITY][IGNORE] table_name
SET
column_name1 = expr1,
   column_name2 = expr2,
   ...[WHERE
      condition
   ];
Code language: SQL(Structured Query Language)(sql)
load more v
72%

I have set up an update query which will update values entered into text fields on a while loop. This works fine until multiple data is being looped from the database. Then for some reason only the last data in the loop will be updated and the rest will stay the same.,Your updating the list table outside of your while loop. Which will contain the values that where last selected (in line 7).,Having one form (including submit button) per row. That way your browser knows on a per-form-basis what uniquely identifiable input field values it should submit.,It is generally a bad idea to have multiple inputs with the same name in one form, which is what happens here if more than one row from the table is selected.

I have set up an update query which will update values entered into text fields on a while loop. This works fine until multiple data is being looped from the database. Then for some reason only the last data in the loop will be updated and the rest will stay the same.

    <form method="post" action="update.php">
    <?php
    $id = $_POST["id"];
    $fname = $_POST["fname"];
    $lname = $_POST["lname"];

   $query= "SELECT * FROM list ORDER BY id ASC" ;
   $result= mysql_query($query);
   while($row = mysql_fetch_assoc($result) ){
   echo"<input type=\"hidden\" name=\"id\" value=" . $row['id'] . " />";
   echo"<input type=\"text\" name=\"fname\" value=" . $row['fname'] . " />";
   echo"<input type=\"text\" name=\"lname\" value=" . $row['lname'] . " />";
 }
?>
  <input type="submit" value="Save Changes" />

 <?php
 $sql = "UPDATE list SET fname = '{$fname}', lname = '{$lname}' WHERE id = {$id}";

  $result = mysql_query( $sql );
 ?>
</form>
load more v
65%

Let us first create a table −,Display all records from the table using select statement −,Following is the query to update only specific records in a range without updating the entire column −,Update only a single column in a MySQL table and increment on the basis of a condition

Let us first create a table −

mysql > create table DemoTable(
   Name varchar(40),
   Position int
);
Query OK, 0 rows affected(1.17 sec)
load more v
75%

mysql_affected_rows — Get number of affected rows in previous MySQL operation,mysql_num_rows() - Get number of rows in result,mysqli_affected_rows(),Example #2 mysql_affected_rows() example using transactions

Records deleted: 10
Records deleted: 0
load more v
40%

UPDATE is a DML statement that modifies rows in a table. , For the multiple-table syntax, UPDATE updates rows in each table named in table_references that satisfy the conditions. Each matching row is updated once, even if it matches the conditions multiple times. For multiple-table syntax, ORDER BY and LIMIT cannot be used. , The UPDATE statement supports the following modifiers: , Single-table UPDATE assignments are generally evaluated from left to right. For multiple-table updates, there is no guarantee that assignments are carried out in any particular order.

Single-table syntax:

UPDATE[LOW_PRIORITY][IGNORE] table_reference
SET assignment_list
   [WHERE where_condition]
   [ORDER BY...]
   [LIMIT row_count]

value: {
   expr | DEFAULT
}

assignment:
   col_name = value

assignment_list:
   assignment[, assignment]...
load more v
22%

The MySQL UPDATE query is used to update existing records in a table in a MySQL database.,It can be used to update one or more field at the same time.,PHP | MySQL ( Creating Database ),How to Insert Form Data into Database using PHP ?

60%

In this tutorial you'll learn how to update the records in a MySQL table using PHP.,The PHP code in the following example will update the email address of a person in the persons table whose id is equal to 1.,After update the persons table will look something like this:,Warning: The WHERE clause in the UPDATE statement specifies which record or records should be updated. If you omit the WHERE clause, all records will be updated.

Let's make a SQL query using the UPDATE statement and WHERE clause, after that we will execute this query through passing it to the PHP mysqli_query() function to update the tables records. Consider the following persons table inside the demo database:

+ -- -- + -- -- -- -- -- -- + -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- +
|
id | first_name | last_name | email |
   + -- -- + -- -- -- -- -- -- + -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- +
   |
   1 | Peter | Parker | peterparker @mail.com |
   |
   2 | John | Rambo | johnrambo @mail.com |
   |
   3 | Clark | Kent | clarkkent @mail.com |
   |
   4 | John | Carter | johncarter @mail.com |
   |
   5 | Harry | Potter | harrypotter @mail.com |
   + -- -- + -- -- -- -- -- -- + -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- +
< ? php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if ($link === false) {
   die("ERROR: Could not connect. ".mysqli_connect_error());
}

// Attempt update query execution
$sql = "UPDATE persons SET email='peterparker_new@mail.com' WHERE id=1";
if (mysqli_query($link, $sql)) {
   echo "Records were updated successfully.";
} else {
   echo "ERROR: Could not able to execute $sql. ".mysqli_error($link);
}

// Close connection
mysqli_close($link); ?
>
< ? php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "root", "", "demo");

// Check connection
if ($mysqli === false) {
   die("ERROR: Could not connect. ".$mysqli - > connect_error);
}

// Attempt update query execution
$sql = "UPDATE persons SET email='peterparker_new@mail.com' WHERE id=1";
if ($mysqli - > query($sql) === true) {
   echo "Records were updated successfully.";
} else {
   echo "ERROR: Could not able to execute $sql. ".$mysqli - > error;
}

// Close connection
$mysqli - > close(); ?
>
< ? php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try {
   $pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
   // Set the PDO error mode to exception
   $pdo - > setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
   die("ERROR: Could not connect. ".$e - > getMessage());
}

// Attempt update query execution
try {
   $sql = "UPDATE persons SET email='peterparker_new@mail.com' WHERE id=1";
   $pdo - > exec($sql);
   echo "Records were updated successfully.";
} catch (PDOException $e) {
   die("ERROR: Could not able to execute $sql. ".$e - > getMessage());
}

// Close connection
unset($pdo); ?
>

After update the persons table will look something like this:

+ -- -- + -- -- -- -- -- -- + -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- -- -- +
|
id | first_name | last_name | email |
   + -- -- + -- -- -- -- -- -- + -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- -- -- +
   |
   1 | Peter | Parker | peterparker_new @mail.com |
   |
   2 | John | Rambo | johnrambo @mail.com |
   |
   3 | Clark | Kent | clarkkent @mail.com |
   |
   4 | John | Carter | johncarter @mail.com |
   |
   5 | Harry | Potter | harrypotter @mail.com |
   + -- -- + -- -- -- -- -- -- + -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- -- -- -- +
load more v
48%

MySQL provides a number of useful statements when it is necessary to INSERT rows after determining whether that row is, in fact, new or already exists.,Using INSERT ... ON DUPLICATE KEY UPDATE,A matching data row is found, causing that existing row to be deleted with the standard DELETE statement, then a normal INSERT is performed afterward.,Notice that even though we only altered one row, the result indicates that two rows were affected because we actually DELETED the existing row then INSERTED the new row to replace it.

mysql > SELECT * FROM books LIMIT 3; +
-- -- + -- -- -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- +
|
id | title | author | year_published |
   + -- -- + -- -- -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- +
   |
   1 | In Search of Lost Time | Marcel Proust | 1913 |
   |
   2 | Ulysses | James Joyce | 1922 |
   |
   3 | Don Quixote | Miguel de Cervantes | 1605 |
   + -- -- + -- -- -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- -- -- - + -- -- -- -- -- -- -- -- +
   3 rows in set(0.00 sec)
load more v

Other "update-undefined" queries related to "PHP MySQL update only updating one row"