How to wite PHP code with the following SQL query? - php

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

Related

Select the most recent 5 rows based on date

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

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';
}

Windows Azure MaxSizeInByte Statement

i want to get the current max size of my DB. I have found the statements an checked it out. It works fine in VS2012 SQL Explorer. But when im using php im geting no data.
This is my function:
function getLoad() {
$conn = connect();
$string = 'DATABASEPROPERTYEX ( 'database' , 'MaxSizeInBytes' )';
$stmt = $conn->query($string);
return $stmt->fetchAll(PDO::FETCH_NUM);
}
The problem is that i get an error in fetching the $stmt. Error is:
can not fetchAll(11)
This code will print the database edition and max size in GB:
<?php
function get_database_properties($server, $database, $username, $password) {
try {
$conn = new PDO ("sqlsrv:server=tcp:{$server}.database.windows.net,1433; Database={$database}", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$query = "SELECT CONVERT(NVARCHAR(128), DATABASEPROPERTYEX ('{$database}', 'Edition')) as 'Edition', " .
"CONVERT(DECIMAL,DATABASEPROPERTYEX ('{$database}', 'MaxSizeInBytes'))/1024/1024/1024 AS 'MaxSizeInGB'";
$stmt = $conn->query($query);
$row = $stmt->fetch();
$conn = null;
return $row;
}
catch (Exception $e) {
die(print_r($e));
}
}
$db_properties = get_database_properties("yourserver", "yourdatabase", "youruser", "yourpassword");
print("Edition={$db_properties['Edition']} MaxSizeInGB={$db_properties['MaxSizeInGB']}\n");
?>

Run a call from a function PHP

i'm building an website using php and html, im used to receiving data from a database, aka Dynamic Website, i've build an CMS for my own use.
Im trying to "simplify" the receiving process using php and functions.
My Functions.php looks like this:
function get_db($row){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Where i will get the rows content like this: $row['row'];
I'm trying to call it like this:
the snippet below is from the index.php
echo get_db($row['session_id']); // Line 22
just to show whats in all the rows.
When i run that code snippet i get the error:
Notice: Undefined variable: row in C:\wamp\www\Wordpress ish\index.php
on line 22
I'm also using PDO just so you would know :)
Any help is much appreciated!
Regards
Stian
EDIT: Updated functions.php
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Instead of echoing the values from the DB, the function should return them as a string.
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = '';
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result .= $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then call it as:
echo get_db();
Another option would be for the function to return the session IDs as an array:
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = array();
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result[] = $row['session_id'];
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then you would use it as:
$sessions = get_db(); // $sessions is an array
and the caller can then make use of the values in the array, perhaps using them as the key in some other calls instead of just printing them.
As antoox said, but a complete changeset; change row to rows in two places:
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
Putting this at the start of the script after <?php line will output interesting warnings:
error_reporting(E_ALL|E_NOTICE);
To output only one row, suppose the database table has a field named id and you want to fetch row with id=1234:
$stmt = $pdo->prepare("SELECT * FROM lp_sessions WHERE id=?");
$stmt->bindValue(1, "1234", PDO::PARAM_STR);
I chose PDO::PARAM_STR because it will work with both strings and integers.

PDO escape & in query

I'm using PDO for my querys and try to escape some '&' since they make the request invalid. I already tried with mysql_real_escape_string and pdo quote... both didn't escaped the '&'. My values are for example "James & Jack".
As Connector:
$this->connect = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
As Query:
function check_exist($query,$parameter)
{
try
{
$this->connect->prepare($query);
$this->connect->bindParam(':parameter', $parameter, PDO::PARAM_STR);
$this->connect->execute();
return $this->connect->fetchColumn();
unset ($query);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Finaly the Call to action
$db = new database;
$db->connect('framework','localhost','root','');
$result = $db->check_exist('SELECT COUNT(*) FROM cat_merge WHERE cat=:parameter',$cat);
Try using prepared statements this way:
<?php
// Connect to the database
$db = new PDO('mysql:host=127.0.0.1;dbname=DB_NAME_HERE', 'username', 'password');
// Don't emulate prepared statements, use the real ones
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// Prepare the query
$query = $db->prepare('SELECT * FROM foo WHERE id = ?');
// Execute the query
$query->execute($_GET['id']);
// Get the result as an associative array
$result = $query->fetchAll(PDO::FETCH_ASSOC);
// Output the result
print_r($result);
?>

Categories