The following script:
<?php
try
{
$db = new PDO("sqlite:./path/phrases");
$result = $db->query('SELECT * FROM phrases');
foreach($result as $row){
$row['phrase'];
$row['score'];
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
is returning:
Warning: Invalid argument supplied for foreach() in myscript.php on line 5
If I execute: Select * from phrases; in a SQL browser, I get back a long list of results, with regard to the columns phrase and score. What am I doing wrong?
There are 2 examples in this answer.
The first example I found at http://juanmanuelllona.blogspot.ca/
Am providing what I hope will be a solution.
1)
try {
$db = new PDO("sqlite:./path/phrases");
echo 'database open';
$sql = "SELECT * FROM phrases";
$obj= $db->query($sql) ;
foreach ($obj as $row)
{
print('Phrase ='.$row['phrase'].' Course='.$row['score']. '<br/>'); // or <br/>
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
2)
And this suggestion taken from an example at http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=phrases", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM phrases";
foreach ($dbh->query($sql) as $row)
{
print $row['phrase'] .' - '. $row['score'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
You need to use echo statement:
$result = $db->query('SELECT * FROM phrases');
foreach($result as $row){
echo $row['phrase'];
echo $row['score'];
}
try
{
$db = new PDO("sqlite:./path/phrases");
$result = $db->query('SELECT * FROM phrases;'); // remove the Semicolon
foreach($result as $row){
$row['phrase'];
$row['score'];
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
try removing the Semicolon inside the statement.
Related
Please help fix "SQLSTATE[HY000]: General error:" in the following PHP script. Also, refer to the MySQL script in case.
<?php
# MySQL
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'procdb';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to MySQL Server successfully." . "\n";
$sql = "CALL prepend('abcdefg', #inOutParam);";
$stmt = $pdo->query($sql);
do {
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rows) {
foreach($rows as $row) {
print($row[0] . "\n");
}
}
} while ($stmt->nextRowset());
} catch (PDOException $e) {
#die("Could not connect to the database $dbname :" . $e->getMessage());
$error = $e->getMessage();
echo $error . "\n";
} catch (Exception $e) {
$error = $e->getMessage();
echo $error . "\n";
} finally {
$pdo = null;
echo "Connection closed." . "\n";
}
?>
Here's the MySQL Script:
DROP DATABASE IF EXISTS procdb;
DELIMITER $$
CREATE DATABASE procdb;$$
DELIMITER ;
USE procdb;
DROP PROCEDURE IF EXISTS prepend;
DELIMITER $$
CREATE PROCEDURE prepend
(
IN inParam VARCHAR(255),
INOUT inOutParam INT
)
BEGIN
DECLARE z INT;
SET z = inOutParam + 1;
SET inOutParam = z;
SELECT inParam;
SELECT CONCAT('zyxw', inParam);
END;$$
DELIMITER ;
USE procdb;
CALL prepend('abcdefg', #inOutParam);
/*
# Output
// (FieldName1 and its value)
inParam
'abcdefg'
// (FieldName2 and its value)
CONCAT('zyxw', inParam)
'zyxwabcdefg'
*/
What is the cause of the error? Note that adding "$stmt->close();" or "$stmt->closeCursor();" did not help.
Please help.
Thanks
Try this, line
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
Outside While loop
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to MySQL Server successfully." . "\n";
$sql = "CALL prepend('abcdefg', #inOutParam);";
$stmt = $pdo->query($sql);
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($rows as $row) {
foreach ($row as $col) {
print $col . "\n";
}
}
$stmt->nextRowset();
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($rows as $row) {
foreach ($row as $col) {
print $col . "\n";
}
}
} catch (PDOException $e) {
#die("Could not connect to the database $dbname :" . $e->getMessage());
$error = $e->getMessage();
echo $error . "\n";
} catch (Exception $e) {
$error = $e->getMessage();
echo $error . "\n";
} finally {
$pdo = null;
echo "Connection closed." . "\n";
}
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;
}
}
?>
Sorry if the title is vague, was unsure how to word it.
Currently, I'm trying to just do a simple piece of php that runs a query and displays all the data in the database, but no data is displaying the page is just completely blank.
Here is the code:
<?php
$username = "user";
$password = "pass";
try {
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
$stmt = $conn->prepare('SELECT * FROM contacts');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ( count($result) ) {
foreach ($result as $query_row)
{
extract($query_row);
echo '<tr>';
echo '<td>'.$fname.'</td>';
echo '<td>'.$lname.'</td>';
echo '<td>'.$title.'</td>';
echo '<td>'.$deparment.'</td>';
echo '<td>'.$email.'</td>';
echo '<td>'.$cell.'</td>';
echo '<td>'.$handle.'</td>';
echo '<td>'.$steam.'</td>';
echo '<td>'.$skype.'</td>';
echo '</tr>';
}
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
I've never worked with PDO before so I've been following a guide/reading different SO questions trying to get a grasp on it. One line that I think may be screwing up is this line:
$stmt->execute(array('id' => $id));
I don't understand what that line is doing and if an I can get an explanation that would be great. I believe I understand the logic behind the rest of the code though.
This should solve your problem (it worked on my server).
Plus, I added the <table> and </table> tags and placed in their respective locations.
<?php
$username = "user";
$password = "pass";
try {
// uncomment for testing purposes as noted by jeroen
// $conn = new PDO('mysql:host=localhost;dbname=database', $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
$stmt = $conn->prepare('SELECT * FROM contacts');
$stmt->execute(array('id' => $id));
// $stmt->execute(); // as noted by Mike Brant
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<table>";
if ( count($result) ) {
foreach ($result as $query_row)
{
extract($query_row);
echo '<tr>';
echo '<td>'.$fname.'</td>';
echo '<td>'.$lname.'</td>';
echo '<td>'.$title.'</td>';
echo '<td>'.$deparment.'</td>';
echo '<td>'.$email.'</td>';
echo '<td>'.$cell.'</td>';
echo '<td>'.$handle.'</td>';
echo '<td>'.$steam.'</td>';
echo '<td>'.$skype.'</td>';
echo '</tr>';
}
}
echo "</table>";
?>
I am trying to set a certain cell in a database to a variable in PDO. The code I am using now is:
$dbuser = "root";
$dbpass = "root";
$player = "ryr11";
//$player = $_GET["pname"];
try {
$conn = new PDO("mysql:host=localhost;dbname=users", $dbuser, $dbpass);
$stmt = $conn->prepare("SELECT * FROM players WHERE username = :player");
$stmt->execute(array("player" => $player));
$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();
}
I want each column to have it's own variable, so I can echo the cell content. As of now, it is only showing it in an array.
echo $row['cell_name'];
fetchAll() returns an associative array.
while ($result = $stmt->fetch())
{
echo 'username : '. $result["username"].'<br />';
echo 'cell_name2 : '. $result["cell_name2"].'<br />';
echo 'cell_name3 : '. $result["cell_name3"].'<br />';
.....
...
etc
}
or you can use a html table style
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.