I want to display all the comments posted under each image from a database.
I tried the following code, but I was able to get only one comment, which was the last one posted.
$sql1="SELECT user,comment FROM comment_table where imagename=:file";
$q1=array(':file'=>$file);
try {
$stmt = $pdo->prepare($sql1);
$stmt->execute($q1);
$stmt->setFetchMode(PDO::FETCH_BOTH);
$result= $stmt->fetch();
$c = $result["comment"];
$u=$result["user"];
}
catch (PDOException $e) {
die("Failed to run query: " . $e->getMessage());
}
echo "<tr><td>".$u.":".$c."</td><tr>";
Please help needed and appreciated.
You need to create a foreach to print all the comments. Take a read here http://php.net/manual/en/control-structures.foreach.php
With your code it just shows one comment, so try this:
$sql1="SELECT user,comment FROM comment_table where imagename=:file";
$q1=array(':file'=>$file);
try {
$stmt = $pdo->prepare($sql1);
$stmt->execute($q1);
$stmt->setFetchMode(PDO::FETCH_BOTH);
$result= $stmt->fetch();
catch (PDOException $e) {
die("Failed to run query: " . $e->getMessage());
}
foreach ($result as $res) {
echo "<tr><td>".$res["user"].":".$res["comment"]."</td><tr>";
}
Related
The following SELECT statement works just fine:
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (65,70,80)');
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
BUT when I try to send a variable into the WHERE clause, I only get one row back.
In this case $ids is a string that looks like '65,70,80'.
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (?)');
$sql->bindParam(1, $ids);
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Do I need to change the way I'm fetching the data, or is my syntax wrong?
A-HA! Thanks for that link Mihai. Here's the code that works:
First: instead of passing in a string, put ids into an $ids array.
// Figure out how many ? marks have to be in your query as parameter placeholders.
$count = count($ids);
$arrayOfQuestions = array_fill(0, $count, '?');
$queryPlaceholders = implode(',', $arrayOfQuestions);
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (' . $queryPlaceholders . ')');
$sql->execute($ids);
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Try this:
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (?)');
$sql->bindParam(1, explode(',', $ids));
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
I am trying to fetch values from a mysql query using PDO...it works with one column but I need to return 2 columns from the query. Below is the piece of code I have made...
try {
$conn = new PDO('mysql:host=localhost;dbname=****', 'root', '****'>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sth = $conn->prepare("select distinct prod_url,ean from tab_nl where ean in (select ean1 from test_sku where sku='$sku') and prod_url like '%prijzen%'");
$sth->execute();
$urlsku = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
$urlean = $sth->fetchAll(PDO::FETCH_COLUMN, 1);
echo $sku;
echo $urlsku;
echo $urlean;
It returns me some array values...which I really can't figure out. Can anyone please help me with this.
If you use fetch() with the PDO::FETCH_ASSOC style it is easy to get both columns:
while($row = $sth->fetch(PDO::FETCH_ASSOC) {
echo $row['prod_url'];
echo $row['ean'];
}
By placing the fetch in a loop all of the rows will be returned which you can then limit as you see fit.
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $data[0]['prod_url'];
echo $data[0]['ean'];
Add LIMIT 2 in the query , to get two sets of result :)
try {
$conn = new PDO('mysql:host=localhost;dbname=****', 'root', '****'>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sth = $conn->prepare("select distinct prod_url,ean from tab_nl where ean in (select ean1 from test_sku where sku='$sku') and prod_url like '%prijzen%' LIMIT 2");
$sth->execute();
$urlsku = $sth->fetchAll(PDO::FETCH_ASSOC, 0);
$urlean = $sth->fetchAll(PDO::FETCH_ASSOC, 1);
print_r($urlsku);
print_r($urlean);
I have the following statement which SELECTs ProductName and Quantity from the orderDetails table. See below:
try {
$stmt = $conn->prepare("SELECT ProductName, Quantity FROM orderDetails WHERE OrderID = :OrderID");
$stmt->bindParam(':OrderID', $_SESSION['newOrderID'], PDO::PARAM_INT);
$stmt->execute();
$_POST['ProductName'] = $stmt->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
If $_POST['ProductName']['ProductName'] exists more than once how can I create a foreach loop based on that?
What I have tried so far...
foreach($_POST['ProductName']['ProductName']) {
}
This did not work...
What have I done wrong?
Complete Code:
try {
$stmt = $conn->prepare("SELECT ProductName, Quantity FROM orderDetails WHERE OrderID = :OrderID");
$stmt->bindParam(':OrderID', $_SESSION['newOrderID'], PDO::PARAM_INT);
$stmt->execute();
array_push($_POST["ProductName"], $stmt->fetch(PDO::FETCH_ASSOC));
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// echo $_POST['ProductName']['ProductName'];
// echo $_POST['ProductName']['Quantity'];
try {
$stmt1 = $conn->prepare("SELECT Stock FROM products WHERE ProductName = :ProductName");
$stmt1->bindParam(':ProductName', $_POST['ProductName']['ProductName']);
$stmt1->execute();
$_POST['Stock'] = $stmt1->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// echo $_POST['Stock']['Stock'];
$_POST['DEDUCT'] = $_POST['Stock']['Stock'] - $_POST['ProductName']['Quantity'];
try {
$stmt2 = $conn->prepare("UPDATE products SET Stock = :Stock WHERE ProductName = :ProductName");
$stmt2->bindParam(':Stock', $_POST['DEDUCT']);
$stmt2->bindParam(':ProductName', $_POST['ProductName']['ProductName']);
$stmt2->execute();
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
You can make a new array called (for example, $rows) which contains all of the fetched data using the function fetchAll() (fetch() only retrieves the next one row).
The most straightforward way to do this is as follows:
try {
$stmt = $conn->prepare("SELECT ProductName, Quantity FROM orderDetails WHERE OrderID = :OrderID");
$stmt->bindParam(':OrderID', $_SESSION['newOrderID'], PDO::PARAM_INT);
$stmt->execute();
//Add all returned values to an array called "$rows"
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
Then if you want to access that data later you can do:
foreach($rows as $row){
var_dump($row); //Show the data in the row to double-check
}
You can create array using foreach like this :
$newval_arr = array();
foreach($_POST['ProductName']['ProductName'] as $key=>$value) {
if(!in_array($value,$newval_arr) || empty($newval_arr))
{
$newval_arr[] = $value;
}
}
Then after you can use $newval_arr in foreach
foreach($newval_arr as $key=>$value)
{
//Your code herer
}
I'd like to execute some queries that doesn't return result set, and then execute a real query, and fetch its result.
Here is an exemple that doesn't work :
<?php
try {
$db = new PDO('dblib:host=myhost;dbname=master','user','password');
$query = "declare #entier int = 1;";
$db->exec($query);
$query = "select #entier;";
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
print_r($rows);
}
catch (PDOException $e) {
print ($e->getMessage());
}
catch (Exception $e) {
print ($e->getMessage());
}
?>
This code neither doesn't work :
try {
$db = new PDO('dblib:host=myhost;dbname=master','user','password');
$query = "declare #entier int = 1; select #entier;";
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
print_r($rows);
}
catch (PDOException $e) {
print ($e->getMessage());
}
catch (Exception $e) {
print ($e->getMessage());
}
?>
But this code works :
<?php
try {
$db = new PDO('dblib:host=myhost;dbname=master','user','password');
$query = "select 1;";
$stmt = $db->query($query);
$rows = $stmt->fetchAll();
print_r($rows);
}
catch (PDOException $e) {
print ($e->getMessage());
}
catch (Exception $e) {
print ($e->getMessage());
}
?>
Thanks for your help
I know this is old, but for other people finding this from Google: you need to use PDOStatement::nextRowset to iterate over the result sets from your multiple queries.
However, it seems there are memory issues when using nextRowset with dblib in some versions (it tried to allocate 94Tb in my case...), so I ended up re-engineering to avoid multiple SQL queries altogether (instead duplicating the value of the DECLARE where it was being used).
PDO::query docs (http://php.net/manual/it/pdo.query.php) say
PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.
This could mean that you can execute with query() both queries with and without result
Wondering if anyone can help at all. I am running through a tutorial on php and mysql, where there is a joke database which holds:
Jokes in joke table
Authors in author table
Categories in category table
I have a page called authors.html.php that contains a list of authors with options to add author, edit/delete author (next to name of each of returned authors). What i am trying to do is if the db containing the authors is empty instead of displaying the following php error:
Notice: Undefined variable: authors in C:\wamp\www\chapter7\admin\authors\authors.html.php on line 22
I want to display a nice tidy message saying no results found.
My code is as follows:
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/chapter7/includes/db.inc.php';
try {
$result = $pdo->query('SELECT id, name FROM author');
} catch (PDOException $e) {
$error = 'Error fetching authors from the database!';
include $_SERVER['DOCUMENT_ROOT'].
'/chapter7/admin/error.html.php';
exit();
}
foreach ($result as $row){
$authors[] = array('id' => $row['id'], 'name' => $row['name']);
}
include 'authors.html.php';
if (isset($_POST['action']) and $_POST['action'] == 'Delete') {
include $_SERVER['DOCUMENT_ROOT'].
'/chapter7/includes/db.inc.php';
//Get jokes belonging to author
try {
$sql = 'SELECT id FROM joke WHERE authorid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
} catch (PDOException $e) {
$error ='Error getting list of jokes to delete.';
include $_SERVER['DOCUMENT_ROOT'].
'/chapter7/admin/error.html.php';
exit();
}
$result = $s->fetchAll();
//Delete joke category entries
try {
$sql = 'DELETE FROM jokecategory WHERE jokeid =:id';
$s = $pdo->prepare($sql);
//For each joke
foreach ($result as $row) {
$jokeId= $row['id'];
$s->bindValue(':id', $jokeId);
$s->execute();
}
} catch (PDOException $e) {
$error = 'Error deleting category entries for joke.';
include $_SERVER['DOCUMENT_ROOT'].
'/chapter7/admin/error.html.php';
exit();
}
//Delete jokes belonging to author
try {
$sql = 'DELETE FROM joke WHERE authorid = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
} catch (PDOException $e) {
$error = 'Error deleting jokes for author';
include $_SERVER['DOCUMENT_ROOT'].
'/chapter7/admin/error.html.php';
exit();
}
//Delete the author
try {
$sql = 'DELETE FROM author WHERE id =:id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
} catch (PDOException $e) {
$error ='Error deleting author';
include $_SERVER['DOCUMENT_ROOT'].
'/chapter7/admin/error.html.php';
exit();
}
header('Location: .');
exit();
}
please be aware i am extremely new to this and have already attempted some iterations that failed miserably so any assistance or even just simple guidance that would step me through the thinking around creating such functionality would be greatly appreciated. Not just looking for the right answer but want to understand the thinking behind if anyone can help that would be great.
Something similar to this should work. I have used this in the past and it has worked for me. You will need to adjust the query and such to your DB and tables, but it should be fine.
$stm = $PdoObj->prepare("SELECT * FROM NEWS_articles");
$stm ->execute();
$results = $stm ->fetchAll();
if($results==null){
echo "<p>No dice, try other criteria</p>";
}else{
foreach($results as $row){
echo $row["articleName"];
}
}