mysql_query function only works with mysql_num_rows - php

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

Related

Create a randomized assoc array from database table results

I am creating a simple drag and drop jquery game and it requires a shuffled resultset of 10 rows from my database table. I am able to achieve this by repeating 10 separate blocks of queries, but I am sure there must be a more elegant way to do this. I tried many things, with loops and append etc. but I can't get the loop-way working.
I can't get this loop version to work:
<script type="text/javascript">
<?php
// first create list of 10 fake id's and shuffle them
$id_array = range(0, 9);
shuffle($id_array);
/*
// then loop to fetch all data from MySql table with spanish, english
// CANNOT GET THIS WORKiNG ?
for (i = 0; i < 10; i++) {
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[i]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$rand_value.append(i) = $row['english'];
$name.append(i) = strtoupper($row['spanish']);
}
*/
Writing it out works, but there must be an easier way...
<script type="text/javascript">
<?php
// create all input from MySql table for drag and drop area with spanish, english
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[0]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$random_key0 = $row['id'];
$rand_value0 = $row['english'];
$name0 = strtoupper($row['spanish']);
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[1]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$random_key1 = $row['id'];
$rand_value1 = $row['english'];
$name1 = strtoupper($row['spanish']);
// and so on to run 10 queries total
?>
Simplify everything by using RAND() in your query. Use just one query and retrieve all ten rows in a shuffled order.
$query="SELECT id,english,UPPER(spanish) FROM colors ORDER BY RAND() LIMIT 10;";
$result=mysqli_query($link,$query);
while($row=mysqli_fetch_array($result)){
// prepare and handle your results using: $row['id'], $row['english'], $row['spanish']
}
EDIT: I've added UPPER() to the query so that the spanish values don't need to be modified later in your php.

Don't query SQL string if value is empty

I have two drop down menu's and when you select a value the value is saved in a session and passed trough AJAX to update a div. I have this working.
The reason I save the value in a session is because I need the database query to be dynamically filled (constructed). At this moment I have the following code:
<?php
$q = $_GET['q'];
$_SESSION['theme'] = $q;
$i = $_SESSION['category'];
$query = "SELECT COUNT(".$q.") c FROM MirrorWebProductsExpanded WHERE Subcategorie = '".$i."'";
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_assoc($result);
echo "
<a href='http://example.nl/search/'>" . $row['c'] . "</a>";
?>
This counts all items from $q which is the value of the first drop down menu.
And WHERE Subcategorie = '".$i."', $i is the value from the second drop down menu.
But, now the problem. If the second value is empty (I haven't selected an option from that drop down menu) the query still add's this part to the query, like:
$query = "SELECT COUNT(".$q.") c FROM MirrorWebProductsExpanded WHERE Subcategorie = ''";.
This makes the count from the first drop down menu always show 0. Is there away to only add the WHERE Subcategorie = '".$i."' when the second drop down menu has a value?
I'm still kind of new to MySQL so please be nice...
Use a query without WHERE clause. Then check if $i is not null, empty or whitespace. If so, add WHERE clause to your query.
$query = "SELECT COUNT(".$q.") c FROM MirrorWebProductsExpanded";
if($i != "")
$query = $query." WHERE Subcategorie = '".$i."'";

MYSQL query using a set of values (values stored from a session array) not working

I'm just a beginner and I'm doing a project (a shopping cart). User can add a product to the cart and the id of the product stores in a session. When I use those ids to echo out PRICE from DB it's not working. I'm using PHP & MYSQL. Here is my code
if(count($_SESSION['cart_items'])>0){
// getting the product ids
$nos = "";
foreach($_SESSION['cart_items'] as $no=>$value){
$nos = $nos . $no . ",";
}
// removing the last comma
$nos = rtrim($nos, ',');
//echo $nos; (will display like this INT VALUES 1,2,3,4)
$nos=mysql_real_escape_string($nos);
$site4->DBlogin();
$qry = "SELECT * FROM vendorproducts WHERE product_no IN('.implode(',',$nos).')";
$result = mysql_query($qry);
$row = mysql_fetch_assoc($result);
echo $row['price'];
}
PHP is not recursively embeddable:
$qry = "SELECT * FROM vendorproducts WHERE product_no IN('.implode(',',$nos).')";
^---start of string end of string ---^
Since you're already in a string, .implode(...) is just plain text, NOT executable code.
This means your query is illegal/invalid SQL, and if you had even basic/minimal error checking, would have been told about this:
$result = mysql_query($qry) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
I have fixed the issue and thanx MARC for your suggestions.
I was making two mistakes:- IMPLODE input field was not an array. and as Marc said the query was not executable.
Changes made :-
$nos = rtrim($nos, ',');
**$narray = array($nos);**
$fgmembersite4->DBlogin();
$qry = **'SELECT * FROM vendorproducts WHERE product_no IN ('.implode(',',$narray).')'**;
$result = mysql_query($qry) or die(mysql_error());
**while (**$row = mysql_fetch_assoc($result)){
echo $row['price'];}

Accessing two different tables for one loop

I have a small issue that I can't figure out.
I have to pull data from two different tables, in one loop. I've never done that before, so I have no idea how. I tried two different queries. That looked like this:
$query = "SELECT * FROM colors ";
$color_select = mysqli_query($connection, $query);
$second_query = "SELECT * FROM votes";
$vote_select = mysqli_query($connection, $second_query);
And then put them into a loop:
while($row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select))
{
$color = $row['Colors'];
$votes = $second_row['Votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
But that didn't work. I didn't expect it to, just wanted to try. :) Maybe someone experienced can help me out. Thanks.
At the end of the day I need a table displayed, that has two columns, one of them contains the color name from one DB table and the other one contains a number of votes.
As requested: table structures.
Table: colors has only one field Colors.
Table: votes has four fields city_id, City, Colors and Votes
*************************EDIT**************************************
So fixed up the query as suggested, but is still shows nothing.
Here is the edited code:
$query = "SELECT * FROM colors,votes WHERE colors.Colors=votes.Colors";
$color_votes_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_votes_select))
{ $color = $row['Colors'];
$votes = $row['Votes']; }
if table having relation.
try this in single query .
SELECT
`colors`.*,votes.*
FROM
`colors`
INNER JOIN
`votes` ON
`votes`.colorId = `colors`.Id
Most imp *****You should have some relationship between tables
Otherwise workaround
Run query on color, Save it in ArrayA
Run query on vote, Save it in ArrayB
Create New Array ArrayC
$arrayC = array();
Loop array A or C if they both contact same row count
array_push($ArrayC, key and value of color, key and value of votes);
Final loop ArrayC to print tr and td
First Relate These two tables, write color_id in votes table.
$query = "SELECT * FROM colors,votes where colors.id=votes.color_id";
$color_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_select))
{
$color = $row['Colors'];
$votes = $row['Votes'];
}
Try this:
$query = "SELECT colors FROM colors";
$color_select = mysqli_query($connection, $query) or die (mysqli_error());
$second_query = "SELECT votes FROM votes"; //you only need column votes right?
$vote_select = mysqli_query($connection, $second_query) or die (mysqli_error());;
while( $row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select)){
$color[] = $row['colors'];
$votes[] = $second_row['votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
Short explanation:
It will fetch the select and store into an array (because what you were doing is selecting multiple rows into one single variable) and then just display with the echo.

Count rows in while loop

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

Categories