Add code around one particular result from SELECT statement - php

I have the following code SELECTING the Title and Image from the "Courses" table in my database.
<?php
$username = 'REMOVED';
$password = 'REMOVED';
try {
$conn = new PDO('mysql:host=localhost;dbname=REMOVED', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT Title, Image FROM Courses');
$stmt->execute();
while($row = $stmt->fetch()) {
print_r($row);
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
How can I make it so that the Title has a header tag wrapped around it and the Image is inside of an image src=""?

depending on your PDO settings the result may for example be returned in an associative array (which would be the most common default setting):
while($row = $stmt->fetch()) {
echo '<img src="' . $row["Image"] . '" title="' . $row["Title"] . '">';
}
update: to force the fetching of associative array, just replace $stmt->fetch() with $stmt->fetch((PDO::FETCH_ASSOC)

replace while loop with following code:
$string="<header>";
$imagesrc="";
While($row=$stmt->fetch()){
$string+=$row['Title'];
$imagesrc=$row['Image'];
}
$string+="</header>";
$stringImage="<img src='".$imagesrc."' />";

Related

How to display a unsorted list using PDO on SQLite table?

I try to display a results of a SELECT query using PDO in a unsorted list and for that I use this code:
<?php
try {
$conn = new PDO('sqlite:db/MyDatabase.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT genus, species FROM MyTable ORDER BY genus ASC, species ASC");
$stmt->execute();
$data = $stmt->fetchColumn();
echo '<ul>' . '<li>' . $data . '<br/>' . '</li>' . '</ul>';
}
catch(PDOException $e) {echo "Error: " . $e->getMessage();}
$conn = null;
?>
But I only get displayed the first item of the column "genus".
How can I get a unsorted list in a more friendlier form of "genus (space) species"?
fetchColumn() only returns the first column from a result set fetchAll() will return all rows from a table. Then loop through the array using foreach or while.
Trying to echo $data will not work since you cannot echo an array, you would need to specify the array keys which in this case would be the column names.
<?php
try {
$conn = new PDO('sqlite:db/MyDatabase.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT genus, species FROM MyTable ORDER BY genus ASC, species ASC");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<ul>';
if ( !empty($data) ) {
foreach ( $data as $row ){
echo '<li>'. $row['genus'] .' '. $row['species'] .'</li>';
}
} else {
// something to show when no results.
}
echo '</ul>';
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

Trouble displaying images from MySQL database

My problem is thatmy code will only display one image from my database. I change the id to a different row, the name and everything else comes up fine but the image wont load. Even if I upload a new image this still happens? Please help!
<?php
session_start();
$user = $_SESSION['username'];
if(!empty($_SESSION['loggedin'])) {
$id = $_GET['id'];
$conn = new PDO ("mysql:host=localhost;dbname=project", "root",
"pass");
$stmt = $conn->prepare("SELECT * FROM images where id = :id");
try {
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($row = $stmt->fetch())
{
if($row == false)
{
echo "Sorry nothing here!";
}
else {
echo "$row[title]";
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['image'] ) . '" />';
echo "$row[username]";
echo "$row[description]";
echo "$row[category]";
}
}
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
What could be causing this? The images are stored as long blobs, their file types vary between jpg, jpeg, png and gif.
I have also tried the following which still works the same as above:
$image = $row['image'];
echo '<img src="data:image/jpeg;base64,'. base64_encode($image) .'" />';

creating a filled drop down list from phpmyadmin

I need to create a filled drop down list which is linked to my table called called 'dog' in phpmyadmin. I need a user to be able to select a dog from the list and press search and the results show up. And all information be stored in my table in phpmyadmin. This is what I have so far:
It doest work its just an empty drop down and it does nothing. Please help.
<?php
// set up connection parameters
$dbHost = 'hostnamegoeshere';
$databaseName = 'databasenamehere';
$username = 'usernamehere';
$password = 'passwordhere';
// make the database connection
$db = new PDO("mysql:host=$dbHost;dbname=$databaseName;charset=utf8","$username", "$password");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // enable error handling
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // turn off emulation mode
?>
//Return an error if bad connection
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ')'
.$mysqli->connect_error);
}
//query database for results
$query = $mysqli->query("SELECT * FROM 'dog'");
?>
<h3> Search dogs</h3>
<select>
<?php
$stmt = $mysqli->prepare($query);
$stmt->execute();
$res = $stmt->get_result();
while($dropdown = $res->fetch_array(MYSQLI_ASSOC)) {
echo '<option value="' . $dropdown['dog'] . '"></option>';} ?>
</select>
I will be very grateful for any help
USE THIS
$res = $stmt->get_result();
$res =$res->fetch_array(MYSQLI_ASSOC)
foreach($res as $a){
echo '<option value="' . $a['dog'] . '">'. $a['dog'] .'</option>';} ?>
}
AT PLACE OF
$res = $stmt->get_result();
while($dropdown = $res->fetch_array(MYSQLI_ASSOC)) {
echo '<option value="' . $dropdown['dog'] . '"></option>';} ?>
Number of issues in your CODE
1) Wrap off quotes form table name(SELECT * FROM 'dog')quotes
2) Don't use prepare and query at one time.($mysqli->query,$mysqli->prepare)
3) Add text to your option(<option value="value"></option>)
4) You are mixing mysqli with pdo
You code would be
Create you connection with mysqli
$mysqli=mysqli_connect($dbHost,$username,$password,$databaseName);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ')'
.$mysqli->connect_error);
}
<h3> Search dogs</h3>
<select>
<?php
$stmt = $mysqli->query("SELECT * FROM dog");// wrap off and use only query to run
$stmt->execute();
$res = $stmt->get_result();
while ($dropdown = $res->fetch_array(MYSQLI_ASSOC)) {
echo '<option value="' . $dropdown['dog'] . '">'.$dropdown['dog'].'</option>';// add text to dropdown
}
?>
</select>

