Matt Jameson
Matt Jameson

Reputation: 217

SQL injection check and php throw error

I have two question

  1. is the following code a good way of practicing against SQL injection ( it seems to work OK as an insert method)

  2. How would in place this error message in the full example:

    if (!mysqli_query($query,$link))
    {
        die('Error: ' . mysqli_error());
    }
    

here is the full example:

<?php

$link = mysqli_connect("localhost","root","", "runtracker");
if (!$link)
{
    die('Could not connect: ' . mysqli_error());
}

$query="INSERT INTO userinfo (UserName) VALUES (?)";

if ($stmt = mysqli_prepare($link, $query)) {

    // Lets create the variables
    $name = $_POST['UserName'];

    // Bind the variables and execute the query
    mysqli_stmt_bind_param($stmt,"s", $name);
    mysqli_stmt_execute($stmt);

    // And now we close the statement
    mysqli_stmt_close($stmt);
}

echo "1 record added";

mysqli_close($link);
?>

Upvotes: 0

Views: 230

Answers (1)

Bill Karwin
Bill Karwin

Reputation: 562270

Yes, using bound parameters is a good way to protect against SQL injection, for dynamic values in SQL queries. For more on SQL injection, you might like my presentation SQL Injection Myths and Fallacies.

You're right that it's good to check for errors after calling API functions. Most mysqli functions return FALSE on error, but connecting is handled slightly differently.

I also like to output the Mysqli error to a log I can read, but not to the user's browser.

Here's how I would code it:

<?php

$mysqli = new mysqli("localhost","root","", "runtracker");
if (mysqli_connect_error())
{
    error_log("Connect error in file ".__FILE__.", line ".__LINE__.": "
      .mysqli_connect_error());
    die("Could not connect to database");
}

if (($stmt = $mysqli->prepare($link, $query)) === false) {
  error_log("Error on prepare in file ".__FILE__.", line ".__LINE__.": "
    .$mysqli->error);
  die('Error on prepare');
}

// Lets create the variables
$name = $_POST['UserName'];

// Bind the variables and execute the query
if ($stmt->bind_param("s", $name) === false) {
  error_log("Error on bind in file ".__FILE__.", line ".__LINE__.": "
    .$stmt->error);
  die('Error on bind');
}
if ($stmt->execute() === false) {
  error_log("Error on execute in file ".__FILE__.", line ".__LINE__.": "
    .$stmt->error);
  die('Error on execute');
}

// And now we close the statement
$stmt->close();

echo "1 record added";

$mysqli->close();

Upvotes: 1

Related Questions