PDO Echo 10 values order by descending - php

I'm trying to echo out 10 numbers from my database in descending order sort of like a Highscores table.
This is my code
$conn = new PDO("mysql:host=HOST;dbname=NAME", "NAME", "PASSWORD");
$hs = $conn->query("SELECT exp FROM login ORDER BY number DESC LIMIT 10");
<? echo $hs?>
I'm new to PDO/PHP I didn't get any errors it just doesn't print anything from my table its just blank ;/

you have to fetch the results in a array, and then echo the elements of the array.
$db = new PDO("mysql:host=$db_hostname;dbname=$database", $db_username, $db_password);
$sql = "SELECT exp FROM login ORDER BY number DESC LIMIT 10";
if ($stmt = $db->query($sql)) //PDO::query() returns a PDOStatement on success or false on failure.
{
//If we got a PDOStatement as a return value from PDO::Query() fetch the results and echo.
if($numbers = $stmt->fetchAll(PDO::FETCH_ASSOC)) //This will fetch all results in associative array.
{
//If the array contained data, then echo them.
foreach ($numbers as $num)
{
echo $num['exp'] . "<br />";
}
}
else
{
//If the PDOStatement returned an empty array. Let us know.
echo "No data in the array";
}
}
else
{
//If PDO::Query returned false, then something is wrong with our query. Or connection or whatever.
echo "Query failed.";
}
In queries that return large results I wouldn't use $stmt->fetchAll().
I would use fetch in a while loop like this:
$db = new PDO("mysql:host=$db_hostname;dbname=$database", $db_username, $db_password);
$sql = "SELECT exp FROM login ORDER BY number DESC LIMIT 10";
if ($stmt = $db->query($sql)) //PDO::query() returns a PDOStatement on success or false on failure.
{
//If we got a PDOStatement as a return value from PDO::Query() !!!ECHO WHILE FETCHING!!!
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) //This loop will keep going for as many rows as the PDOStatement returns.
{
echo $row['exp'] . "<br />";
}
}
else
{
//If PDO::Query returned false, then something is wrong with our query. Or connection or whatever.
echo "Query failed.";
}
The difference between the first code chunk and the second is that in 1st chunk, we fetch all the results in a array and print them. In the second one tho, we print the data as we retrieve them one by one with PDOStatement::fetch()

You need to fetch the data from the object. I'll provide a link rather than code that will be helpful to you.
It should give you good introduction. It covers your question.
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers#Running_Simple_Select_Statements

Related

php get_result() returns an empty result set

So, I have a prepared statement that I have successfully prepared, bound, and executed:
SELECT * FROM users WHERE email = ? AND pass = SHA1(?)
It looks like one row is returned, as expected. However, why is the $result variable empty when I call #$stmt->get_result()? Thanks in advance.
$num_rows = mysqli_num_rows($stmt->get_result());
if ($num_rows == 1) {
// Fetch the result set
$result = $stmt->get_result();
//if result empty echo false
if(empty($result)) {
echo "result is empty";
}
}
Just to put the two comments together and elaborate a litte....
<?php
$result = $stmt->get_result();
$num_rows = mysqli_num_rows($result);
if ($num_rows == 1) {
// already fetched the mysqli_result
// now lets fetch the one record from that result set
$row = $result->fetch_assoc();
// ....do something with row
}
else {
// either 0 ...or more than 1 row
foo();
}
But you can even get rid of the call to mysqli_num_rows() (so it also works in case of unbuffered queries)
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ( !$row ) {
// no such record
foo();
}
else {
// ....do something with row
// might want to check whether there are more matching records
// given the context there shouldn't, but ...
}

PDO query returns result, but i cant fetch it

Hello im trying out PDO and im stucked in a weird situation.
$statement->fetch()
returns me the desired results, but when i try to fetch em , while doesnt seem to work. I tried use $statement->fetchAll() with foreach but it doesnt work either.
I also tried fetch(PDO::FETCH_ASSOC) but again no luck. AM i doing something wrong ?
$pdoObject = new PDO("mysql:host=$dbhost;dbname=$dbname;", $dbuser, $dbpass);
$pdoObject -> exec("set names utf8");
$sql="SELECT * from prokiriksi_clean where name=:name";
$statement = $pdoObject->prepare($sql);
$statement->execute(array(':name' =>$clean));
$testyo=$statement->fetch();
var_dump($testyo); //returns array
if ($statement->fetch()){
echo 'inside if'; //it is printed
while ($record = $statement->fetch()) {
var_dump($record); //doesnt print
echo 'inside while'; //doesnt print
}
}
The problem is that you don't save the results of your first $statement->fetch(), so you skip the first row of your results. Given the way you have written your query, it looks like you only have one row, so you have nothing to loop over after that first row. Thus, the while never runs.
Remove the if and just do the while ($record = $statement->fetch()) loop:
while ($record = $statement->fetch()) {
var_dump($record);
echo 'inside while';
}
If you need to verify that you have any results before doing the loop, you can use the procedure described in the documentation or simply use a counter to see if the loop ran, like this:
$rows = 0;
while ($record = $statement->fetch()) {
var_dump($record);
echo 'inside while';
$rows++;
}
if ($rows) {
echo "Processed $rows rows\n";
} else {
echo "Oops! No data!\n";
}
When doing your if statement, you're fetching the result of your query, so you cannot fetch it a second time. Check this thread to perform multiple fetches: PDO multiple fetching of same query