How to check EXISTS result - PDO

I use a http://php.net/ page code for conecting with PDO. I Add the EXIST term. How to check if the EXISTS return false? If is not posible, how to check if select return an empty result?
try {
$conn = new PDO("mysql:host=$servername;dbname=xxxx", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
getUsers($conn,$po[0]);
$conn = null;
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
function getUsers($con,$po){
$sql = "SELECT * FROM usuarios WHERE EXISTS (SELECT id FROM webs WHERE name='$po')";
foreach ($con->query($sql) as $row) {
print $row['nombre'] . "\n";
print $row['id'] . "\n";
print $row['email'] . "\n";
}
}
The WHERE EXISTS returns a standard SELECT result (rows) based on the subquery after key EXISTS
So, to check if the EXISTS fails, you have to use rowCount, that return the number of rows returned by the query:
$result = $con->query($sql);
if( $result->rowCount() > 0 ) echo "EXISTS";
else echo "NOT EXISTS";
(Edit:)
Please note:
As noted in the comments below, the rowCount() works fine in this case and always with mySQL database structures, but «this behaviour is not guaranteed for all database» structures: with sqLite, i.e., it doesn't works.
if you will use like this then it will work and no require for check condition
$rows = $con->query($sql);
if($rows){
foreach ($rows as $row) {
print $row['nombre'] . "\n";
print $row['id'] . "\n";
print $row['email'] . "\n";
}
}

Two near-identical pieces of code.. one works, the other doesn't

The following code works fine, it randomly selects an image from a folder, and assigns it as a background to a generated Div. This works. If I use this code a second time, but use it to simply place an img-src of the randomised image, this also works. However, using the code in the same way as the first, breaks the site. What am I doing wrong?
<!-- BEGIN FEATURED 1 -->
<?php
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch (PDOException $e) {
echo $e->getMessage();
echo 'Could not establish a connection to the database.';
}
$query = $conn->prepare('SELECT `articleid`,`title` FROM `news_articles` WHERE featured = 1 ORDER BY RAND() LIMIT 1');
$array = array(
'N'
);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_COLUMN, 0);
foreach ($results as $row) {
}
$image = get_rand_img('images/featured_images/csgo/');
$title = $result['title'];
echo '<a href="index.php?viewarticle=1&articleid=' . $row . '">';?>
<div id="featured-image" style="height: 267px; width: 292px; background:url(/images/featured_images/csgo/<?php echo $image ?>)">
<?php
$result = $conn->prepare("SELECT `articleid`,`title`,`short_title` FROM `news_articles` WHERE articleid=$row");
$result->execute();
$rows = $result->fetch();
echo '<div class="featuredtitle1">';
echo $rows['short_title'];
echo '</div>';
echo '</div>';
echo '</a>';
?>
The code below, breaks the site.. (I have commented it out at the moment as you can see).
<!-- BEGIN FEATURED 2 (Disabled) -->
<?php
/*
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch (PDOException $e) {
echo $e->getMessage();
echo 'Could not establish a connection to the database.';
}
$query = $conn->prepare('SELECT `articleid` FROM `news_articles` WHERE featured = 1 ORDER BY RAND() LIMIT 1');
$array = array(
'N'
);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_COLUMN, 0);
foreach ($results as $row) {
}
$image = get_rand_img('images/featured_images/dota/');
$title = $result['title'];
echo '<a href="index.php?viewarticle=1&articleid=' . $row . '">';?>
<div id="featured-image2" style="height: 267px; width: 292px; background:url(/images/featured_images/dota/<?php echo $image ?>)">
<?php
$result = $conn->prepare("SELECT `articleid`,`title`,`short_title` FROM `news_articles` WHERE articleid=$row");
$result->execute();
$rows = $result->fetch();
echo '<div class="featuredtitle2">';
echo $rows['short_title'];
echo '</div>';
echo '</div>';
echo '</a>';
*/
?>
I don't understand why the first piece of code is fine, but duplicating it again breaks it?
Before you edited your comment, I saw a fatal error about accessing object as an array. Try to change your code from this:
$results = $query->fetchAll(PDO::FETCH_COLUMN, 0);
To this:
$results = $query->fetchAll(PDO::FETCH_ASSOC);

Categories