PHP SQL: Find smallest value using PDO - php

I am attempting to find the smallest value in my SQL records using a PDO connection. The records are varchar so must be converted to int in order to find smallest. I am stuck on this issue:
mysql_fetch_assoc() expects parameter 1 to be resource, array given
The problem is I do not know how to get a resource from a PDO connection. The query is valid.
<?php
//load and connect
require("config.inc.php");
//change varcar to ints and put into array
$query = "SELECT score FROM easy";
$stmt = $db->prepare($query);
$result = $stmt->execute();
$rows = $stmt->fetchAll();
$scoreArray = array();
$index = 0;
while($row = mysql_fetch_assoc($rows)){
$scoreArray[$index] = intval($row);
$index++;
}
$smallest = min($scoreArray);
$response["success"] = 0;
$response["message"] = "The min is: ".$smallest;
echo(json_encode($response));
?>

You need to convert your field to int.
find smallest value by means of SQL:
SELECT min(score) FROM easy
While selecting all the records from database and process them in PHP is NOT the way to go. It's against the very basic principles. Data mining is a job for database.
$query = "SELECT min(score) FROM easy";
$stmt = $db->prepare($query);
$result = $stmt->execute();
$min = $stmt->fetchColumn();

Don't use mysql_fetch_assoc when using PDO:
Replace
while($row = mysql_fetch_assoc($rows)){
with
foreach ( $rows as $row ){

Related

sql in database gives different result in php

I got the following sql:
SELECT COUNT(pu_id) FROM purchasing WHERE MONTH(pu_create_date)=MONTH(NOW())
In Mysql it gives the result 0 as expected.
When I put it in PHP I get the result 1 of $numMonth. This is the php code:
$database = new Database();
$db = $database->getConnection();
$stmt= $db->query('SELECT COUNT(pu_id) FROM purchasing WHERE MONTH(pu_create_date)=MONTH(NOW())') ;
$numMonth = $stmt->execute();
echo $numMonth;
Why do I get two different results?
pu_id = unique key
pu_create_date = timestamp
You have to fetch the row from the query.
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_NUM);
$numMonth = $row[0];
echo $numMonth;

PHP PDO - incremental for loop that fetches the next array row with each loop

I'm in the process of updating my old mysql database techniques to prepared pdo statements. I'm all good with while loops while($row = $result->fetch()) however how would I do the following with PDO prepared statements?
$sql = "SELECT * FROM table WHERE id=".$id;
$result = mysql_query($sql) or die(mysql_error());
$loop_count = mysql_num_rows($result);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = mysql_fetch_array($result);
echo $loop_row['field'];
}
I've tried this but with no joy:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_count = $result->rowCount();
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = $result->fetch();
echo $loop_row['field'];
}
Thanks!
UPDATE: The reason for using a for loop instead of a while loop is the ability to paginate the results, otherwise I would just put LIMIT 7 on the end of the SQL query.
To properly count rows with PDO you have to do this -
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];
But you would be better off using LIMIT in your query if all you want to do is get a static number of results.
In addition you're making your loop overly complex, there is no need to test for a range in the for condition just set the static number unless you're doing something weird, like possibly pagination.
You can try it this way:
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_rows = $result->fetchAll();
$loop_count = count($loop_rows);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
echo $loop_rows[$row]['field'];
}
As requested by the OP, here's an example of PDO prepared statements using LIMIT and OFFSET for pagination purposes. Please note i prefer to use bindValue() rather than passing parameters to execute(), but this is personal preference.
$pagesize = 7; //put this into a configuration file
$pagenumber = 3; // NOTE: ZERO BASED. First page is nr. 0.
//You get this from the $_REQUEST (aka: GET or POST)
$result = $conn->prepare("SELECT *
FROM table
WHERE id= :id
LIMIT :pagesize
OFFSET :offset");
$result->bindValue(':id', $id);
$result->bindValue(':pagesize', $pagesize);
$result->bindValue(':offset', $pagesize * $pagenumber);
$result->execute();
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
This gives you the complete resultset of rows, limited to your required page. You need another query to calculate the total number of rows, of course.
What you could try is:
//Get your page number for example 2
$pagenum = 2;
//Calculate the offset
$offset = 7 * $pagenum;
//Create array
$data = array();
$result = $conn->prepare("SELECT * FROM table WHERE id= ? LIMIT 7 OFFSET ?");
$result->bind_param("ii", $id,$offset);
$result->execute();
$resultSet = $result->get_result();
while ($item = $resultSet->fetch_assoc())
{
$data[] = $item;
}
$result->close();
//echo resultSet you want
var_dump($data);

How can I get all id's from a database column into one single array?

How can I fetch all the values from columns (like an id column) and put them into an array?
I'm using PDO API and I tried with other code, but it's not working for me.
$STH = $DBH->query('SELECT Tid from Playlist ');
$STH->setFetchMode(PDO::FETCH_OBJ);
$result = $STH->fetch();
while($result = mysql_fetch_array($result)) {
$ids_array[] = $result['Tid'];
}
You can directly return an id array by specifying the PDO::FETCH_COLUMN.
$stmt = $DBH->query("SELECT Tid from Playlist");
$ids_array = $stmt->fetchAll(PDO::FETCH_COLUMN);
You are mixing mysql_* and PDO, which is obviously not going to work.
Just fetchAll() your results and then just merge all rows into one array by simply looping through all rows with array_map() and returning the id, e.g.
$stmt = $DBH->query("SELECT Tid from Playlist");
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
$ids = array_map(function($v){
return $v->Tid;
}, $result);
print_r($ids);

Get result out of query [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
I am looking for the result out of a query, but it keeps giving me resource id #3.
The following is my code.
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
print_r($typeResult);
What step am I missing here?
You need to fetch the result. All you're doing is sending the query.
Be aware that if you are writing new code, you should use mysqli_ or PDO functions as your query is vulnerable to SQL injection and mysql_ functions are being deprecated. Hesitantly, below is a sample for mysql_fetch_assoc.
<?php
$sql = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row[sellingid];
}
mysql_free_result($result);
?>
Reference
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
$row = mysql_fetch_array($typeResult);
print_r($row);
More clear hint - use MySQLi class/functions, read this:
http://lt1.php.net/manual/en/mysqli-result.fetch-assoc.php
or if you like OOP approach more then
http://lt1.php.net/manual/en/mysqli-result.fetch-object.php
You are not actually fetching the results of your query. Below are two examples that use WHILE loops to fetch the results as rows. You can then grab the column values and work with them.
Incorrect and depreciated method, but working:
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
// for each row
while ($row = mysql_fetch_array($typeResult)) {
// grab the columns
$value = $row['column_name'];
}
I would recommend using MySQLi or PDO like to following (MySQLi):
$mysqli_connection = new mysqli("hostname", "username", "password", "database");
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$res = $mysqli_connection->query($type);
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$value = $row['column_name'];
}
$res->free();
$mysqli_connection->close();

Pulling Data from a Mysql Table Field and putting it into an array

I can find lots of tutorials showing you how to load an array into a database field but can't seem to figure out how to pull each entry in a field into an array as seperate items. Seems simple enough just can't get it to work, any help?
If using the modern PDO library, use the PDOStatement->fetchAll() function with the fetch_style parameter set to PDO::FETCH_COLUMN.
Based on a sample from that page:
$sth = $dbh->prepare("SELECT field FROM dbtable");
$sth->execute();
$array = $sth->fetchAll(PDO::FETCH_COLUMN);
If using the old MySQL API (not recommended, example omits error checking)
$array = array();
$result = mysql_query("SELECT field FROM dbtable");
while ($row = mysql_fetch_row($result)) {
$array[] = $row[0];
}
mysql_free_result($result);
$big_2_dimensional_array_of_data;
foreach ($big_array_of_data as $row) {
$query = "INSERT INTO table_name (field1, field2, ...) VALUES($row[0], $row[1], ...)
mysql_query($query);
}
Something like that I think
after reading his question a few times, i guess what he wants to do is something like this:
$query = "SELECT field1, field2, ... fieldn FROM table;";
$r = mysql_query($query,$conn);
$row = mysql_fetch_assoc($r);
i'm still not quite sure what it is he exactly wants...
My interpretation of this question is that the questioner has inserted a number of rows into a table, and isn't sure how to handle getting them out other than one at a time. (It's possible that the question might also be referring to data serialized and then stuck into a single field... but I hope not!)
So, here's how to get multiple rows:
$query = "SELECT field1, field2, ... fieldn FROM table;";
$r = mysql_query($query,$conn);
$data = array();
while($row = mysql_fetch_assoc($r)) {
$data[] = $row;
}
You'd now have all the rows returned by your query in $data, so something like this would work to access it: $data[2]['field1']
The examples below assume your SELECT statement is stored in $select and your connection is stored in $db. A two-dimensional array of the results is stored in $rows afterward.
If you're using mysql (for mysqli procedures, just replace mysql_ with mysqli_):
$result = mysql_query($select, $db);
$rows = [];
while ($row = mysql_fetch_assoc($result) {
$rows[] = $row;
}
Using mysqli classes:
$result = $db->query($select);
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$result->close()
Using PDO:
$stmt = $db->query($select);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Categories