简体   繁体   中英

Update using PDO statement

I am still getting my head around a PDO statement but the code below does not do what I assumed it would

  $temp = "6c ";    
  $weather_report = "Its currently $temp " ; 

  $qry = $pdo->exec("UPDATE data_weather SET text= '$weather_report' WHERE period='report' ");

This does update my database but only with 'Its currently' and the temp value is missing ,

After reading some articles I believe I need to use quote but I am not sure how to implement it ?

any help please ?

Please use query parameters instead of interpolating variables into SQL strings.
It's safer, faster, and easier.

$temp = "6c ";    
$weather_report = "It's currently $temp " ; 

$sql = "UPDATE data_weather SET text= ? WHERE period='report'";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($weather_report));

Note that you don't need to quote the string. In fact, you must not put quotes around the ? placeholder. You can use apostrophes inside your weather report string safely.

You can use a parameter placeholder any place you would normally put a single scalar value in an SQL expression. Eg in place of a quoted string, quoted date, or numeric literal. But not for table names or column names, or for lists of values, or SQL keywords.

Although Bill has already answered the question, I'd like to add:

Do not use named parameters with TEXT columns, at least not with MySQL. It won't work. Use question marks instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM