0

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);
?>
2
  • Where, exactly, are you doing anything to protect yourself against SQL injection? Commented Dec 9, 2012 at 17:46
  • @JackManey, he's using a prepared statement. Commented Dec 9, 2012 at 18:15

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.