ipkiss
ipkiss

Reputation: 57

how would i write prepared sql statements rather than using real_escape PHP, MySQL

public $id;
public $filename;
public $type;
public $size;
public $description;
public $title;

this is what i am using now, which is bad,

$sql = "INSERT INTO photographgallery 
              (filename,type,size,description,title)
    VALUES ('$sanitized_filename', '$sanitized_type', '$sanitized_size', '$sanitized_description', '$sanitized_title')"; 

i was wondering if i could write a prepared statement for this, how would i go about it, i am stack. help.

Upvotes: 1

Views: 48

Answers (2)

Darwin von Corax
Darwin von Corax

Reputation: 5246

In your SQL you replace the variables with question-mark placeholders (?). Create a mysqli_stmt by passing your query to mysqli::prepare, then bind your variables to the placeholders with a call to mysqli_stmt::bind_param. Call mysqli_stmt::executeto perform the insert. It looks like this:

$sql = "INSERT INTO photographgallery 
            (filename, type, size, description, title)
          VALUES
            (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
// The string 'ssiss' in the following means 'string, string, int, string, string'
//  and describes the types of the parameters.
$stmt->bind_param('ssiss', $filename, $type, $size, $description, $title);
$stmt->execute();
$stmt->close();  // always clean up after yourself

Upvotes: 2

Matt
Matt

Reputation: 1757

// Your variables, however you get them.    
$filename = "name1";
$type = "type1";
$size = 100;
$desc = "test desc";
$title = "title"

if($stmt = $mysqli->prepare("INSERT INTO photographgallery (filename, type, size, description, title) VALUES (?, ?, ?, ?, ?)") {
    $stmt->bind_param('ssiss', $filename, $type, $size, $desc, $title); //Assuming the variables are string, string, int, string, string respectively
    $stmt->execute();
    $stmt->close();
}

Using the if around the code ensures that it only runs if the prepare statement has no errors. If there is an error the prepare statement returns false.

Upvotes: 1

Related Questions