0

UPDATE at bottom of question

I'm getting the error:

Warning: mysqli_query() expects parameter 2 to be string, object given

Questions about this are incredibly common on Stack Overflow - my apologies in advance. I haven't been able to find a good answer for my specific problem. If there is a thread that addresses this, please let me know.

Here is my Ajax code:

    $.ajax({
        url: "get.php",
        type: "post",
        datatype: "json",
        data:{ ajaxid: altCheck }, //this is an integer passed to MySQL statement
        success: function(response){
            console.log(response);
        },
        error: function(){
            console.log("test");
        }
    });

get.php

<?php

$db = mysqli_connect("...", "...", "...", "...");

$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
var_dump($value); //checking to see what $value is at this point

$sql = $db->prepare("SELECT * FROM table WHERE screeningId = ?");
$sql->bind_param("s",$value);


//THIS LINE THROWS THE ERROR
$result = mysqli_query($db, $sql);
$temp = array();
while ($row = mysqli_fetch_array($result)){
    //output data
    array_push($temp,$row['imageURL']);
    }
echo json_encode($temp);
?>

The fourth line of code var_dump($value); outputs string(0).


UPDATE: MySQLi

<?php

$db = mysqli_connect("...", "...", "...", "...");

$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);

$query = $db->prepare('SELECT * FROM table WHERE screeningId = ?');
$query->bind_param('s', $_GET[$value]);
$query->execute();

if ($result = mysqli_query($db, $query)) {
    while ($url = mysqli_fetch_object($result, 'imageURL')) {
        echo $url->info()."\n";
    }
}

?>

Screenshot of MySQL table data columns:

enter image description here

rpivovar
  • 3,150
  • 13
  • 41
  • 79

3 Answers3

1

Since you are using mysqli_* all other place in your project, update your get.php as below.

<?php
$db = mysqli_connect("...", "...", "...", "...");

$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$value = mysqli_real_escape_string($db, $value);
//var_dump($value); //checking to see what $value is at this point

$sql = "SELECT * FROM table WHERE screeningId = '$value'";

$result = mysqli_query($db, $sql);
$temp = array();
while ($row = mysqli_fetch_array($result)){
    //output data
    array_push($temp,$row['imageURL']);
    }
echo json_encode($temp);

EDIT

With respect to bind param with mysqli,

<?php
$conn = new mysqli('db_server', 'db_user', 'db_passwd', 'db_name');


$sql = 'SELECT * FROM table WHERE screeningId = ?';
$stmt = $conn->prepare($sql);
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING);
$stmt->bind_param('s', $value);
$stmt->execute();
$res = $stmt->get_result();
$temp = array();
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
  array_push($temp,$row['imageURL']);
}
echo json_encode($temp);
Naga
  • 2,190
  • 3
  • 16
  • 21
  • 2
    The OP should keep the parameterized query. – chris85 May 30 '17 at 04:09
  • This got rid of all errors, thank you. Now I'm just getting an empty array output: `[ ]`. – rpivovar May 30 '17 at 04:11
  • @chris85 does that mean maybe I should do this whole thing in PDO? – rpivovar May 30 '17 at 04:12
  • echo $sql; and try run the printed query direct in the database and check it out. – Naga May 30 '17 at 04:14
  • 2
    No. It means you should keep this line: `$sql->bind_param("s",$value);` and keep the `?` in the $sql string instead of $value. – Louys Patrice Bessette May 30 '17 at 04:14
  • Replacing `$sql = "SELECT * FROM table WHERE screeningId = '$value'";` with `$sql = $db->prepare("SELECT * FROM table WHERE screeningId = ?"); $sql->bind_param("s",$value);` throws two errors – rpivovar May 30 '17 at 04:17
  • `Warning: mysqli_query() expects parameter 2 to be string, object given` and `Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given` – rpivovar May 30 '17 at 04:18
  • 2
    Look at the "Security" example in the comparison article I gave you. ==> "mysqli, prepared statements" – Louys Patrice Bessette May 30 '17 at 04:21
  • 2
    @coffeebot `PDO` and `mysqli` both support parameterized queries, you need to use the manual for whichever driver you are using. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php – chris85 May 30 '17 at 04:23
  • @LouysPatriceBessette looking at that example right now. Thanks. – rpivovar May 30 '17 at 04:28
  • I've updated my code above to be (I believe) all `mysqli` but still getting `Warning: mysqli_query() expects parameter 2 to be string, object given` – rpivovar May 30 '17 at 04:39
  • 1
    @coffeebot: use the edited code. It should work. If not please let me know. – Naga May 30 '17 at 04:50
  • It works in that there aren't any errors, but the output is `[ ]`, and trying this from the actual page outputs all of index.html – rpivovar May 30 '17 at 04:55
  • 1
    prinrt your query and try run direct in mysql server to check whether it has records or not. – Naga May 30 '17 at 05:00
  • Hmm, yeah, that seemed to produce results as it should. Weird. – rpivovar May 30 '17 at 05:07
  • then print_r($row); before array_push and amke sure the column names... – Naga May 30 '17 at 05:11
  • `print_r($row['imageURL']);` `array_push($temp,$row['imageURL']);` tried to add that before array_push, but it didn't print anything? I don't understand what's going on – rpivovar May 30 '17 at 05:16
  • `print_r($row);` not `print_r($row['imageURL']);` may be you don't have imageURL column in your table? – Naga May 30 '17 at 05:21
  • I've added a picture of all data columns from the MySQL table at bottom of question. Tried `print_r($row)`, and that doesn't seem to print anything either. – rpivovar May 30 '17 at 05:26
  • `screeningId` is of type integer. Does that make a difference at all? – rpivovar May 30 '17 at 05:37
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/145415/discussion-between-naga-and-coffeebot). – Naga May 30 '17 at 06:36
1

EDIT

Okay... 8 edits spent on mysqli... Enought!
Here is how I DO using PDO. And it WILL work first shot.
I have a separate file for the database connection info.

dbconnection.php:
(The advantage of the separate definition file is one place to update the user password when needed.)

<?php
// Database connection infos (PDO).
$dsn = 'mysql:dbname=[DATABASE_NAME];host=127.0.0.1';
$user = '[DATABASE_USER]';
$password = '[USER_PASSWORD]';


try {
  $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
  echo 'Connexion failed : ' . $e->getMessage();
}
?>

Now in your PHP files where a database request has to be done, include the PDO definition file, the just request what you want:

<?php
include('dbconnection.php');

// JUST TO DEBUG!!!
$_REQUEST['ajaxid'] = "1";

// Database request.
$stmt = $dbh->prepare("SELECT * FROM table WHERE screeningId = ?");
$stmt->bindParam(1, $_REQUEST['ajaxid']);
$stmt->execute();

if (!$stmt) {
   echo "\nPDO::errorInfo():\n";
   print_r($dbh->errorInfo());
   die;
}

// Looping through the results.
$result_array =[];
while($row=$stmt->fetch()){
  array_push($result_array,$row['imageURL']);
}

// The result array json encoded.
echo json_encode($result_array);
?>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
0

Select Data With PDO in get.php:

<?php 

    if( isset($_POST['ajaxid']) ) {
      $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $stmt = $conn->prepare("SELECT * FROM table WHERE screeningId = :screeningId"); 
      $stmt->execute(array(':screeningId' => $_POST['ajaxid']));
      $row = $stmt->fetch();
    }
?>

You configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $conn object:

$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Ali Hesari
  • 1,821
  • 5
  • 25
  • 51