Select the most recent 5 rows based on date - php

I haven't touched PHP in a while and trying to select the 5 most recent entries in my database and print them to screen.
I see mysql command isn't recommended anymore and to use PDO->mysql instead.
My query is something like this:
SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5;
I'm assuming I would have to put the values into an array and create a loop and output the results.
<?php
$db = new PDO('mysql:dbhost='.$dbhost.';dbname='.$dbname, $user, $pass);
while () {
print($title[$i], $date[$i], $author[$i]);
$i++
}
$db = null;
?>
I'm stuck filling in the gaps with the above code.
Update: The $db = new PDO.... line is reporting an error message:
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] Can't connect to local MySQL server through socket... in /var/...
PDO is confirmed to be installed and enabled. My other web apps on the server can connect to the same remote mysql server fine.

<?php
$host = 'localhost'; $db = 'db-name'; $user = 'db-user'; $pw = 'db-password';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
<?php
$sql = "SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5";
$query = $conn->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
?>
<?php do {
// print your results here ex: next line
echo 'Title: '.$row['title'].' Date: '.$row['date'].' Author: '.$row['author'].'<br>';
} while ($row = $query->fetch(PDO::FETCH_ASSOC)); ?>
Don't forget to close and release resources
<?php $query->closeCursor(); ?>
EDIT
I recommend not echoing error messages once you have confirmed your code functions as expected; however if you want to simply use plain text you can do this...
You can add this to your connection block...
if ($conn->connect_error) {
die("Database Connection Failed");
exit;
}
You can also change your query block...
try {
$sql = "SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5";
$query = $conn->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die("Could not get the data you requested");
exit;
}
Again, it is recommended that errors not be echoed. Use error checking only for debugging.

<?php
$db = PDO('mysql:dbhost=$dbhost;dbname=$dbname', $user, $pass);
$sth = $db->prepare("SELECT id,title,date,author FROM table ORDER BY date LIMIT 5");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
?>
in a loop:
while($row = $sth->fetch()) {
echo $row['column'];
}
From the documentation: http://php.net/manual/en/pdostatement.fetch.php

Related

How to select data from 'logged in user' from database to a graph

I need help with some code. I want to select data from mySQL to a graph on my web page.
The data must be from the current logged in user, and when I select data to a card it works fine, but when I select it to a graph the graph disappears.
I'm using this code for the cards, and it works fine:
$sql = "SELECT energyexpenditure FROM energy4project WHERE user_id = '{$_SESSION["user_id"]}' ORDER BY time_stamp DESC LIMIT 1;";
This is the code for my current graph that don't show data based on logged in user:
<?php
header('Content-Type: application/json');
$host = "localhost";
$user = "`blabla";
$pwd = "blabla";
$db = "blabla";
$conn = new mysqli($host, $user, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT energyexpenditure, time_stamp FROM energy4project ORDER BY time_stamp DESC LIMIT 7;";
$result = $conn->query($sql);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
echo json_encode($data);
?>
When I implement the code from the cards in the graph code it doesn't work.
Why does the SELECT WHERE user = '{$_SESSION["user_id"]} not work in the graphs?
If I understood good your Mysql query return an empty result. Try to modify your code as follows:
if(!$result = $conn->query($sql)) {
echo "query error.";
die();
}
$data = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$data[] = $row;
}
/* free result set */
$result->free();
/* close connection */
$conn->close();
//uncomment the below line if you want to check de result of your mysql query because it seems be good.
//var_dump($data); die(); echo "<pre>";
echo json_encode($data);
So if you don't have any mysql error, verify your database name, table name are correctly and if it has data in your table.
Reference: https://www.php.net/manual/en/mysqli-result.fetch-array.php
Regards

Can't retrieve data from MS SQL with PDO

