execute() gets no results - php

I have two queries here, $check_perms and $get_projects. The former seems to work, but not the latter. There's no error, just no results, yet I know there should be.
$sessionUser = $_SESSION['user_id'];
$check_perms = $db->prepare("SELECT * FROM tasks WHERE id = ?");
$check_perms->bind_param('i', $par);
if ($result = $check_perms->execute())
if ($row = mysqli_fetch_assoc($result))
if ($row['user'] != $sessionUser){
echo "<container>Error. This is not your task.</container>";
exit;
}
$get_projects = Database::connect()->prepare("SELECT * FROM tasks WHERE user = ? ORDER BY weight DESC");
$get_projects->bind_param('i', $sessionUser);
if ($result = $get_projects->execute())
while ($row = mysqli_fetch_assoc($result))
//stuff

Are you sure that tasks.user field is an integer? Try to change:
$check_perms->bind_param('i', $sessionUser);
to
$check_perms->bind_param('s', $sessionUser);

Related

Get All Rows When Variable Empty PHP Mysql

$frame_type = '';
$ret = mysqli_query($con, "select * from products where status='1' AND frame_type = '$frame_type' ");
while ($row = mysqli_fetch_array($ret)) {
$emparray[] = $row;
}
Get All Rows If The $frame_type Is Empty I am trying this way but i get zero rows , How to fix that Where $frame_type has value then send to query else not
There are a some of things that is wrong with your question (code). But if you only want answer. Just copy this
$frame_type = '';
$query = "select * from products where status='1' ";
// strlen has value
if(strlen($frame_type)) {
$query .= "AND frame_type = '$frame_type'";
}
$ret = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($ret)) {
$emparray[] = $row;
}
PS: It's never a safe idea to pass everything to the query. Use prepared statement if you can.

How to nest 2 SQL statements with a foreach loop inside each other

