Getting elements of the array MySQLi + PHP - php

Trying to get array from using MySQLi and PHP, so that I could work with each element of the array (like $array[0], array[1])
$titlesquery = $db->prepare("SELECT title FROM books WHERE id = ?");
$titlesquery->bind_param('i', $id);
$titlesquery->execute();
$titlesquery->bind_result($returned_title);
$json = $titlesquery->fetch($returned_title, MYSQLI_ASSOC);
echo json_encode($json);
This doesn't work. I get such warning:
mysqli_stmt::fetch() expects exactly 0 parameters, 2 given
If it helps, just $titlesquery->fetch(); works fine but I get not a kind of array(?) structure, just single element for that column. What is my mistake?

Like what exactly says on the error message, it needs no parameters:
http://php.net/manual/en/mysqli-stmt.fetch.php
bool mysqli_stmt::fetch ( void )
$titlesquery->bind_result($returned_title);
$titlesquery->fetch();
$json = array('title' => $returned_title);
After you have invoked ->bind_result(), this already binds results from your prepared statement.
If you want an array row fetching and this is available to you (needs mysqlnd), use ->get_result() instead.
$titlesquery = $db->prepare("SELECT title FROM books WHERE id = ?");
$titlesquery->bind_param('i', $id);
$titlesquery->execute();
$result = $titlesquery->get_result();
$json = $result->fetch_assoc();
echo json_encode($json);

Related

PHP bind_param not binding parameter [duplicate]

This question already has answers here:
MySQLI Prepared Statement: num_rows & fetch_assoc
(5 answers)
Closed 5 years ago.
I am trying to search a table for specific items using a prepared statement in PHP. I am getting no errors, but also getting no record. Here is my code:
$items = [];
$search = "john";
if ($stmt = $this->con->prepare("SELECT * FROM phptest WHERE search = ?")) { //'john'";
$stmt->bind_param("s",$search);
$stmt->execute();
while ($row = mysqli_fetch_array($stmt)) {
$item = [];
$item['id'] = $row['id'];
$item['first'] = $row['search'];
$item['last'] = $row['data'];
array_push($items, $item);
}
}
return $items;
Now, when I don't use a prepared statement, and just SELECT * FROM phptest I get all the results in the table (including the item where search = 'john'). Furthermore, if I use the query SELECT * FROM phptest WHERE search = 'john' I get the one record where search = 'john'
But as soon as I turn it into the prepared statement, I get zero errors but zero records. I do get a warning:
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
Which made me think my bind_param or execute() was returning FALSE, but when I check, it does not appear to be returning false.
I started off my adventure working through the tutorial https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/, which I thought I understood fully but ran into my error when trying to make my own PHP API.
I then went to the manual http://php.net/manual/fr/mysqli.prepare.php, but still cannot find my error.
Though it has been closed as "off-topic," I have reviewed PHP bind_param not working and found nothing applicable to my situation.
Likewise, I am not finding the error in PHP bind_param not defined nor php bind_param is not working.
You're very close. mysqli_fetch_array() expects to be passed a result object, not the statement object itself:
$stmt = $conn->prepare(...);
$stmt->bind_param(...);
$stmt->execute();
$result = $stmt->get_result();
while ($row = mysqli_fetch_array($result)) {
Or, in the fully OO manner:
while ($row = $result->fetch_array()) {

cannot get results from prepared statement's fetch()

This is my code
I tried replacing SELECT * with SELECT booktitle. If I do fetch(PDO::FETCH_BOTH) , that is the default, I get Warning: mysqli_stmt::fetch() expects exactly 0 parameters, 1 given in C:\Apache24\htdocs\phpprepared.php on line 89. I guess I dont have to bind_param, since there are no params here.
$query3 = 'SELECT * FROM books';
$stmt = $db->prepare($query3);
$stmt->execute();
while ($row = $stmt->fetch()) {
echo 'booktitle: '.$row['booktitle'].'<br>';
}
The problem
I get the booktitle string echoed 9 times, but no actual data. I am confused on how to use the fetch, the results and/or the associative (?) array so I can get the data. Thanks
Edit
Wondering if there is a way to simply get everything from a table without having to use bind_result or the combination get_result - fetch_assoc.
Thanks

php Prepared Statement giving me JSON Malformed

My php code works fine when it is not a prepared statement - however when it is a prepared statement it is giving me a json malformed error. After debugging my code for some time I have realised that there is something wrong with my if statement and that it should be different when it is a prepared statement. I am not sure what to change but this is my code:
$statement = "SELECT userID, forename, surname, email, age FROM employees WHERE forename = ?"
$outcome = $conn -> prepare($statement);
$outcome->bind_param('s', $forename);
$outcome->execute();
$outcome->close();
$outcomearray = array();
echo json_encode("It works as of now"); // This bit works and the message is echoed
// From this point, it is giving me errors and problems
if(mysqli_num_rows($outcome)){
while($line = mysqli_fetch_assoc($outcome)){
$outcomearray[] = array
(
"userID" => $line["userID"],
"forename" => $line["forename"],
"surname" => $line["surname"],
"username" => $line["username"],
"email" => $line["email"],
"age" => $line["age"]
);
}
echo json_encode($outcomearray);
}
It is the following two lines:
if(mysqli_num_rows($outcome)){
while($line = mysqli_fetch_assoc($outcome)){
that I believe are giving the errors.
How do I fix this?
$stmt = $conn->prepare(
"SELECT userID, forename, surname, email, age FROM employees WHERE forename = ?"
);
$stmt->bind_param('s', $forename);
$stmt->execute();
$rows = array();
$result = $stmt->get_result();
while($line = $result->fetch_assoc()){
$rows[] = $line;
}
print json_encode($rows);
$conn->close();
Note that this is the typical pattern when you are returning JSON resonses. If there is no match you render an empty array - thus there is no real need to check the number of rows.
If you for whatever reason needed to you can get the number of rows from the num_rows property on the mysqli_result object:
$result = $stmt->get_result();
if ((bool) $result->num_rows) {
}
Also note that the whole point of fetch_assoc is to get an associative array. So if your column names line up with the JSON you want to produce there is no need to map the keys one by one.
http://php.net/manual/en/class.mysqli-result.php
Try use
$outcome->num_rows;
OR
mysqli_stmt_num_rows($outcome);
Also use
$outcome->bind_result('userID','email', 'age', 'surname', 'forename');
$outcome->fetch()
instead
mysqli_assoc_fetch()

PHP PDO Select Query Results

This seems like it should be a very easy task, but I'm not sure it is.
I would like to use PDO to do a SELECT query, and then immediately after find out if there are any results (rows), and if so how many.
I'd like to fetch the result as an object not an array, as I like the $obj->col_name syntax, and it just feels a bit wrong to return an array just to find the above out.
$qryh = $conn->query("SELECT ...");
Then use $qryh to first find out if there are any rows, and if so how many.
Can this be done without falling back to using arrays..?
UPDATE:
I know about rowCount(), but I think it only works on UPDATE, INSERT and DELETE - my question relates to SELECT.
UPDATE 2:
I'm using SQL Server and MS Access, not MySQL, and rocount() does not work.
SOLUTION FOUND
The accepted answer lead to the solution. Here is what I found:
I was setting the PDO::ATTR_CURSOR option to PDO::CURSOR_SCROLL when creating the PDO object (new PDO(...), which returned -1 on a rowCount(). However if I set the cursor within ->prepare(... using an array (array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)) it works and returns the row count.
http://technet.microsoft.com/en-us/library/ff628154(v=sql.105).aspx
So, the example on the above link works, setting the cursor when you create the PDO object doesn't work. Also note that in the 'remarks' section on the above link, it mentions PDO::CURSOR_SCROLLABLE which doesn't for me (I get Undefined class constant 'CURSOR_SCROLLABLE').
Try this way:
$query = "select * from ...";
$stmt = $conn->prepare( $query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
print $stmt->rowCount()
Should work
$stmt = $conn->query('SELECT ...');
// number of rows:
$rows = $stmt->rowCount();
// get an array with objects:
$objects = $stmt->fetchAll();
// another way to count the results:
$rows = count($objects);
This is what I do in my database class:
$stmt = $conn->prepare('SELECT ...');
$stmt->execute();
$arrayOfObjects = $stmt->fetchALL(PDO::FETCH_OBJ);
$numberOfRows = count($arrayOfObjects);
print $numberOfRows;
By passing PDO::FETCH_OBJ each object is an stdClass meaning you can use the -> syntax.
I believe this is what you are looking for, and it just uses the PHP count() function instead of mySQL rowCount().
If you want more context, here is the DB class I use in all of my projects: https://gist.github.com/pxlsqre/9f6471220ef187343f54
You're right, PDO::rowCount does not work properly with SELECT
One workaround is to Add the count to your query
$qryh = $conn->query("SELECT COUNT(*) as numRows FROM Table");
$result = $qryh->(PDO::FETCH_OBJ);;
$count = $result->numRows;
$qryh->fetchColumn()
Returns the number of rows selected through a SELECT query

PDO fetchAll() returns empty array

I'm executing a simple query, without bound parameters, using PDO. I have tested it directly against my database and it executes cleanly, returning the expected results. However, when I plug it in to my PDO object and call fetchAll(), it returns an empty array.
$query = 'SELECT count(*) as mycount FROM mytable';
$mysql = $connection->prepare($query);
$result = $mysql->fetchAll();
print_r($result);
Expected result:
array
(
[mycount] => 8
)
Actual result:
array
(
)
Any ideas what might be causing this, or how to go about troubleshooting this?
You've prepared, but haven't executed the statement. You need
$mysql->execute();
first
First you need to:
$mysql->execute();
Then you can
$result = $mysql->fetchAll();

Categories