Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQLi prepared update statement in PHP

Tags:

sql

php

xss

mysqli

How do you write a prepared update statement? Reference:mysqli::prepare

I've tried writing it as described:

  if ($stmt = $mysqli->prepare("UPDATE tblFacilityHrs SET title =? description = ? WHERE uid = ?")){
            $stmt->bind_param('sss', $title, $desc, $uid2);

            //Get params
            $title=$_POST['title'];
            $desc=$_POST['description'];
            $uid2=$_GET['uid'];     

$stmt->execute();
            $stmt->close();
    }
    else {
        //Error
        printf("Prep statment failed: %s\n", $mysqli->error);
    }

Error:

Prep statment failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'description = ? WHERE uid = ?' at line 1 Edited row.

like image 539
에이바 Avatar asked May 16 '12 17:05

에이바


People also ask

What is Mysqli prepare statement?

A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Prepared statements basically work like this: Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?").

Can we use prepared statement for select query in PHP?

You must always use prepared statements for any SQL query that would contain a PHP variable. To do so, always follow the below steps: Create a correct SQL SELECT statement.

What is $STMT in PHP Mysqli?

$stmt is just rather idiomatic. A prepared statement as such is a database feature. The database itself takes the query in two steps: first the query structure with placeholders, second the data to fill in the placeholders.


1 Answers

You're just missing a comma between the set columns:

UPDATE tblFacilityHrs SET title = ?, description = ? WHERE uid = ?
                                ^^^^^^

When MySQL reports an error the likes of check the manual for syntax to use near 'something, look most often to the character immediately preceding the 'something, as that is where your error occurs.

Note: you may need to call bind_param() after setting the input variables rather than before. I can't remember how MySQLi parses them and when they're bound, but logically it makes more sense in code to set them first then bind anyway.

//Get params
$title=$_POST['title'];
$desc=$_POST['description'];
$uid2=$_GET['uid'];   

$stmt->bind_param('sss', $title, $desc, $uid2);
like image 179
Michael Berkowski Avatar answered Oct 03 '22 23:10

Michael Berkowski