I use PDO on my local computer to connect to MS SQL server to use prepare statements. The driver is installed properly and can connect to database. Here's the code:
try {
$con = new PDO("sqlsrv:Server={$host};Database={$db_name}", $username, $password);
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$query = "SELECT TOP 10 ClientID FROM CLIENT";
$stmt = $con->prepare($query);
$stmt->execute();
$num = $stmt->rowCount();
print $num;
From SSMS the query returns as it should, but nothing from the code as it prints -1 as the result of $num. If i change the query to SELECT ##VERSION it prints the version properly but not my query. My query is right from SSMS and PDO can connect to server but can't figure out where the problem is it's so frustrating please help.
can you try :
try {
$con = new PDO("sqlsrv:Server={$host};Database={$db_name}", $username, $password);
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$query = "SELECT TOP 10 ClientID FROM CLIENT";
$stmt = $con->prepare($query);
$stmt->execute();
$rows = $stmt->fetchAll();
$num = count($rows);
print $num;
// To print results :
foreach ($rows as $row) {
echo $row["ClientID"] . "<br/>";
}

How to wite PHP code with the following SQL query?

I am trying to query out a result, it works in SQL query, but I'm trying to get the result using PHP
SELECT prs_amtdb FROM `prs` WHERE prs_amtcrck = 0
Using mysqli
Note: Make sure you bind your value. mysqli does not automatically
secure your query
$connection= mysqli_connect($host, $user, $password, $database);
$query="SELECT prs_amtdb FROM prs WHERE prs_amtcrck = 0";
$result= mysqli_query($connection, $query);//$connection is your database
//connection
//fetch the result
while($row= mysqli_fetch_array($result)){
echo $row['column_name'].'<br/>';
}
Using PDO:
$query = $db->query("SELECT `prs_amtdb` FROM prs WHERE `prs_amtcrck` = 0");
$results = $query->fetchAll();
foreach($results as $result) {
echo $result;
}
http://php.net/manual/en/pdo.query.php
If you have user input that you're using in your query you should always use prepared statements eg:
$query = $db->prepare("SELECT `prs_amtdb` FROM prs WHERE `prs_amtcrck` = :atmcrck");
$query->bindParam(':atmcrck', 0); // 0 will be the user input
$query->execute();
$results = $query->fetchAll();
foreach($results as $result) {
echo $result;
}
Make sure you have a database connection setup in PDO:
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
die($e->getMessage());
}
http://php.net/manual/en/pdo.connections.php

PDO mySql Connection

There is a link that I found a while back. What I would like to know is:
How do I query a simple SELECT * FROM table_name using PDO?
I tried playing around with the examples here but I was not getting any results back. All along I have been using the mysql_connect method which I dont want to use anymore. I would like to use following:
<?php
$host="127.0.0.1"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="microict-intrasys"; // Database name //
//$id = 5;
try {
$conn = new PDO('mysql:$host;$db_name,', $username, $password);
$stmt = $conn->prepare('SELECT version FROM system_info');
// $stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) )
{
foreach($result as $row)
{
print_r($row);
}
}
else
{
echo "No rows returned.";
}
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
?>
First create the pdo instance and connect...
$db = new PDO('mysql:host=127.0.0.1;dbname=yourDBName;charset=utf8', 'username', 'password');
I use charset as well to have the correct formated data here... but you dont have to use it. Connection string could also look like
PDO("mysql:host=127.0.0.1;dbname=yourDBName" , $username, $password);
(using $username & $password here)
since working with pdo i ran into speed issues when i use localhost instead of 127.0.0.1 PDO seems to use the DNS to translate localhost into 127.0.0.1 and this causes speed. And im talking about seconds just for connecting to DBs
after connecting you can query like
$stmt = $db->query("SELECT * FROM table");
and than fetch could results like
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['field1'].' '.$row['field2']; //etc...
}
or
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
so than you should have at least some result.... (simple way)
I guess your problem is...
accourdig to your source you have a issue in your connectionstring....
<?php
$host="127.0.0.1"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="microict-intrasys"; // Database name
//$id = 5;
try {
$conn = new PDO('mysql:host={$host};dbname={$db_name}', $username, $password);
// you neeeeeed this--^ and this--^
$stmt = $conn->prepare('SELECT version FROM system_info');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) )
{
foreach($result as $row)
{
print_r($row);
}
}
else
{
echo "No rows returned.";
}
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
?>
you are missing some in your connection string! kinda typo
your parsed string looks like
"mysql:localhost;microict-intrasys"
and thats wrong. it must look like
//"mysql:host=localhost;dbname=microict-intrasys"
"mysql:host=127.0.0.1;dbname=microict-intrasys" // better
PDO Check
if (!defined('PDO::ATTR_DRIVER_NAME')) {
echo 'PDO unavailable';
}

mysql_fetch_array within while loop is working in localhost but not working in host server

$result = mysql_query('SELECT * FROM phpfox_education_question where subject_id = 2 and ques_id =1');
var_dump($result);
//var_dump result is :- "resource(64) of type (mysql result)" in localhost and web host,but
while($row = mysql_fetch_array($result))
{
var_dump($row); //**NOTHING DISPLAYED in web host server but in localhost**
}
Give this a try:
$query = "SELECT * FROM phpfox_education_question WHERE subject_id = '2' AND ques_id = '1'";
$result = mysql_query($query) or die(mysql_error()); // <--- added this
echo "Results: ".mysql_num_rows($result)."<br />"; // <--- added this to output result count
while($row = mysql_fetch_array($result))
{
print_r($row); //**NOTHING DISPLAYED in web host server but in localhost**
}
This is used depreciated code btw
Try adding this:
var_dump(mysql_num_rows($result));
To see if there are any rows to be fetched, if not, that's your answer.BTW, in PDO this code looks like this:
$db = new PDO('mysql:dbname=default_db_name;host=127.0.0.1',$user,$pass);
//use prepared statmenets
$stmt = $db->prepare('SELECT * FROM your_db.phpfox_education_question WHERE subject_id = :subject_id AND ques_id = :ques_id');
//pass binds when executing the stmt
$stmt->execute(array(':subject_id' => 2, ':ques_id' => 1));
//number of rows found:
var_dump($stmt->rowCount());
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{//fetch rows as assoc array
var_dump($row);
}
Note that this is a basic example, there's a lot more you can do with PDO
Update:
To get more debugging info, try this:
try
{
$db = new PDO();//connect, pass correct data here
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//cause PDO to throw PDOExceptions on error
$stmt = $db->prepare('SELECT * FROM your_db.phpfox_education_question WHERE subject_id = :subject_id AND ques_id = :ques_id');
$stmt->execute(array(':subject_id' => 1, ':ques_id' => 2));
var_dump($stmt->rowCount());
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
var_dump($row);
}
}
catch(PDOException $e)
{
echo $e->getMessage();
$db = null;
return;
}
echo 'No problems with query<br/>';
$db = null;//disconnecto
Make sure no errors are being thrown, if there are, check the messages, find out what is going wrong and fix it. If you can't find a way to fix them, we're here to help, of course.

Categories