Fetch specific column value from result set in php - php

MY code is:
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("select userid,fname,type from native_users where email=:email and pass=:pass");
$stmt->bindParam(':email', $username);
$stmt->bindParam(':pass', $password);
$stmt->execute();
if($stmt->rowCount() > 0)
{
$_SESSION['uid']=$stmt->fetchColumn(0); //working
$_SESSION['fname']=$stmt->fetchColumn(1); //not working
$utype=$stmt->fetchColumn(3); // not working
if($utype == "admin")
{
// send to admin page
}
else
{
//send to user page
}
}
else
{
echo"Incorrect data.";
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
I am new to PHP, I basically do Java.
I read here that:
There is no way to return another column from the same row if you use
PDOStatement::fetchColumn() to retrieve data.
In java, there is ResultSet#getString() funtion to do this.
What is the PHP equivalent of this?

You can use:
$result = $sth->fetch();
$result[0] will give userid
$result[1] will give fname
$result[2] will give type
Please read this
fetchColumn(), Returns a single column from the next row of a result
set.
Please read this for detail.

Use PDO::fetchAll() :
$rows = $stmt->fetchAll();
foreach ($rows as $v) {
echo $v['userid'] . " " . $v['fname'] . " " . $v['type'] ;
}
}
or just print_r($rows) you will notice that it's an associative array.

Related

Check PDO query for result and then reuse the data

I am new to PDO, and am in the process of upgrading an application from mysql_query to PDO. This is surely a stupid question - but I hope someone can help me wrap my head around it.
I need to see if a PDO query has any data:
- if it doesn't, throw an error
- if it does, retrieve that data
I could do this easily with mysql_num_rows, but that's deprecated as we all know.
The issue is that once I've checked if there is any data, I can no longer retrieve it.
The check runs fine, but then when trying to retrieve the actual result, it's empty. I can of course execute the query again after the check - but I'd rather avoid having to run a query twice.
try
{
$result = $pdo2->prepare("SELECT first_name FROM users WHERE email = :email;");
$result->bindValue(':email', $email);
$result->execute();
$data = $result->fetchAll();
}
catch (PDOException $e)
{
$error = 'Error fetching user: ' . $e->getMessage();
echo $error;
exit();
}
if (!$data) {
echo "No data!";
} else {
echo "Data found!";
}
$row = $result->fetch();
echo "First name: " . $row['first_name'];
How can I solve this?
I tried to assign $result to another variable ($test = $result), and then run the data check on the $test variable instead - but even so, the $result variable STILL doesn't return any data after running the check (see the commented lines):
try
{
$result = $pdo2->prepare("SELECT first_name FROM users WHERE email = :email;");
$result->bindValue(':email', $email);
$result->execute();
$test = $result; // Duplicating the variable
$data = $test->fetchAll(); // Running the check on the duplicated variable
}
catch (PDOException $e)
{
$error = 'Error fetching user: ' . $e->getMessage();
echo $error;
exit();
}
if (!$data) {
echo "No data!";
} else {
echo "Data found!";
}
$row = $result->fetch(); // Still doesn't return the result!
echo "First name: " . $row['first_name'];
This is really doing my head in... I think there's a simple solution somewhere, I just can't see it. Please help!
$result->fetch() only fetches rows that haven't already been fetched. Since you fetched everything with $result->fetchAll(), there's nothing left.
If you want the first row, you can use:
$row = data[0];
If you want to process all the rows, use:
foreach ($data as $row)
Instead of fetching everything, you can use the rowCount() method.
if (!$result->rowCount()) {
echo "No data";
} else {
echo "Data found!";
}
There are caveats regarding the use of rowCount() with SELECT queries in PDO, but I think it generally works with MySQL.
As you are using a try/catch block you can raise your own exceptions as well as catch those thrown by PDO - so you could do something like this:
try{
$sql='SELECT first_name FROM users WHERE email = :email;';
$stmt = $pdo2->prepare( $sql );
if( !$stmt )throw new Exception('Failed to prepare sql statement');
$result=$stmt->execute( array( ':email' => $email ) );
if( !$result )throw new Exception('Failed to get any results');
$rows = $stmt->rowCount();
if( $rows == 0 )throw new Exception('Empty recordset');
while( $rs=$stmt->fetch( PDO::FETCH_OBJ ) ){
echo $rs->firstname;
}
}catch ( PDOException $e ){
exit( 'Error fetching user: ' . $e->getMessage() );
}
You can always fetch individual rows and for the first row, check if the data is returned and process if not. Then enter a do...while() loop which processes the data and then reads the next row at the end of the loop...
try
{
$result = $pdo2->prepare("SELECT first_name FROM users WHERE email = :email;");
$result->bindValue(':email', $email);
$result->execute();
$row = $result->fetch(); // Fetch first row of data
if (!$row) {
echo "No data!";
} else {
echo "Data found!";
do {
echo "First name: " . $row['first_name'];
}
while ($row = $result->fetch());
}
}
catch (PDOException $e)
{
$error = 'Error fetching user: ' . $e->getMessage();
echo $error;
exit();
}

