0

I'm trying to return a single record with the following statements:

$username = $_POST["username"];
$con=mysqli_connect("localhost","root","pass","Testproject");

// Check connection
if (mysqli_connect_errno($con))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }


$sql = mysqli_query($con,"SELECT * FROM registeredusers where Username=".$username);
  $row = mysqli_fetch_array($sql);

  if (!$row) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

and am getting the following errors:

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in "Filepath goes here"/AddEvent.php Error: Unknown column 'Tom' in 'where clause'

"Tom" in this case is the user name. Any ideas how to fix this? I've looked at similar questions on stackoverflow, but majority of them are a little more complex or aren't trying to get a single record.

EDIT: I've change the query to the following:

  $sql = mysqli_query($con,"SELECT * FROM registeredusers") or die(mysqli_error($con));
  $row = mysqli_fetch_array($sql);

And added this as well"

$row_cnt = $result->num_rows;
 printf("Result set has %d rows.\n", $row_cnt);

Im getting the following:

"Result set has 0 rows".

I've typed the exact query into my DBMS and it returns many rows.

11
  • DO NOT use string interpolation or concatenation to add user data to your queries. You must properly escape your values to avoid SQL injection bugs. mysqli makes this easy with bind_param. Commented Dec 14, 2013 at 20:10
  • try this mysqli_query(...) or die(mysqli_error(); what error it throws or simply put check of mysqi_num_rows() > 0 then mysqli_fetch_array() Commented Dec 14, 2013 at 20:10
  • 1
    Change your query to use quotes: where Username='$username') -- but note that this code is vulnerable to SQL injection. You should use paramaterized queries instead. Commented Dec 14, 2013 at 20:10
  • stackoverflow.com/questions/11309187/… Commented Dec 14, 2013 at 20:20
  • Ok, I added "or die(mysqli_error($con))" and get the following: Unknown column 'Tom' in 'where clause' Commented Dec 14, 2013 at 20:35

1 Answer 1

1

You are missing quotes for $username and is vulnerable for SQL injection. I suggest you to bind the variable, so MySQLi will do the quoting and protect you from SQL injection:

$sql = "SELECT * FROM registeredusers where Username = ?";
if ($stmt = $con->prepare($sql)) {
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $results = $stmt->get_result();
    $row = mysqli_fetch_array($results);
    var_dump($row);
}
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.