Select * from table not working SQL - php

I am trying to select all records from a table and then output them below, however I am only able to get the most recent output out.
The table structure is Id, Start, End, DistanceDirections and Date
I am using the code below to get them and then output each Start as a H1 on the page. As mentioned I am only getting the last value out not all as I would expect, I have also tried to be more specific which can be seen in the code below that and it didn't have an effect on the result.
$sql = "SELECT * FROM `searchdata`";
$stmt = $conn->prepare($sql);
$stmt->execute();
foreach($stmt as $row) {
$htmlResult = "<h1>" . $row['Start'] . "</h1>";
}
Here is the other try:
$sql = "SELECT * FROM `searchdata` WHERE DistanceDirections = 'distance'";
$stmt = $conn->prepare($sql);
$stmt->execute();
foreach($stmt as $row) {
$htmlResult = "<h1>" . $row['Start'] . "</h1>";
}
Is there something simple I am missing?

You're only executing the query, you'll also need to fetch the rows.
$sql = "SELECT * FROM `searchdata`";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
$htmlResult = "";
foreach($result as $row) {
$htmlResult .= "<h1>" . $row['Start'] . "</h1>";
}
echo $htmlResult;
More info:http://php.net/manual/en/pdostatement.fetchall.php

Related

Show count instead of duplicate values on select - PHP

I'm trying to build a demo website showcasing the food and/or products in your home ie. fridge or freezer.
I've got most of it down, dynamically creating a list with the items, but I would like to have the duplicates count up like 1x [product] instead of just appearing multiple times in the list like this:
.
My query and stuff looks like this - all inside a for loop.
$sql = "SELECT * FROM goods WHERE person_id = " . $_SESSION['ID'] . " AND room LIKE '" . $rooms[$count] . "'";
if ($result = mysqli_query($conn, $sql)){
if (mysqli_num_rows($result) > 0){
$output = "<ul>";
while ($row = mysqli_fetch_array($result)){
$output .= "<li class='varer'> " . $row['name'] . "</li>";
}
$output .= "</ul>";
}
}
Hope you can help - I'm not that experienced with PHP :)
Check the following code where I show you how to have a group by to have the quantity per item and also, how to use query with prepared statements to avoid sql injection:
// prepare and bind
$stmt = $conn->prepare("SELECT COUNT(*) AS QUANTITY, * FROM goods WHERE person_id = ? AND room LIKE ? BROUP BY name");
$stmt->bind_param("ii", $_SESSION['ID'], $rooms[$count]);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
if ($result) {
$output = "<ul>";
while ($row = $stmt->fetch_assoc()) {
$output .= "<li class='varer'> " . $row['QUANTITY'] . "x " . $row['name'] . "</li>";
}
$output .= "</ul>";
}
(using prepared statements)
$sql = "SELECT room,count(*) FROM goods WHERE person_id = ? AND room LIKE ? ";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $_SESSION['ID'], $rooms[$count]);
$stmt->execute();
result = $stmt->get_result();
if( $result->num_rows > 0 ){
$output = "<ul>";
while ($row = $result->fetch_assoc()){
$output .= "<li class='varer'> " . $row['name'] . "</li>";
}
$output .= "</ul>";
}
$stmt->close();

How to add a while loop to a variable to display and if - else if result?

I have a if - else if statement changing the query from a db based on user input, and I'm displaying the respective results in while loop one for all the if - else if statements however how can I put the while loop into a variable such as $output then just echo that when the if conditions are met?
<?php include 'db_connect.php';
$job_title = $_POST['job_title'];
$company_name = $_POST['company_name'];
$salary = $_POST['salary'];
if($job_title !== " "){
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE jobTitle LIKE :job_title");
$sql->bindValue(':job_title', '%' . $job_title . '%', PDO::PARAM_INT);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
// while loop here //
} else if($company_name !== " ") {
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE company_name LIKE :company_name");
$sql->bindValue(':company_name', '%' . $company_name . '%', PDO::PARAM_INT);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
// while loop here //
}else if($salary !== " ") {
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE salary_info LIKE :salary");
$sql->bindValue(':salary', '%' . $salary . '%', PDO::PARAM_INT);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
// while loop here //
} ?>
You can save the entire query result in a variable using PDOStatement::fetchAll. Later you use the query result outside of if-else block as per your requirement.
<?php
include 'db_connect.php';
$job_title = $_POST['job_title'];
$company_name = $_POST['company_name'];
$salary = $_POST['salary'];
$output = "";
if($job_title !== " "){
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE jobTitle LIKE :job_title");
$sql->bindValue(':job_title', '%' . $job_title . '%', PDO::PARAM_STR);
if($sql->execute()){
$output = $sql->fetchAll();
}
} else if($company_name !== " ") {
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE company_name LIKE :company_name");
$sql->bindValue(':company_name', '%' . $company_name . '%', PDO::PARAM_STR);
if($sql->execute()) {
$output = $sql->fetchAll();
}
}else if($salary !== " ") {
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE salary_info LIKE :salary");
$sql->bindValue(':salary', '%' . $salary . '%', PDO::PARAM_INT);
if($sql->execute()) {
$output = $sql->fetchAll();
}
}
// Now you can use that query result `$output` as per your requirement.
?>
Also, I changed the datatypes in ->bindValue() methods, and that's because I'm assuming jobTitle and company_name are of string datatype whereas salary is of integer type. If that's not the case then you need to change the datatypes in ->bindValue() methods accordingly.
Here's the reference:
http://php.net/manual/en/pdo.constants.php
Sidenote: If you want to see the entire query result structure, do var_dump($output);
You can just use the while loop just once after all the if-else statement has ended.