Okay I try with the first query to get all names of the computers from the table psComputers. Now I need in the second query a variable from the first query to iterate over all entries which are assigned to the respective computer in the table psTest. I wonder if such a thing is possible at all?
Table psComputer contains ID, name
Table psTest contains ID, computername, category, value
index.php
$statement = $pdo->prepare("SELECT * FROM psComputers ");
$statement->execute();
$result = $statement->fetchAll();
if ($statement->rowCount() > 0) {
foreach ($statement->fetchAll() as $row) {
$id = $row['ID'];
$name = $row['name'];
$statement2 = $pdo->prepare("SELECT * FROM psTest WHERE computerName = $name");
$statement2->execute();
$result2 = $statement2->fetchAll();
if ($statement2->rowCount() > 0) {
foreach ($statement2->fetchAll() as $row2) {
$id2 = $row2['ID'];
$computerName = $row2['computerName'];
$category = $row2['category'];
$value = $row2['value'];
}
}
}
}
You need quotes around $name in the second query, since it's a string.
$statement2 = $pdo->prepare("SELECT * FROM psTest WHERE computerName = '$name'");
But since you're using a prepared query, you should use a parameter instead of substituting a variable.
You also shouldn't call $statement->fetchAll() twice. The first call will read all the rows, and the second won't have anything left to read (it doesn't reset the cursor).
$statement = $pdo->prepare("SELECT * FROM psComputers ");
$statement->execute();
$result = $statement->fetchAll();
if (count($result) > 0) {
$statement2 = $pdo->prepare("SELECT * FROM psTest WHERE computerName = :name");
$statement2->bindParam(':name', $name);
foreach ($result as $row) {
$id = $row['ID'];
$name = $row['name'];
$statement2->execute();
$result2 = $statement2->fetchAll();
if (count($result2) > 0) {
foreach ($result2 as $row2) {
$id2 = $row2['ID'];
$computerName = $row2['computerName'];
$category = $row2['category'];
$value = $row2['value'];
}
}
}
}
But even better is to just join the two queries:
$statement = $pdo->prepare("
SELECT c.id AS computerID, c.name AS computerName, t.id AS testID, t.category, t.value
FROM psComputers AS c
JOIN psTest AS t ON c.name = t.computerName
ORDER BY c.id");
A couple things to note,
When using strings in queries, they must be quoted.
You are already preparing the statement - bind the value instead, and the note above becomes irrelevant.
You can use a JOIN instead of running a query in a loop. This will also remove the variable in the name, making both notes above irrelevant! (You should take note of both, but they become irrelevant for the code in question).
Its rarely a good idea to run a query within a loop.
$statement = $pdo->prepare("SELECT pt.*
FROM psTest pt
JOIN psComputers pc ON pt.computerName=pc.name");
$statement->execute();
$result = $statement->fetchAll();
if (count($result)) {
foreach ($result as $row) {
$id2 = $row['ID'];
$computerName = $row['computerName'];
$category = $row['category'];
$value = $row['value'];
}
}

How to get number of results from a mysqli query?

So I'm doing this query:
'SELECT * FROM Album WHERE id = ?;'
using a prepare sql statement, and I was wondering how to get the number of results this query returns? B/c since every album id is unique this query should only return 1 album and I want to make sure that its doing that.
Code
$stmt = $mysqli->prepare('SELECT * FROM Album WHERE id = ?;');
$id = 2;
$stmt->bind_param('i', $id);
$executed = $stmt->execute();
$result = $stmt->get_result();
if($row = $result->fetch_assoc()){
$info['id'] = $row['id'];
$info['title'] = $row['title'];
$info['date_created'] = $row['date_created'];
$info['creator'] = $row['creator'];
}
// Send back the array as json
echo json_encode($info);
You can get it using $result->num_rows:
if ($row = $result->fetch_assoc()) {
$info['id'] = $row['id'];
$info['title'] = $row['title'];
$info['date_created'] = $row['date_created'];
$info['creator'] = $row['creator'];
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
}
You can find more details on PHP Documentation.
I want to make sure that its doing that
In your code you are already doing that. The following condition
if($row = $result->fetch_assoc()){
does exactly what you want.
Just use COUNT(*)
SELECT COUNT(*) FROM Album WHERE id = ?;
Reference:
https://dev.mysql.com/doc/refman/5.7/en/counting-rows.html
Another way
$query = $dbh->prepare("SELECT * FROM Album WHERE id = ?");
$query->execute();
$count =$query->rowCount();
echo $count;

Creating an array of IDs from a while loop

Im trying to generate an array but not sure how to go about it.
I'm currently getting my data like so:
$query = mysql_query("SELECT * FROM users WHERE userEmail LIKE 'test#test.com'");
$row = mysql_fetch_array($query);
$query1 = mysql_query("SELECT * FROM categories");
while($row1 = mysql_fetch_array($query1)){
$query2 = mysql_query("SELECT * FROM usersettings WHERE userId = ".$row['userId']." AND usersettingCategory".$row1['categoryId']." LIKE 'y'");
$isyes = mysql_num_rows($query2);
if($isyes > 0){
$cat1 = mysql_query("SELECT * FROM shops WHERE shopstateId = 1 AND (categoryId1 = ".$row1['categoryId']." OR categoryId2 = ".$row1['categoryId']." OR categoryId3 = ".$row1['categoryId'].")");
$cat1match = mysql_num_rows($cat1);
if($cat1match > 0){
while($cat1shop = mysql_fetch_array($cat1)){
$cat1msg = mysql_query("SELECT * FROM messages WHERE shopId = ".$cat1shop['shopId']." and messagestateId = 1");
while($cat1msgrow = mysql_fetch_array($cat1msg)){
echo $cat1msgrow['messageContent']." - ".$cat1msgrow['messageCode'];
$cat1img = mysql_query("SELECT shopimagePath FROM shopimages WHERE shopimageId = ".$cat1shop['shopimageId']);
$imgpath = mysql_fetch_array($cat1img);
echo " - ".$imgpath['shopimagePath']."<br/>";
}
}
}
}
}
But this can cause duplicates when a user has all 3 of a shops categories picked in their preferences. I am trying to find a way to just pull the message ID out instead of the whole thing and put it into an array giving me, for example:
1,3,5,7,1,3,5,2,4,7,8
Then I can just run a separate query to say get me all messages where the ID is in the array, but i am unsure of the most constructive way to build such an array and examples of array from a while loop I have seen do not seem to be what I am looking for.
Is there anyone out there that can push me in the right direction?
Can't help with this code. But if you want an array from a query without duplicate result, you can use " select DISTINCT (id) " in your query or for more simple solution :
$id_arr = array();
$sql = mysql_query("select id from id_table");
while ($id_result = mysql_fetch_array($sql) {
$id = $id_result['id'];
if (!in_array($id, $id_arr)) {
$id_arr[] = $id;
}
}
I have found a much easier way to create the required result. I think at 6am after a hard night coding my brain was fried and I was making things a lot more complicated than I needed to. A simple solution to my issue is as follows:
$query = mysql_query("SELECT * FROM users WHERE userEmail LIKE 'test2#test2.com'");
$row = mysql_fetch_array($query);
$categories = "(";
$query1 = mysql_query("SELECT * FROM categories");
while($row1 = mysql_fetch_array($query1)){
$query2 = mysql_query("SELECT usersettingCategory".$row1['categoryId']." FROM usersettings WHERE userId = ".$row['userId']);
$row2 = mysql_fetch_array($query2);
if($row2['usersettingCategory'.$row1['categoryId']] == y){
$categories .= $row1['categoryId'].",";
}
}
$categories = substr_replace($categories ,")",-1);
echo $categories."<br />";
$query3 = mysql_query("SELECT * FROM shops,messages WHERE shops.shopId = messages.shopId AND messages.messagestateId = 1 AND (shops.categoryId1 IN $categories OR shops.categoryId2 IN $categories OR shops.categoryId3 IN $categories)");
while($row3 = mysql_fetch_array($query3)){
$query4 = mysql_query("SELECT shopimagePath FROM shopimages WHERE shopimageId = ".$row3['shopimageId']);
$row4 = mysql_fetch_array($query4);
echo $row3['messageContent']." - ".$row3['messageCode']." - ".$row4['shopimagePath']."<br />";
}

Checking if mysql_query returned anything or not

$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
If 'table' has no rows. whats the easiest way to check for this.?
Jeremy Ruten's answer above is good and executes quickly; on the other hand, it only gives you the number of rows and nothing else (if you want the result data, you have to query the database again). What I use:
// only ask for the columns that interest you (SELECT * can slow down the query)
$query = "SELECT some_column, some_other_column, yet_another_column FROM `table`";
$results = mysql_query($query, $connection);
$numResults = mysql_num_rows($results);
if ($numResults > 0) {
// there are some results, retrieve them normally (e.g. with mysql_fetch_assoc())
} else {
// no data from query, react accordingly
}
You could use mysql_num_rows($results) to check if 0 rows were returned, or use this faster alternative:
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
Alternatively you can simply check if the result of mysql_fetch_assoc is false.
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
$Row = mysql_fetch_assoc($results);
if ($Row == false)
{
$Msg = 'Table is empty';
}
One thing i noticed that was missed was the fact that the query might not succeed, so you do need to check if the $results variable is set. I'll use the answer given by yjerem as an example.
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
if ($results) { // or use isset($results)
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
}
If you loop through the results, you can have a counter and check that.
$x = 1;
$query = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($query))
{
$x++;
}
if($x == 1)
{
//No rows
}

Categories