PHP FetchAll() Not returning rows - php

I was wondering if somebody could help shed some light as to why this PHP code is not entering into the for loop? In MySQL the query returns the appropriate rows that I need but in this PHP file it fails to return anything into the array, thus not executing the foreach loop.
CODE
<?php
try {
$sql = 'SELECT FirstName,LastName ';
$sql .= 'FROM adventureworks.employeedepartmenthistory ';
$sql .= 'JOIN employee USING(EmployeeID) ';
$sql .= 'JOIN contact USING(ContactID) ';
$sql .= 'WHERE DepartmentID = 2';
$stmt = $dbh->prepare($sql);
$stmt->execute();
echo $sql;
echo '<ul>';
foreach ($stmt->fetchAll() as $emps){
echo "<li>" . $emps["FirstName"] . $emps["LastName"] . "</li>";
}
echo '</ul>';
$stmt = null;
}
catch (Exception $e) {
echo "Error";
echo $e->getMessage();
}
?>
I even have the program echo the SQL query and I copy that into MySQL and it still works. Could it be a simple syntax error or is it the table joins that im performing?
Also im certain that the program is contacting the database correctly because I have other similar PHP files working properly like this one:
<?php
try {
$sql = 'SELECT department.Name FROM adventureworks.department';
$stmt = $dbh->prepare($sql);
$stmt->execute();
echo '<ul>';
foreach ($stmt->fetchAll() as $depts) {
echo "<li>" . $depts["Name"] . " -> (" .
"<a href='deptEmps.php?deptID=" . $depts['deptID']
. "'>Employees </a>)" . "</li>\n";
}
echo '</ul>';
$stmt = null;
}
catch (Exception $e) {
echo "Error";
echo $e->getMessage();
}
?>

The problem with the PHP script was that I was not specifying which tables to select from. This was harder than it should have been since the syntax above returned data in MySQL which was the database I was accessing, The correct PHP script that is working can be found below:
Working PHP:
<?php
try {
$sql = 'SELECT contact.FirstName,contact.LastName ';
$sql .= 'FROM adventureworks.employeedepartmenthistory ';
$sql .= 'JOIN adventureworks.employee USING(EmployeeID) ';
$sql .= 'JOIN adventureworks.contact USING(ContactID) ';
$sql .= 'WHERE DepartmentID = 2';
$stmt = $dbh->prepare($sql);
$stmt->execute();
echo $sql;
echo '<ul>';
foreach ($stmt->fetchAll() as $emps){
echo "<li>" . $emps["FirstName"] . $emps["LastName"] . "</li>";
}
echo '</ul>';
$stmt = null;
}
catch (Exception $e) {
echo "Error";
echo $e->getMessage();
}
?>
I was wrong that the tables would have been assumed through the JOIN in PHP as they are in MySQL.

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;
?>

How to fetch main, sub and child categories from three tables. PHP MYSQLI

