Run a second query inside a foreach loop? - php

Need to run 2 queries inside a foreach but cant do it without errors.
So, i have this for showing comments:
$query = 'SELECT * FROM comments WHERE updatepostid = "' . $postID . '"';
try {
$stmt = $db->prepare($query);
$stmt->execute();
$countcomments = $stmt->rowCount();
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
foreach ($rows as $row):
$commentID = $row['commentID'];
$usercommentID = $row['userID'];
$commentusername = ucfirst($row['commentusername']);
$comment = ucfirst($row['comment']);
$updatepostid = $row['updatepostid'];
<div class="textcomment">
<?php
echo "<a class='$rightscommentcolor'>$commentusername:</a> $comment";
?>
</div>
<?php endforeach; ?>
I then however want to run another query on the users database to check what rights the user has and then set the class of the comments username to that class.
That query would be e.g.
<?php
$query2 = 'SELECT * FROM users WHERE id = "' . $usercommentID . '"';
try {
$stmt = $db->prepare($query2);
$stmt->execute();
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
foreach ($rows as $row):
$rights = $row['rights'];
if ($rights = '1') {
$rightscommentcolor = 'userrights1';
} else if ($rights = '5') {
$rightscommentcolor = 'userrights5';
}
?>
<?php endforeach; ?>
How is the proper way to go about this?
P.S. i understand that the above code will probably make people cry.

Use a single query with a join. Also, since you're using PDO, you should use parametrized queries rather than concatenating strings.
$query = "SELECT * FROM comments c
JOIN users u ON u.id = c.userID
WHERE updatepostid = :updatepostid";
try {
$stmt = $db->prepare($query);
$stmt->execute(array(':updatepostid' => $postID));
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}

You can join the tables in select as mentioned:
<?php
$query = "SELECT * FROM comments c
JOIN users u ON u.usercommentID = c.userID
WHERE updatepostid = :updatepostid";
try {
$stmt = $db->prepare($query);
$stmt->execute();
$countcomments = $stmt->rowCount();
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
foreach ($rows as $row):
$commentID = $row['commentID'];
$usercommentID = $row['userID'];
$commentusername = ucfirst($row['commentusername']);
$comment = ucfirst($row['comment']);
$updatepostid = $row['updatepostid'];
if ($rights = '1') {
$rightscommentcolor = 'userrights1';
} else if ($rights = '5') {
$rightscommentcolor = 'userrights5';
}
echo "<div class="textcomment"><a class='$rightscommentcolor'>$commentusername:</a> $comment</div>";
endforeach;
?>
You also could insert the second loop within the first and assign separate variables to that second loop so that it does not conflict with the first as below, but joining would be a better option:
<?php
$query = 'SELECT * FROM comments WHERE updatepostid = "' . $postID . '"';
try {
$stmt = $db->prepare($query);
$stmt->execute();
$countcomments = $stmt->rowCount();
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
foreach ($rows as $row):
$commentID = $row['commentID'];
$usercommentID = $row['userID'];
$commentusername = ucfirst($row['commentusername']);
$comment = ucfirst($row['comment']);
$updatepostid = $row['updatepostid'];
$query2 = 'SELECT * FROM users WHERE usercommentID = "' . $usercommentID . '"';
try {
$stmt2 = $db->prepare($query2);
$stmt2->execute();
}
catch (PDOException $ex2)
{
die("Failed to run query: " . $ex2->getMessage());
}
$rows2 = $stmt2->fetchAll();
foreach ($rows2 as $row2):
$rights = $row2['rights'];
if ($rights = '1') {
$rightscommentcolor = 'userrights1';
} else if ($rights = '5') {
$rightscommentcolor = 'userrights5';
}
endforeach;
echo "<div class="textcomment"><a class='$rightscommentcolor'>$commentusername:</a> $comment</div>";
endforeach;
?>

Related

Trying to get property of non-object CRUD

I am making a CRUD system for blog publications, but it's kinda strange, another developer (with more experience) looked to my coded and for him it's all right too, but this error (Notice: Trying to get property of non-object in C:\xampp\htdocs\genial\painel\inc\database.php on line 32) remains appearing.
My database code:
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
function open_database() {
try {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
return $conn;
} catch (Exception $e) {
echo $e->getMessage();
return null;
}
}
function close_database($conn) {
try {
mysqli_close($conn);
} catch (Exception $e) {
echo $e->getMessage();
}
}
function find( $table = null, $id = null ) {
$database = open_database();
$found = null;
try {
if ($id) {
$sql = "SELECT * FROM" . $table . " WHERE id = " . $id;
$result = $database->query($sql);
if ($result->num_rows > 0) {
$found = $result->fetch_assoc();
}
}
else {
$sql = "SELECT * FROM " . $table;
$result = $database->query($sql);
if ($result->num_rows > 0) {
$found = $result->fetch_all(MYSQLI_ASSOC);
}
}
} catch (Exception $e) {
$_SESSION['message'] = $e->GetMessage();
$_SESSION['type'] = 'danger';
}
close_database($database);
return $found;
}
function find_all( $table ) {
return find($table);
}
function save($table = null, $data = null) {
$database = open_database();
$columns = null;
$values = null;
//print_r($data);
foreach ($data as $key => $value) {
$columns .= trim($key, "'") . ",";
$values .= "'$value',";
}
$columns = rtrim($columns, ',');
$values = rtrim($values, ',');
$sql = "INSERT INTO " . $table . "($columns)" . " VALUES " ($values);";
try {
$database->query($sql);
$_SESSION['message'] = 'Registro cadastrado com sucesso.';
$_SESSION['type'] = 'success';
} catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
function update($table = null, $id = 0, $data = null) {
$database = open_database();
$items = null;
foreach ($data as $key => $value) {
$items .= trim($key, "'") . "='$value',";
}
$items = rtrim($items, ',');
$sql = "UPDATE " . $table;
$sql .= " SET $items";
$sql .= " WHERE id=" . $id . ";";
try {
$database->query($sql);
$_SESSION['message'] = 'Registro atualizado com sucesso.';
$_SESSION['type'] = 'success';
}
catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
Sorry if it's not right idled.
I put an space on the code after the "FROM" at
$sql = "SELECT * FROM" . $table . " WHERE id = " . $id;
The error remains the same but know on line 36 that is:
if ($result->num_rows > 0) {
$found = $result->fetch_all(MYSQLI_ASSOC);
}
Turned the code on line 36 to:
$if (result = $database->query($sql)) {
The error disappeared, others problems not relative to this question happened.
Just in case this question isn't closed as off-topic -> typo generated, I'd better provide an acceptable answer.
Add a space between FROM and $table in your SELECT query.
Check for a non-false result from your query.
Your new code could look like this:
$sql = "SELECT * FROM `$table`";
if ($id) {
// assuming id has been properly sanitized
$sql .= " WHERE id=$id"; // concatenate with WHERE clause when appropriate
}
if ($result = $database->query($sql)) { // only continue if result isn't false
if ($result->num_rows) { // only continue if one or more row
$found = $result->fetch_all(MYSQLI_ASSOC); // fetch all regardless of 1 or more
}
}
$sql = "INSERT INTO " . $table . "($columns)" . " VALUES " ($values);"; has too many double quotes in it -- you can tell by how Stack Overflow highlights the characters. I could say that you could clean up the syntax, but it would ultimately be best to scrap your script and implement prepared statements.

$_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']));

Prepared statements doesn't return results

I trying to do all my querys with prepared statements but is new for me and I have some troubles. This is first query and doesn't echo result from table. This is what I've done so far. May be is realy newbie question but is something completely new for me.
if(isset($_GET['joke_id'])){
$joke_id = $_GET['joke_id'];
$qry = $con->prepare("SELECT * FROM joke WHERE joke_cat = ?");
$qry->bind_param('i', $joke_id);
$qry->execute();
$result = $qry->get_result();
$result->fetch_array();
$result = mysqli_query($con, $qry) or die("Query failed: " . mysqli_errno($con));*/
$line = mysqli_fetch_array($result, MYSQL_BOTH);
if (!$line) echo '';
$previd = -1;
$currid = $line[0];
if (isset($_GET['id'])) {
$previous_ids = array();
do {
$previous_ids[] = $line[0];
$currid = $line[0];
if ($currid == $_GET['id']) break;
$previd = end($previous_ids);
$line = mysqli_fetch_array($result, MYSQL_BOTH);
} while ($line);
}
if ($line) {
echo "<div id=\"box\">";
echo nl2br($line['text']) . "<br /><br />";
echo "<div id=\"share\"><span class='st_facebook' displayText='Facebook'></span>
<span class='st_twitter' displayText='Tweet'></span>
<span class='st_googleplus' displayText='Google +'></span></div>";
echo '<br /><br /><br />';
echo "</div>";
}
else echo '<p>Empty category</p><br/>';
This is what I use right now before to try PDO and it's work with no problems.
qry = "SELECT * FROM joke WHERE joke_cat = '$joke_id'";
$result = mysqli_query($con, $qry) or die("Query failed: " . mysqli_errno($con));
$_GET['joke_id'] and $_GET['joke_cat'] is set ?
or try
$qry = $con->prepare("SELECT * FROM joke WHERE joke_cat =:joke_cat");
$qry->bindParam(':joke_cat', $_GET['joke_cat'], PDO::PARAM_STR);
$qry->execute();
$result = $qry->fetchAll();

Query MySQL using Joomla syntax

The following query is returning the result I expected:
$link=mysqli_connect('localhost','user','pass');
if(!$link){
echo "No connection!";
exit();
}
if (!mysqli_set_charset($link, 'utf8'))
{
echo 'Unable to set database connection encoding.';
exit();
}
if(!mysqli_select_db($link, 'database')){
echo "No database";
exit();
};
$res = $link->query("SELECT rules FROM xmb9d_viewlevels WHERE id=10");
while ($row = $res->fetch_array()) {
echo " cenas = " . $row['rules'] . "\n";
};
But, since I'm using Joomla 2.5.16 and I'm trying to keep its syntax, I tried:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$res = $db->query("SELECT rules FROM #__viewlevels WHERE id=10");
while ($row = $res->fetch_assoc()) {
echo " cenas = " . $row['rules'] . "\n";
};
This isn't working. It is only displaying the text " cenas =".
What is wrong with this code?
Try the following:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('rules'))
->from($db->quoteName('#__viewlevels'))
->where($db->quoteName('id')." = ".$db->quote('10'));
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result) {
echo " cenas = " . $result->rules;
}

Multiple conditions queries with PDO

I asked this question in http://codereview.stackexchange.com and they wanted me to post it here. I couldn't get this code to work at all. I switched from regular mysql to pdo which is more safer. Could someone tell me what I'm missing here. I've been struggling with it for couple of day, and I could find exact answer when I first searched this site.
$input = $_POST['input'];
$categories = $_POST['category'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$qq = $db->prepare(" SELECT * FROM classified ")or die(print_r($qq->errorInfo(), true));
/*** execute the prepared statement ***/
$qq->execute();
/*** echo number of columns ***/
$rows = $qq->fetch(PDO::FETCH_NUM);
if ($rows>0){
$query = (" SELECT * FROM classified ");
$cond = array();
$params = array();
if (!empty($input)) {
$cond[] = "title = ?";
$params[] = $input;
}
if (!empty($categories)) {
$cond[] = "id_cat = ?";
$params[] = $categories;
}
if (!empty($state)) {
$cond[] = "id_state = ?";
$params[] = $state;
}
if (!empty($zipcode)) {
$cond[] = "zipcode = ?";
$params[] = $zipcode;
}
if (count($cond)) {
$query .= ' WHERE ' . implode(' AND ', $cond)or
die(print_r($query->errorInfo(),true));
}
$stmt = $db->prepare($query);
$stmt->execute($params);
$ro = $stmt->fetch(PDO::FETCH_NUM);
}
if ($ro > 0) {
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row)
{
echo $row['title'];
echo $row['categories'];
echo $row['state'];
echo $row['zipcode'];
}
}
I think it's a good idea to post an answer here rather than posting a link. I'm sure it will be useful for some people.
$input = $_POST['input'];
$categories = $_POST['category'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$qq = $db->prepare(" SELECT * FROM classified ")or die(print_r($qq->errorInfo(),
true));
/*** execute the prepared statement ***/
$qq->execute();
/*** echo number of columns ***/
$rows = $qq->fetch(PDO::FETCH_NUM);
if ($rows>0){
$query = " SELECT * FROM classified where confirm='0' ";
if(!empty( $_POST['input'])) {
$query .= "AND title LIKE '%".$input."%' ";
}
if (!empty($_POST['category']) )
{
$query .= "AND id_cat = ".$categories." ";
}
if (!empty($_POST['state']) )
{
$query .= "AND id_state = ".$state." ";
}
if(!empty($_POST['zipcode'])) {
$query .= "AND zipcode = ".$zipcode." ";
}
$query .= "ORDER BY date ";
}
$stmt = $db->prepare($query);
$stmt->execute($params);
$result = $stmt->fetchAll();
// $ro = $stmt->fetch(PDO::FETCH_NUM);
// it didn't work when I tried to count rows
if ($result > 0) {
foreach ($result as $row)
{
echo $row['title'];
echo $row['categories'];
echo $row['state'];
echo $row['zipcode'];
}
}else{
echo " No data available";
}

Categories