PHP PDO rowCount not working? I think

So I am grabbing the amount of rows in a specific table where the username is already in the database like so:
$second_sql = $db->prepare("SELECT * FROM users WHERE username = :username");
$second_sql->bindParam(':username', $username);
$second_sql->execute();
if($second_sql->rowCount() == 1) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
The problem is it's not working. If you need more of the script just tell me.
Some databases does not report the row count with PDO->rowCount() method.
SQLite, for instance.
So don't use rowCount(); doing so makes your code less portable.
Instead use the COUNT(*) function in your query, and store the result in a variable.
Finally, use that variable to fetch the one and only column (users) using the fetchColumn() method.
So you can play with this:
try {
$second_sql = $db->prepare("SELECT COUNT(*) from users WHERE username = :username");
$second_sql->bindParam(':username', $username, PDO::PARAM_STR);
$second_sql->execute();
$count = $second_sql->fetchColumn();
} catch (PDOException $e) {
// Here you can log your error
// or send an email
// Never echo this exception on production
// Only on development fase
echo "Error: " . $e->getMessage();
}
if ($count) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
Perhaps you wanna test you condition for a single row:
if ($count == 1)
Hope this helps you.
Cheers!

PDO Read From Database

I have made a code using PDO to read a table from a database.
I try to echo my result but I get a blank page without error.
My Code Is:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
But the echo is empty without any error.
What I am doing wrong?
Thank you All!
Few things to change:
dont forget $
if your going to catch the error, catch the whole pdo code
You can use rowCount() to count the rows
echo something if the record count is 0
include 'config.php';
$id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->rowCount() != 0)
{
$row = $result->fetch(PDO::FETCH_BOTH);
echo $row['Data1'];
echo $row['Data2'];
}else{
echo 'no row found';
}
}catch(PDOException $e){
echo "error " . $e->getMessage();
}
Also use prepared statements for example:
$result = $conn->prepare("SELECT * FROM mytable WHERE id=:id");
$result->execute(array(':id'=>$id));
I'm assuming there's only one record with the id "264540733647332".
The issue is that $result->fetchColumn() call reads first row in the result set and then advances to the next result. Since there's only one of the results, the subsequent call to $result->fetchAll() returns nothing, hence no data displayed.
To fix this replace fetchColumn with rowCount:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>

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.

SQL Query won't return what is in the row (PHP)

My PHP:
<?php
function connectDB($user, $pass) {
try {
return(new PDO("mysql:host=localhost;dbname=Test;", $user, $pass));
} catch(PDOException $ex) {
return $ex;
}
}
$db = connectDB("root", "root");
if ($db instanceof PDOException) {
die($db->getMessage());
}
$query = "SELECT * FROM `TABLE`";
$stmt = $db->prepare($query);
$stmt->execute();
$rows = $stmt->fetch();
foreach($rows as $row) {
echo $row['VALUE1'];
echo $row['VALUE2'];
echo $row['VALUE3'];
}
?>
It only echo's the first letter of each value.
Here is what my table looks like:
VALUE1 VALUE2 VALUE3
gomeow book nothing
other book nothing
It only prints out the first letter of the first row many times
Prints out: ggggggbbbbbbnnnnnn
Check your error logs, and try with this and let me know then -
$rows = $stmt->fetch(PDO::FETCH_BOTH);
print_r($rows);

Categories