-1

This is my code:

$con = mysqli_connect($databasehost,$dbname,$dbpassword) or die(mysql_error());
mysqli_select_db($con, $dbname) or die(mysql_error());
mysqli_query($con,"SET CHARACTER SET utf8");
$query = file_get_contents("php://input");
$sth = mysqli_query($con,$query);

if (mysql_errno()) {
    header("HTTP/1.1 500 Internal Server Error");
    echo $query.'\n';
    echo mysql_error();
}
else
{
    $rows = array();
    while($row = mysql_fetch_assoc($sth)){
        $rows[] = $r;
    }
    print json_encode($rows);
}

What's the problem?

This is the error:

[19-Jan-2018 09:17:39 UTC] PHP Warning:  mysql_fetch_assoc() expects parameter 1 to be resource on line 22
Gholamali Irani
  • 4,391
  • 6
  • 28
  • 59
  • mysqli_connect("$hostname","$username","$dbname","$password") you mixed mysql in mysqli – omkara Jan 19 '18 at 09:35
  • You cannot mix [`mysql`](http://php.net/manual/en/book.mysql.php) and [`mysqli`](http://php.net/manual/en/book.mysqli.php) functions. Besides that, **the `mysql` PHP extension is dead** -- Stop using the [`mysql_*()` PHP functions](http://php.net/manual/en/function.mysql-connect.php). They are old, deprecated since PHP 5.5 and completely removed in PHP 7. Use [`mysqli`](http://php.net/manual/en/book.mysqli.php) or [`PDO_mysql`](http://php.net/manual/en/ref.pdo-mysql.php) instead. Read the answers to [this question](https://stackoverflow.com/q/12859942/4265352) to learn more about why and how. – axiac Jan 19 '18 at 10:19

2 Answers2

0

You are mixing mysqli and mysql.

The latter is deprecated as of version 5.5.0.

Try using mysqli_fetch_assoc($sth) instead of mysql_fetch_assoc($sth)

See http://php.net/manual/en/mysqli-result.fetch-assoc.php also.

Doc
  • 177
  • 1
  • 3
  • 14
-1

Your problem is you are mixing mysqli and mysql.

Try to use mysqli_fetch_assoc($sth) instead of mysql_fetch_assoc($sth).

And, in mysqli_connect("host", "user", "password", "database"), you are missing the user name.

// (1) make sure $username is defined.
$con = mysqli_connect($databasehost,$username,$dbname,$dbpassword) or die(mysqli_error());

// check to use mysqli_, not mysql_
mysqli_select_db($con, $dbname) or die(mysqli_error());
mysqli_query($con,"SET CHARACTER SET utf8");
$query = file_get_contents("php://input");
$sth = mysqli_query($con,$query);

if (mysql_errno()) {
    header("HTTP/1.1 500 Internal Server Error");
    echo $query.'\n';
    echo mysql_error();
}
else
{
    $rows = array();

    // (2) Use mysqli_fetch_assoc instead of mysql_fetch_assoc.
    while($row = mysqli_fetch_assoc($sth)) {

        // (3) $r is not defined. Use $row.
        $rows[] = $row;
    }
    print json_encode($rows);
}