PHP query MySQL update

I have a site that has an update request. Example.

Table name -> myTable
Table Content -> id (AI)
                 name -> myName
                 age -> 13
                 image -> (no values)
                 birthdate -> (no values)

I put only the name and age values . In the image and date of birth, I did not put anything.
If I edit it and update, and I do not put anything in the name and at the age , I put only the values โ€‹โ€‹of image and the date of birth . The result is this. (I need this question)

Table name -> myTable
Table Content -> id (AI)
                 name -> myName
                 age -> 13
                 image -> myImage.jpg
                 birthdate -> Feb. 31, 2010


This is my code:

<? php
  // mysql connect ...
  // mysql select database ...
$ sql = "UPDATE myTable SET name = '". $ name. "', age = '". $ age. "', image = '". $ image. "', birthdate" '$ birthdate .. "' WHERE id = $ id ";
mysql_query ($ sql);
?>

I used this code, but the output is:

Table name -> myTable
Table Content -> id (AI)
                 name -> (no values)
                 age -> (no values)
                 image -> myImage.jpg
                 birthdate -> Feb. 31, 2010


Feel free to ask if you understand my question
Thank you

+3
source share
5 answers

UPDATE , , UPDATE.

$sql , , , , .

<?php

$columns = array("name", "age", "image", "birthdate");
$set = array();
foreach ($columns as $col) {
    if (isset($_GET[$col])) {
      $set[] = "$col = '" . mysql_real_escape_string($_GET[$col]) . "'";
    }
}
$sql = "UPDATE myTable "
if ($set) {
    $sql .= " SET " . implode(",", $set);
}
$sql .= " WHERE id = " . (int) $id;
+4

-

$sql = "UPDATE myTable SET name = '".$name."', age = '".$age."', image = '".$image."', birthdate"'$birthdate.."' WHERE id = $id"

:

$sql = "UPDATE myTable SET name = '".$name."', age = '".$age."', image = '".$image."', birthdate = '".$birthdate."' WHERE id = $id"

, , . , ? , . , , .

+2

:

// update name and age
$sql = "UPDATE myTable SET name = '$name', age = '$age' WHERE id = '$id'";

// Update image and birthday
$sql = "UPDATE myTable SET image = '$image', birthdate = '$birthdate' WHERE id = '$id'";

, .

+1

, .

+1

Personally, I think that such queries are not so reliable, especially when it comes to type casting, etc.

I recommend trying and implementing PDO or something like that.

http://php.net/manual/en/book.pdo.php

Otherwise, the error birthdate'".$birthdate."'should bebirthdate = '".$birthdate."'

0
source

Source: https://habr.com/ru/post/1748071/


All Articles