0

I'm trying to execute a simple mySQL query in a php page, and I keep getting this error : "Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in..." even though the query returns a result in mysql workbench. This is my code:

<?php
$con=mysqli_connect("localhost","root","","eshkol");
// Check connection

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  $sql1="SET Names utf8";

 $sql = mysql_query("SELECT * FROM student WHERE idStudent=2");
    $r = mysql_fetch_array($sql);
    echo $r["idStudent"];



if (!mysqli_query($con,$sql1))
  {
  die('Error hebrew: ' . mysqli_error($con));
  }
if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "success";

mysqli_close($con);
?>

What am I doing wrong here?

0

1 Answer 1

5

You're mixing mysql_* and mysqli_* functions.

$sql = mysql_query($con, "SELECT * FROM student WHERE idStudent=2");
$r = mysql_fetch_array($sql);

should be

$sql = mysqli_query($con, "SELECT * FROM student WHERE idStudent=2");
$r = mysqli_fetch_array($sql);

What's interesting is you're using them just below that code:

if (!mysqli_query($con,$sql1))
  {
  die('Error hebrew: ' . mysqli_error($con));
  }
if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }

You probably want to combine the two to clean up your code:

$sql = mysql_query($con, "SELECT * FROM student WHERE idStudent=2");
if (!$sql) {
    die('Error: ' . mysqli_error($con));
}
$r = mysql_fetch_array($sql);
Sign up to request clarification or add additional context in comments.

5 Comments

Thank, That works, but I'm still getting this error "Warning: mysqli_query() expects parameter 2 to be string, object given in..."
Make sure the query you provide is an actual query and not something else
It's an actual query, I don't follow you, @JohnConde
Apparently it is not a string but some sort of object. Do a _var_dump()` on that variable to inspect it closer.
I'm questioning this $sql1="SET Names utf8"; in conjunction with if (!mysqli_query($con,$sql1)) --- Is that "legal"?

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.