Having trouble getting my head around fetch_assoc()

sorry but complete newbie to php and mysqli. I have this in my code:
$sql = "SELECT tutorial_title, tutorial_author FROM tutorial_info WHERE tutorial_id<=3;";
$result = $conn->query($sql);
if($result===FALSE) {
echo "Select failed <br>";
}
else {
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Tutorial Title: " . $row["tutorial_title"]. " - Name: " . $row["tutorial_author"]. "<br>";
}
} else {
echo "0 results";
}
This works fine but I don't understand how the line while($row = $result->fetch_assoc()) works. From what I understand it fetches an array so I have something like while($row=$somearray). Why does this iterate though all the rows though? Does fetch_assoc() have a loop built in that iterates though all the rows and returns one at a time?
THere are different answer but one is:
mysqli_fetch_assoc — Fetch a result row as an associative array.
Also, Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in resultset.
Read mysqli_fetch_assoc in detail.

Struggling with prepared statements

I am unable to get the following working. I want to use prepared statements in the example below, but I am getting an error. The function defnitily gets passed the correct value in $array:
private function getInfoFromSystem($array) {
try {
$sql = "
SELECT
PCO_AGENT.NAME,
PCO_INBOUNDLOG.LOGIN AS LOGINID,
PCO_INBOUNDLOG.PHONE AS CALLERID,
PCO_INBOUNDLOG.STATION AS EXTEN,
PCO_INBOUNDLOG.TALKTIME AS CALLLENGTH,
PCO_INBOUNDLOG.CHANNELRECORDID AS RECORDINGID,
PCO_SOFTPHONECALLLOG.RDATE,
PCO_INBOUNDLOG.RDATE AS INBOUNDDATE
FROM
PCO_INBOUNDLOG
INNER JOIN
PCO_LOGINAGENT ON PCO_INBOUNDLOG.LOGIN = PCO_LOGINAGENT.LOGIN
INNER JOIN
PCO_SOFTPHONECALLLOG ON PCO_INBOUNDLOG.ID = PCO_SOFTPHONECALLLOG.CONTACTID
INNER JOIN
PCO_AGENT ON PCO_LOGINAGENT.AGENTID = PCO_AGENT.ID
WHERE
LOGINID = :extension
";
$arr = array(":extension" => $array['extension']);
$query = $this->mssql->prepare($sql);
$query->execute($arr);
// $sql = "select * from sys.messages where message_id = 229";
foreach($this->mssql->query($sql) as $row) {
echo "<pre>";
print_r($row);
echo "</pre>";
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
You should not be calling query() after execute(). Instead you need to fetch() your rows:
$query = $this->mssql->prepare($sql);
$query->execute($arr);
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo "<pre>";
print_r($row);
echo "</pre>";
}
// OR rather than the fetch loop above, use fetchAll()
$rowset = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($rowset);
In my experience with PDO + MSSQL, attempting to call a regular query immediately after calling execute() on a statement that returns rows will fail unless you have called $query->closeCursor() first. However, in this case, you should not be calling query() at all. You've already executed your statement with bound params, and just need to fetch rows from it.

Display mysql data in php function

Ok i got a problem now i want to display a data from the database and display it through a function now how do i do that??
like i have fetched a row from the database and its name is $row_field['data']; and it is correct now i have assigned a variable to it like this $data = $row_field['data']; now if i call it in a function it shows undefined variable even after i assigned it global in the function like this
function fun(){
global $data;
echo $data;
}
but if i assign it a value like 1 or 2 or anything it gets displayed without any error why is that so??
If it displays if you assign it a value like 1 or 2 while still in the global scope, then I can only assume that your database did not return the result you thought it did. Does the database value display if you echo it out outside of the function?
Global is evil. I dont know what you are trying to do, but why dont you just do the query in the function itself?
If you have a column named data and your php call was something like
$result = mysql_query("SELECT data FROM mytable");
while ($row_field = mysql_fetch_assoc($result, MYSQL_NUM)) {
...
}
Then you could replace ... with print $row_field['data'].
Else please provide a snippet of your code where you query the db and retrieve the result.
When learning php try to start with simple things. For example in order to get some data from a database follow the examples from php website.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
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["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
If all this goes well go a little further change a little the while loop.
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$myArray[] = $row;
}
mysql_free_result($result);
// now you can start playing with your data
echo $myArray[0];
Small steps...

Categories