How to get first row of data in sqlite3 using php PDO
As per my below code first row data does not display becuase I have used recordset for check row is return or not.
Any idea how to get all data from record set?
My Code.
try {
$dbhandle = new PDO("sqlite:".$database);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$result=$dbhandle->query("select * from table");
if($result)
{
if($rs1==$result->fetchColumn())
{
while ($rs1 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT))
{
echo "<pre>";
print_r($rs1);
echo "</pre>";
}
}
else
{
// error message
}
}
If you just want to get the first row, then there's no need to use a loop.
$result=$dbhandle->query("select * from table");
if ($result) {
$row = $result->fetch(PDO::FETCH_ASSOC);
echo "<pre>";
print_r($row);
echo "</pre>";
}
Update:
For get all rows.
$result=$dbhandle->query("select * from table");
$rows = array();
if ($result) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $row;
}
if ($rows) {
echo "<pre>";
print_r($rows);
echo "</pre>";
} else {
echo "No results";
}
}
Related
Here is my php file to retrieve users informations using recycleview in android.
but it does not work I don't know. I need some help
Here, image is TEXT and String, the others are varchar String also in my database 'xxxxx' table---users
<?php
include("connect.php");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT nom, prenom, telephone, email,ncni, datenaissance, image FROM users ORDER BY id DESC ";
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
?>
You have made a lot of mistakes in your code. You have skipped mysqli (query,fetch_assoc,num_rows should be mysqli_query,mysqli_fetch_assoc,mysqli_num_rows) everywhere. If you don't want to write mysqli multiple times, you should try PDO.
Here is an example:
try {
$db = new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8',DBUSER, DBPASS);
//echo "Connected";
}
catch (PDOException $e) {
//print "Error!: " . $e->getMessage() . "<br/>";
echo "Not Connected";
die();
}
$query = $db->prepare("SELECT `nom`, `prenom`, `telephone`, `email`,`ncni`, `datenaissance`, `image` FROM `users` ORDER BY `id` DESC");
$query->execute();
if ($query->rowCount() > 0) {
$data = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data);
}
else
{
echo 'No Result Found';
}
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();
}
I have myself in a unique situation here and I am not sure if this is the correct way to go about it; I am open to suggestions.
I have a function in which it grabs all of the table names in a database and stores them into an array. Next newly parsed items ($id) are passed against this table name array and any matches are unset from this array. This leaves me with the leftovers which are items that have been discontinued.
Code below:
function itemDiscontinued($dbh, $id, $detail) {
try {
$tableList = array();
$result = $dbh->query("SHOW TABLES");
while ($row = $result->fetch()) {
$tableList[] = $row[0];
}
$key = array_search($id, $tableList);
unset($tableList[$key]);
print_r($tableList);
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
The problem is that the array $tablelist keeps recreating itself due to the function being in a foreach loop (Parsing process). I only require one instance of it to work with once it is created. I apologise before hand if the problem is a bit hard to understand.
Yea, it's really hard to understand. Maybe you'll try this:
function itemDiscontinued($dbh, $id, $detail) {
static $tables = array();
if (!$tables) {
$tables = getTableList($dbh);
}
$key = array_search($id, $tables);
unset($tables[$key]);
print_r($tables);
}
function getTableList($dbh) {
try {
$tableList = array();
$result = $dbh->query("SHOW TABLES");
while ($row = $result->fetch()) {
$tableList[] = $row[0];
}
return $tableList;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
how about an array_push with an extra parameter
function itemDiscontinued($dbh, $id, $detail, $outputArray) {
try {
$result = $dbh->query("SHOW TABLES");
while ($row = $result->fetch()) {
array_push($outputArray, $row[0]);
}
$key = array_search($id, $outputArray);
unset($outputArray[$key]);
return $outputArray; // use this for subsequent run on the foreach statment
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
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);
here's the PHP/PDO.
try {
$query = 'SELECT Date,Close FROM DY_AAPL LIMIT 5';
$sth = $db->prepare($query);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)){
$result_array=array();
$result_array[]=$row['Close'];
/* $num = $row['Close']; */
echo json_encode($result_array);
}
}catch (PDOException $e){
echo 'ERROR ' . $e->getMessage();
}
When I attempt to access the array using javascript, it's only outputting the last value in the array. Any pointers?
<script type="text/javascript">
var myjson = JSON.parse('<?php echo json_encode($result_array); ?>');
document.write(myjson);
</script>
I thought it might have something to do with 'JSON.parse,' but I'm not sure. Thanks in advance!
Try
$result_array = array();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$result_array[]=$row['Close'];
/* $num = $row['Close']; */
}
echo json_encode($result_array);
…instead of initializing and outputting the array in each loop turn.
You should echo your end result, not every iteration:
while ($row = $sth->fetch(PDO::FETCH_ASSOC)){
$result_array=array();
$result_array[]=$row['Close'];
}
echo json_encode($result_array);
Try this for your PHP:
try {
$query = 'SELECT Date,Close FROM DY_AAPL LIMIT 5';
$sth = $db->prepare($query);
$sth->execute();
$result_array=array();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)){
$result_array[]=$row['Close'];
}
echo json_encode($result_array);
}catch (PDOException $e){
echo 'ERROR ' . $e->getMessage();
}
It's because your doing the json encode within the while-loop. Place it outside the loop so the entire array get encoded.
Also, you're initializing the array within the while-loop. Which means that it will overwrite itself each time it loops.