I am trying to while loop information into a SELECT statement, then COUNT the results. I have tried at least 10 different "solutions" and none works. I only get 0, 1, or nothing. Here's my most recent attempt:
$query35 = "SELECT * FROM movies WHERE userID = $memberID";
$result35 = $db->query($query35);
while ($row35 = $result35->fetchAll(PDO::FETCH_ASSOC)) {
$movie = $row35['movie'];
$query36 = "SELECT COUNT(*) AS similar FROM movies WHERE userID = '$profileID' && movie = '$movie'";
$result36 = $db->query($query36);
$row36->fetchObject;
$similar = $row36['similar'];
echo $similar;
}
$row36->fetchObject;
Seems null object, I think it should be
$row36 = $result36->fetchObject();
If all you are looking to do is count the number of times your loop is run per script execution, then it is fairly simple to do. See below:
$count = 0;
while($row35 = $result35->fetch(PDO::FETCH_ASSOC)){
//Do all your loop stuff.
$count++;
}
var_dump($count);
Important to note that your $count variable needs to be declared outside of your loop.
Also you either need to use fetchAll with a foreach loop, or use fetch with a while loop, but don't mix them.
Also a tip on good practice. Try to avoid as much as possible executing any kind of database querying with a loop, you can run into serious performance issues down the line as your loops get bigger.
Not sure what are you doing. But at least try:
$query35 = "SELECT * FROM movies WHERE userID = $memberID";
$result35 = $db->query($query35);
if ($row35 = $result35->fetchAll(PDO::FETCH_ASSOC))
foreach ($row35 as $row) {
print_r($row);
}
or maybe
$query35 = "SELECT * FROM movies WHERE userID = $memberID";
$result35 = $db->query($query35);
while ($row = $result35->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
$movie = $row['movie'];
$query36 = "SELECT COUNT(*) AS similar FROM movies WHERE userID = '$profileID' && movie = '$movie'";
$result36 = $db->query($query36);
$obj = $result36->fetchObject();
$similar = $obj->similar;
echo $similar;
}
Related
I have a very strange problem today. I have a section of code which queries a table based on a GET variable passed from a user input (pretty standard).
However for this to work I have to include a redundant mysql_num_rows variable....
This Works;
<?php
1. $cat = strval($_GET['c']);
2. $query = "SELECT * FROM stock WHERE Category = '$cat'";
3. $num_rows = mysql_num_rows(mysql_query($query));
4. $values = mysql_query($query);
?>
For some reason without line 3 it doesn't work.
By the way this is ultimately used to create an array passed to a google chart which is all fine.
What am I doing wrong?
All code for reference;
<?php
$cat = strval($_GET['c']);
$query = "SELECT * FROM stock WHERE Category = '$cat'";
LINE UNDER QUESTION --> $num_rows = mysql_num_rows(mysql_query($query));
$values = mysql_query($query);
$material = array();
$quantity = array();
$colour = array();
while ($row = mysql_fetch_array($values)) {
array_push($material, $row['Material']);
array_push($quantity, $row['Quantity']);
array_push($colour, $row['Colour']);
}
...Then all the google chart stuff....
?>
Specify columns in the select and use an index.
And make sure the $_GET value is validated.
You probably already have done this, but try the query in e.g. phpMyAdmin.
Maybe all this will help.
SELECT
material,
quantity,
colour
FROM
stock
WHERE
Category = ...
ORDER BY ..
;
I'm using my mysqli query as JSON output.
This is my query:
$sql = "SELECT p.*,comments.*,COUNT(comments.id) AS numComments FROM people AS p
LEFT JOIN comments ON comments.people_id = p.id
WHERE p.name LIKE '%".$data."%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myArray[] = $row;
}
echo json_encode($myArray);
} else {
echo 0;
}
What I want to do, is to group all the person comments and place it under the person data. for example:
The desired output is that I will be able to access the comments not directly from the query, but from the person itself.
for example:
echo $person['comment'][0]['content']
Currently, I access it like any of the query data..
echo $person['content']
JSON OUTPUT:
As you can see, the person data and the comment data is mixed in the same array. I want the comments to have an array of their own.
Any ideas?
Edit: Seem like I have problem with the query. it returns only the first comment!
You need so-called eager loading for this task. It will involve two queries, but it will be way better than one.
You have to select your people first, then get people ids and query comments table for the comments. And finally you will have to combine the two arrays together.
I will use PDO as it will take 5 times less code to write, thanks to some neat PDO features.
$stmt = $conn->prepare("SELECT * FROM people WHERE name LIKE ?");
$stmt->execute(["%$data%"]);
$people = $stmt->fetchAll(PDO::FETCH_UNIQUE);
$ids = array_keys($people);
$in = str_repeat('?,', count($ids) - 1) . '?';
$stmt = $db->prepare("SELECT people_id, * FROM comments WHERE people_id IN ($in)");
$stmt->execute($ids);
$comments = $stmt->fetchAll(PDO::FETCH_GROUP);
foreach($people as $id=>$row)
{
$row['comments'] = $comments[$id];
$people[$id] = $row;
}
I have an array of tag names which I passed via POST Method and I these tag names has its corresponding tag_id in the database. All I want is to search the id while iterating the array of tag names and I want the result of each query to be stored in an empty array. I think I just misunderstood something or what.
$tags_array = ['shoes','gadgets','fashion','food'];
$tags_array_id = [];
$tags_sql = '';
foreach ($tags_array as &$tag) {
$sql = "SELECT tag_id FROM `tbltag` WHERE tag_name = ".$tag." group by tag_name";
$query = mysqli_query($conn, $sql);
$result = mysqli_fetch_row($query);
$tags_array_id[] = $result[0];
};
Please help guys, suggestions highly appreciated.
Basically something like:
$sql = "SELECT * FROM `tbltag` WHERE tag_name IN('".implode("','", $tags_array)."')";
One last comment: You probably want to search for tag_id's instead of tag names, as you'll probably have those in your input ($_POST/$_GET). And as FuzzyTree has mentioned above, you'll want some type of ID validation and some kind of escaping of data going into the query to avoid SQL injection.
Use this instead
$tags_array = ['shoes','gadgets','fashion','food'];
$tags = implode("','", $tags_array);
$tags = "'".$tags."'";
$sql = "SELECT tag_id FROM tbltag WHERE tag_name IN ({$tags})";
Question: Do you need the & in your foreach loop? You are not directly modifying the tags_array just using the information?
Trying adding the number to the array e.g add $x so you are adding in 1 record into 1 part of the array as you loop though.
$tags_array = ['shoes','gadgets','fashion','food'];
$tags_array_id = [];
$tags_sql = '';
$x = 0;
foreach ($tags_array as &$tag) {
$sql = "SELECT tag_id FROM `tbltag` WHERE tag_name = ".$tag." group by tag_name";
$query = mysqli_query($conn, $sql);
$result = mysqli_fetch_row($query);
$tags_array_id[$x] = $result[0];
$x++;
};
I am running the following code, which runs a query, gets all the student_id's in a class, then for each student id it gets all their grades. My problem is though that the data put into the array doesnt stay in it when it goes back and runs the for loop for the second, third, etc student. Is there a way to keep the data in the array and keep adding to it? I have included some code below to help paint the picture. Thanks All
$sql = "SELECT student_id FROM users_table WHERE class_id ='5'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$row_cnt = mysqli_num_rows($result);
$students = array();
for($y=0; $y<$row_cnt; $y++)
{
array_push($students, $row['student_id']);
$sql2 = "SELECT student_grade FROM grades_table WHERE student_id ='".$students[$y]."'";
$result2 = $db->sql_query($sql2);
$row2 = $db->sql_fetchrow($result2);
$row_cnt2 = mysqli_num_rows($result2);
for($z=0; $z<$row_cnt2; $z++)
{
array_push($students, array($row['student_grade']));
}
}
In the second sql2 part you may want to do something like this instead:
for($z=0;$z<$row_cnt2;$z++) {
$students[$row['student_id']] = $row['student_grade'];
}
Doing it like this, your array doesn't get overwritten, and you'll get something like this:
array(
5 => "A"
6 => "B"
)
Where 5 is the student_id and A is the grade.
But, of course, this can also easily be solved with the JOIN query Mark Baker provided.
What's the "larger query" you're writing?
What you are doing at the moment will make the students array look like a big basket with everything poured in... You should create an index then assign the grades array to it
$students = array();
for($i = 0; $i < $row_cnt; $i++)
{
$sql2 = "SELECT student_grade FROM grades_table WHERE student_id ='".$students[$y]."'";
$result2 = $db->sql_query($sql2);
$row2 = $db->sql_fetchrow($result2);
$row_cnt2 = mysqli_num_rows($result2); //probably don't need this count anymore
$students[$row['student_id']] = $row2;
}
You should take note of Mark's comment... it provides a more elegant way. Also learn about prepared statements and how the help prevent SQL injection
The following goes into an endless loop, meaning it just constantly shows the same record over and over and over again.
<?php
while ($rowr = mysql_fetch_assoc(mysql_query("SELECT * FROM table1")) {
while($rowu = mysql_fetch_assoc(mysql_query("SELECT * FROM table2 WHERE id = '".$rowr['uid']."'"))){
while($rowc = mysql_fetch_assoc(mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'"))){
?>
<tr><td><?php echo $rowc['post']; ?></td><td><?php echo $rowu['username']; ?></td><td><font color="#FF0000">X</font></td></tr>
<?php
};
};
};
?>
Why does that happen and how can I fix it?
You are putting the mysql query in the while statement so every time it gets there it does the same query and shows the same first record, you are never advancing to the next record in the result set.
Personally I would combine all queries into one, but to show how you can solve your problem (the same applies to all loops):
$results = mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'");
while ($rowc = mysql_fetch_assoc($results))
{
// do stuff
}
Simply because the query gets executed again every time the loop condition is checked. That means you'll always get the same result unless something changes in the database in the meantime.
You need something like this:
<?php
$res1 = mysql_query("SELECT * FROM table1");
while ($rowr = mysql_fetch_assoc($res1)) {
$res2 = mysql_query("SELECT * FROM table2 WHERE id = '".$rowr['uid']."'");
while($rowu = mysql_fetch_assoc($res2)){
$res3 = mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'");
while($rowc = mysql_fetch_assoc($res3)){
?>
<tr><td><?php echo $rowc['post']; ?></td><td><?php echo $rowu['username']; ?></td><td><font color="#FF0000">X</font></td></tr>
<?php
}
}
}
?>
That's just to illustrate why it doesn't work. As others already noted, combining your queries into one using JOIN would be advisable.
Btw, you don't need a ; after a {} block.
Use joins and you can do it in one query.
Mysql Join
Join Tutorial
You're re-executing the queries on each loop iteration, restarting the results from scratch.
You want something like this instead:
$resultR = mysql_query("... table1");
while($rowR = mysql_fetch_assoc($resultR)) {
$resultU = mysql_query("... table2");
while($rowU = mysql_fetch_assoc($resultU)) {
etc...
}
}
Of course, this is a highly inefficient construct. You end up running count($rowR) * count($rowU) * count($rowC) queries. Why not reformulate it as a join?