i am working on a project, in which i want to use Categories and their Sub and Child categories, i've created 3 tables ( MainCats, SubCats, ChildCats ).
now i want to fetch data from those tables and want to store in option of HTML.
Here is code PHP, MYSQLI and HTML code.
$cat_fetch = "SELECT categories, sub_categories, child_categories FROM categories.maincatSd, sub_categories.subcat_name, child_categories.child_cat_name";
$cat_run = mysqli_query($con, $cat_fetch);
echo "<option value='' >ڪيٽيگري چونڊيو</option>";
if(mysqli_num_rows($cat_run) >0){
while($cat_row = mysqli_fetch_array($cat_run)){
$cat_name = $cat_row['child_cat_name'];
$cat_name = $cat_row['subcat_name'];
$cat_name = $cat_row['maincatSd'];
//$cat_name = $cat_row['subcat_name'];
echo "<option value='".$cat_name."' ".((isset($Catagory) and $Catagory == $cat_name)?"selected":"")." >".ucfirst($cat_name)."</option>";
}
}else{
echo "<option name='Catagory' tabindex='2' id='Catagory' value=''>NoCat</option>";
}
From the output of your given image.. I don't feel you need to maintain any kind of relation at the time of fetching records from tables. It just needs to fetch records from those three tables & build the options list & print show on the web page. If that's exactly what you want, then check out this.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Connect to DB
$mysqli = new mysqli('127.0.0.1', 'host', 'password', 'DB_Name');
if ($mysqli->connect_errno) {
echo "Error: Failed to make a MySQL connection, here is why: \n";
echo "Errno: " . $mysqli->connect_errno . "\n";
echo "Error: " . $mysqli->connect_error . "\n";
exit;
}
// ---Fetch all main category records---
$sql = "SELECT * FROM main_cat";
if (!$result = $mysqli->query($sql)) {
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$totRecordsMainCat= array();
if($result->num_rows){
while($dataSource = $result->fetch_assoc()){
$totRecordsMainCat[] = $dataSource;
}
}
// ---Fetch all Sub category records---
$sql = "SELECT * FROM sub_cat";
if (!$result = $mysqli->query($sql)) {
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$totRecordsSubCat= array();
if($result->num_rows){
while($dataSource = $result->fetch_assoc()){
$totRecordsSubCat[] = $dataSource;
}
}
// ---Fetch all Child category records---
$sql = "SELECT * FROM child_cat";
if (!$result = $mysqli->query($sql)) {
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$totRecordsChildCat= array();
if($result->num_rows){
while($dataSource = $result->fetch_assoc()){
$totRecordsChildCat[] = $dataSource;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo "<select>";
echo "<option value=''>Select Category</option>";
foreach ($totRecordsMainCat as $key => $value)
{
$cat_name = $value['cat_name'];
echo "<option value='$cat_name'>$cat_name</option>";
}
foreach ($totRecordsSubCat as $key => $value)
{
$cat_name = $value['subcat_name'];
echo "<option value='$cat_name'>$cat_name</option>";
}
foreach ($totRecordsChildCat as $key => $value)
{
$cat_name = $value['childcat_name'];
echo "<option value='$cat_name'>$cat_name</option>";
}
echo "</select>";
?>
</body>
</html>
Why not do it using 3 different queries and nested loops..
SELECT * FROM main_cat
// Loop query result
SELECT * FROM sub_cat WHERE sub_cat_id = main_cat_id
// Loop query result
SELECT * FROM child_cat WHERE child_cat_id = sub_cat_id
// Loop query results

HTML & PHP | Filling a select with a query

I have a function that uses mysqli function that is as follows:
public function GetProjectOptions()
{
$return = "";
$sql = "SELECT `id`, `project_name` FROM `projects`;";
$rs = static::$link->query($sql);
$return .= '<select class="form-control" name="project">';
while ($result = mysqli_fetch_assoc($rs));
{
$return .= "<option value='" . $result['id'] . "'>" .
$result['project_name'] . "</option>";
}
$return .= '</select>';
return $return;
}
The purpose of this function is to create the options and select that will be used for the Projects on my site, I know that there are 4 projects currently stored in the table, but they do not return in this function, what have I done wrong?
EDIT:
Link to screen output: (http://i.imgur.com/YIYiheH.png)
Link to code output: (http://i.imgur.com/RZsUIwQ.png)
Link to code usage: (http://i.imgur.com/4J9rvd7.png)
(Wouldn't let me do normal links)
I found the problem.
Remove the semi-colon here
while ($result = mysqli_fetch_assoc($rs));
^
that's why it's not throwing an error, because it's considered as valid syntax.
Your loop is being stopped/terminated by it.
What I think Jay and Styphon mean by their comment is that you don't do any error checking within your SELECT query. Are you sure your query is executing properly? I understand this is a relatively simple query and that you're positive there are four projects currently stored in your table, but it's always a good habit to check. Try this:
public function GetProjectOptions()
{
$return = "";
$sql = "SELECT `id`, `project_name` FROM `projects`;";
$rs = static::$link->query($sql);
$return .= '<select class="form-control" name="project">';
if($rs){
while ($result = mysqli_fetch_assoc($rs));
{
$return .= "<option value='" . $result['id'] . "'>" . $result['project_name'] . "</option>";
}
$return .= '</select>';
}else{
$message = 'Invalid query: ' . mysqli_error() . "\n";
$message .= 'Whole query: ' . $sql;
die($message);
}
return $return;
}
I hope this helps!

my pdo connection doesn't work

Echoing to my previous question about SQL-injection. I'm trying to set up a PDO connection.
For that I want to replace my old code with the new:
Here is the old
$conn = mysql_connect("localhost", "sec", "dubbelgeheim") or
die('Error: ' . mysql_error());
mysql_select_db("bookshop");
$SQL = "select * from productcomment where ProductId='" . $input . "'";
$result = mysql_query($SQL) or die('Error: ' . mysql_error());
$row = mysql_fetch_array($result);
if ($row['ProductId']) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
} else
echo "No Record!";
mysql_free_result($result);
mysql_close();
And here is the new:
$input = $_GET['input'];
if ($input) {
$user= 'sec';
$pass = 'dubbelgeheim';
try {
$dbConn = new PDO('mysql:host=127.0.0.1;dbname=bookshop', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$escaper = $db->real_escape_string($input);
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $escaper);
$statement->execute();
$result = $statement->get_result();
$statement->close();
$count = $result->num_rows;
if ($count > 0) {
while ($row = $result->fetch_assoc()) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
}
}
else {
echo 'No record!';
}
$result->free();
$db->close();
}
When I tried this new code.. It gives the following error:
Error!: SQLSTATE[HY000] [1045] Access denied for user
'sec'#'localhost' (using password: YES)
I also tried to replace localhost with 127.0.0.1.
My goal is to make my page secure for SQL-injection.
May anyone have a great solution!
The code looks ok at first glance.
Try this solution. It looks like this anonymus user might be the problem.
EDIT: (as suggedted in comments)
In summary:
The recommended solution is to drop this anonymous user. By executing
DROP USER ''#'localhost';

$_Get not getting url id

*fixed****
echo "<li>" . $row['iname'] . "</li>";
what is missing ?
.php
/facepalm
I can't seem to get the id value to pass to the $_GET. I've tried adding sessions and all kinds of stuff.
Even when I just do a print_r($GET) by itself it gives me :
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for
this address in a way that will never complete
This is not for production, but a project so I'm not to worried about injections ect..
I've use GET with old php mysql syntax and it works, just not sure what the problem is. Alos no the code is barbaric so any help would be greatly appreciated.
Page 1 :
<?php
require('lib/inc/db_inc.php');
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice,iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE items.itype = 'usb_controllers'";
$stmt = $db->query($sql);
while ($row = $stmt->fetch()){
$id = $row['itemID'];
echo "<div class=\"prodMain\">";
echo "<div class=\"img\">";
echo "<img src=\"" . $row['imgURL'] ."\"/>";
echo "</div>";
echo "<ul>";
echo "<li>" . $row['iname'] . "</li>";
echo "<li>" . $row['idesc'] . "</li>";
echo "<li>" . $row['iprice'] . "</li>";
echo "</ul>";
echo "</div>";
}
?>
page 2 :
<?php
require('../lib/inc/db_inc.php');
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice,iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE itemID = '$id'";
$stmt = $db->query($sql);
$row = $stmt->fetch();
echo print_r($row);
?>
db_inc.php
<?php
try {
$db = new PDO('mysql:host=******;dbname=*****', '*********', '********');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
This statement
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice, iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE itemID = '$id'";
$stmt = $db->query($sql);
has a vulnerability for SQL Injection. See here.
So you should rewrite it like
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice, iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE itemID = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));

Categories