PHP while loop loops everything except first query result

I am struggling to understand why while loop not looping through the first query result.
$pdo = new PDO('connection');
$stmt2 = $pdo->prepare("SELECT user FROM records
ORDER BY date DESC");
$stmt2->execute();
$r2 = $stmt2->fetch(PDO::FETCH_ASSOC);
while ($r2 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td>' . $r1['user'] . '</td></tr>';
}
I've read this thread but it is OOP. Any suggestions?
You already have fetched the first record by $r1 = $stmt1->fetch(PDO::FETCH_ASSOC);, and fetching the rest in while loop. This should work -
$stmt2->execute();
while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td>' . $r1['user'] . '</td></tr>';
}
That's because you're fetching it twice. Remove the fetch just before while loop.
To something like this,
$pdo = new PDO('connection');
$stmt2 = $pdo->prepare("SELECT user FROM records
ORDER BY date DESC");
$stmt2->execute();
while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td>' . $r1['user'] . '</td></tr>';
}

MySQL Prepared Statement, write multiple rows

So far I have used prepared statements to get ONE row from a database. But how do I write multiple rows onto the page. Looked online and people only seem to be showing how to get the one row.
if ($count_sets->num_rows > 0) {
$query = "SELECT id,jpg,udate,imageset FROM images WHERE dodelete = ? AND udate = ? AND imageset = ?";
if ($stmt = $mysqli->prepare($query)) {
//echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
$stmt->bind_param("isi",$deleted,$session_date,$imageset);
$stmt->execute();
$stmt->store_result();
//Get result
$stmt->bind_result($result_id,$result_jpg,$result_date,$result_imageset);
//Number of rows returned
$count_rows = $stmt->num_rows;
}
} else {
echo "No images to process, do an upload first!";
}
$folder = str_replace("/", "", $session_date);
if ($count_rows > 0) {
echo "hel<br />";
echo $result_jpg[0];
}
Found some example code:
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("SELECT * FROM mytable where userid=? AND category=? ORDER BY id DESC");
$stmt->bind_param('ii', intval($_GET['userid']), intval($_GET['category']));
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1, $column2, $column3);
while($stmt->fetch())
{
echo "col1=$column1, col2=$column2, col3=$column3 \n";
}
$stmt->close();
It's the following part I didn't know how to do.
while($stmt->fetch())
{
echo "col1=$column1, col2=$column2, col3=$column3 \n";
}

Convert mysql_query to PDO statements

While there are a large number of PDO usage examples I have not been able to successfully convert from mysql_query to PDO statements.
Here's what works but is insecure:
<?php
$db = mysql_connect("localhost","username","passphrase");
mysql_select_db("database",$db);
$cat= $_GET["cat"];
/* grab a row and print what we need */
$result = mysql_query("SELECT * FROM cat WHERE cat = '$cat' ",$db);
$myrow3 = mysql_fetch_row($result);
echo "$myrow3[2]";
/* here's an array */
echo '<div class="container">';
$q = mysql_query("SELECT * FROM name WHERE Field4 = '$cat'",$db);
while ($res = mysql_fetch_array($q)){
echo '<div class="item"><p>' . $res['Field1'] . '</p></div>';
}
echo '</div>';
?>
Here is my attempt thus far at attempting to convert the mysql_query* to PDO statements based on How to prevent SQL injection in PHP?. Currently the page does not display, well anything. Any insight would be appreciated!
<?php
$pdo = new PDO('mysql:host=localhost;dbname=database','username','password');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cat= $_GET["cat"];
/* let try grabbing one of those rows, do not think an array should be here? */
$stmt = $pdo->prepare('SELECT * FROM cat WHERE cat = :cat');
$stmt->bindParam(':cat', $cat);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result[2];
/* Now we need an array similar to what we had before */
echo '<div class="container">';
$stmt = $pdo->prepare('SELECT * FROM name WHERE Field4 = :Field4');
while ($res = $stmt->execute(array(':cat' => $cat))) {
echo '<div class="item"><p>' . $res['Field1'] . '</p></div>';
}
echo '</div>';
?>
The way you are doing it, first off, isn't protecting you.
A PDO statement should look like (from the manual):
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
So, for your example:
$stmt = $pdo->prepare('SELECT * FROM cat WHERE cat = :cat');
$stmt->bindParam(':cat', $cat);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
Or you could do:
$stmt = $pdo->prepare("SELECT * FROM cat where cat = ?");
if ($stmt->execute(array($cat)) {
while ($row = $stmt->fetch()) {
//print stuff or whatever
}
}
Finally, in your last part:
while $stmt->execute(array(':cat' => $cat));
echo '<div class="item"><p>' . $res['Field1'] . '</p></div>';
It doesn't look like $res ever gets set. It should look like:
while ($res = $stmt->execute(array(':cat' => $cat)) {
echo '<div class="item"><p><a href="bits.php?page=' . $res['Field2'] .
'&' . $res['Field6'] . '">' . $res['Field1'] . '</a></p></div>';
}

Categories