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

17
  • 2
    Well again I don't do PHP, but I would expect a prepare() function in any language to return an object. You are using it as an object yourself when you call the $sql->bind_param() method on the next line. Commented May 30, 2017 at 3:40
  • 2
    It looks like your are mixing mysqli and PDO syntax... Commented May 30, 2017 at 3:44
  • 2
    So what do you want to use mysqli or PDO ? HERE is a comparison article between the two. Commented May 30, 2017 at 3:51
  • 2
    You can use both in one site... But not both in the same request to DB ;) It is easier to choose one and get used to it. Commented May 30, 2017 at 4:01
  • 2
    No.. -> is an object operator... That is PHP. look here Commented May 30, 2017 at 4:04

3 Answers 3

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);
?>
Sign up to request clarification or add additional context in comments.

37 Comments

lolll My bad... json.encode($arrayTojson) sould be json_encode($arrayTojson)... Arrgg... so many similar syntax...
Let's give a try with what I got working for years... ;) PDO !!
Right!... lolll var is some JavaScript deformation in my brain. remove var in front of $result_array. I edited.
I added a "JUST TO DEBUG" line... Now accesse get.php directly... Like http://your-domain/get.php
What you don't know is always harder then what you know. ;) Don't feel cheap, it is the same for everyone. ;)
|
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);

21 Comments

The OP should keep the parameterized query.
No. It means you should keep this line: $sql->bind_param("s",$value); and keep the ? in the $sql string instead of $value.
Look at the "Security" example in the comparison article I gave you. ==> "mysqli, prepared statements"
@coffeebot PDO and mysqli both support parameterized queries, you need to use the manual for whichever driver you are using. php.net/manual/en/mysqli.quickstart.prepared-statements.php
@coffeebot: use the edited code. It should work. If not please let me know.
|
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);

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.