user2674835
user2674835

Reputation: 139

Mysql data retrieve in PHP

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?

Upvotes: 0

Views: 105

Answers (1)

John Conde
John Conde

Reputation: 219924

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);

Upvotes: 5

Related Questions