Just wondering what would be the best way of adding all the values in a column together where the pid=$pid in a column.
Here's some sample code of what I'm using:
$query = mysql_query("SELECT pid, reputation FROM reputation WHERE pid=\"{$post['pid']}\"");
while($rep = mysql_fetch_assoc($query))
{
echo $rep['reputation'];
}
That works fine, but when more than one row exists where the pid=X I need the reputation column on those rows to add together and output the result.
use GROUP BY
SELECT pid, SUM(reputation) totalReputation
FROM reputation
WHERE pid = 0
GROUP BY pid
in php
$query = mysql_query("SELECT pid, SUM(reputation) totalReputation
FROM reputation
WHERE pid = " .$post['pid'] ."
GROUP BY pid");
and fetch the alias
echo $rep['totalReputation'];
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
$query = mysql_query("SELECT SUM(reputation) as rep FROM reputation WHERE pid=\"{$post['pid']}\"");
while($rep = mysql_fetch_assoc($query))
{
echo $rep['rep'];
}
NOTE: You should not use mysql_* extension since they are now deprecated.
Related
So what I'd really like to do is combine the two queries.
I broke them up into two to help me figure out where the issue is.
sql2 is where the issue is. When I run it in phpMyAdmin (without WHERE)it works so what's going on here?
$holidayID = formval('holidayID');
$sort= formval('sort', 'rating');
$dir = formval('dir', 'ASC');
$sql = "SELECT recipeID, holidayID, recipeName, rating
FROM recipes
WHERE holidayID = $holidayID
ORDER BY $sort $dir ";
//execute
$result = mysqli_query($dbc, $sql);
$sql2 = "SELECT recipes.holidayID, holidays.holidayName
FROM recipes
JOIN holidays ON recipes.holidayID=holidays.holidayID
WHERE holidayID = $holidayID
LIMIT 1";
$result2 = mysqli_query($dbc, $sql2);
var_dump($result2);
The first query works fine.
So what am I doing wrong?
Thank you for your time.
The problem with your query is that the holidayID in your WHERE condition is ambiguous - MySQL doesn't know if you mean from the recipes or holidays table. Specify it, like you do when selecting and joining,
SELECT recipes.holidayID, holidays.holidayName
FROM recipes
JOIN holidays ON recipes.holidayID=holidays.holidayID
WHERE holidays.holidayID = $holidayID -- Specify the column, here its holidays
LIMIT 1
You should also note that this query might be vulnerable to SQL injection, and that you should utilize prepared statements in order to protect your database against that.
How can I prevent SQL injection in PHP?
Using proper error-reporting, with mysqli_error($dbc);, MySQL would've told you this as well.
PHP.net on mysqli_error();
$raw_results=mysql_query("SELECT resort_name FROM resorts WHERE resort_id=(SELECT resort_id FROM resort_place WHERE place_id=(SELECT place_id FROM place WHERE place='$query')) ") or die(mysql_error());
$check_num_rows=mysql_num_rows($raw_results);
$solutions = array();
while($row = mysql_fetch_assoc($raw_results)) {
$solutions[] = $row['solution'];
}
This is my code and it returns an error message like
Warning: mysql_query() [function.mysql-query]: Unable to save result set in C:\xampp\htdocs\search\news.php on line 131
Subquery returns more than 1 row
can any one help me to retrieve the values from the data base...
this will yield the same result with you multiple subquery.
SELECT DISTINCT a.resort_name
FROM resorts a
INNER JOIN resort_place b
ON a.resort_id = b.resort_id
INNER JOIN place c
ON b.place_id = c.place_id
WHERE c.place='$query'
As a sidenote, the query is vulnerable with SQL Injection if the value(s) came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
Use prepared statements using mysqli_ or PDO functions instead. Your query can be accomplished using an explicit JOIN:
SELECT DISTINCT resorts.resort_name
FROM resorts
JOIN resort_place ON resort_place.resort_id = resorts.resort_id
JOIN place ON place.place_id = resort_place.place_id
WHERE place.place = '$query'
use IN operator like place_id in (your sub query here)
$raw_results=mysql_query("SELECT resort_name FROM resorts WHERE resort_id IN
(SELECT resort_id FROM resort_place WHERE place_id IN
(SELECT place_id FROM place WHERE place='$query')
)
") or die(mysql_error());
The other answers are wise, you could do better than nesting queries.
If you really want to do AND my_column_id = (SELECT something FROM ...)
make sure that the subquery returns only one row, maybe by ending it with LIMIT 0, 1.
I'm trying to pull multiple rows from a single table. I'm trying to pull either all males or all females in different zip codes.
<?php
$zipCodes = array("55555", "66666", "77777", etc...);
$fetchUser = mysql_query("select * from users where gender = '$_POST[gender]' ".implode(" or zipCode = ", $zipCodes)." order by id desc");
while($var = mysql_fetch_array($fetchUser)) {
code...
}
?>
You should use IN on this,
SELECT ...
FROM tableName
WHERE gender = '$_POST[gender]' AND
zipCode IN (55555, 6666, 77777)
currently your code is vulnerable to SQL Injection. Please read on PDO or MySQLI extension.
Read more on this article: Best way to prevent SQL injection in PHP
PHP PDO: Can I bind an array to an IN() condition?
// Prevent SQL injection for user input
$fetchUser = mysql_query("select * from users where gender = '".filter_var($_POST[gender], FILTER_SANITIZE_STRING)."' OR zipCode IN (".implode(",", $zipCodes).") order by id desc");)
I have a table with 4 record.
Records: 1) arup Sarma
2) Mitali Sarma
3) Nisha
4) haren Sarma
And I used the below SQL statement to get records from a search box.
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%$q' LIMIT 5";
But this retrieve all records from the table. Even if I type a non-existence word (eg.: hgasd or anything), it shows all the 4 record above. Where is the problem ? plz any advice..
This is my full code:
$q = ucwords(addslashes($_POST['q']));
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%".$q."' LIMIT 5";
$rsd = mysql_query($sql);
Your query is fine. Your problem is that $q does not have any value or you are appending the value incorrectly to your query, so you are effectively doing:
"SELECT id,name FROM ".user_table." WHERE name LIKE '%' LIMIT 5";
Use the following code to
A - Prevent SQL-injection
B - Prevent like with an empty $q
//$q = ucwords(addslashes($_POST['q']));
//Addslashes does not work to prevent SQL-injection!
$q = mysql_real_escape_string($_POST['q']);
if (isset($q)) {
$sql = "SELECT id,name FROM user_table WHERE name LIKE '%$q'
ORDER BY id DESC
LIMIT 5 OFFSET 0";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "id: ".htmlentities($row['id']);
echo "name: ".htmlentities($row['name']);
}
} else { //$q is empty, handle the error }
A few comments on the code.
If you are not using PDO, but mysql instead, only mysql_real_escape_string will protect you from SQL-injection, nothing else will.
Always surround any $vars you inject into the code with single ' quotes. If you don't the escaping will not work and syntax error will hit you.
You can test an var with isset to see if it's filled.
Why are you concatenating the tablename? Just put the name of the table in the string as usual.
If you only select a few rows, you really need an order by clause so the outcome will not be random, here I've order the newest id, assuming id is an auto_increment field, newer id's will represent newer users.
If you echo data from the database, you need to escape that using htmlentities to prevent XSS security holes.
In mysql, like operator use '$' regex to represent end of any string.. and '%' is for beginning.. so any string will fall under this regex, that's why it returms all records.
Please refer to http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html once. Hope, this will help you.
I need to create a small piece of code to allow me to filter my events database based on category types users have selected.
I currently have it working for users who have only one category selected...
$user_qstring = "SELECT types FROM tbl_users WHERE user_id='".$_SESSION['id']."'";
$user_result = mysql_query($user_qstring);
$user_row = mysql_fetch_array($user_result);
$type_filter = $user_row['types'];
if(isset($type_filter) && $type_filter !="") {
$day_events = "SELECT COUNT(*) FROM tbl_events WHERE day='".$day_id."' AND
type='".$type_filter."'";
}else{
$day_events = "SELECT COUNT(*) FROM tbl_events WHERE day='".$day_id."'";
}
I need to alter this code so that if $type_filter is set and contains multiple categories in the following format.
Festivals,Sports,Education
And have the query automatically add...
OR type='".$type_filter[2]."' OR type='".$type_filter[3]."' OR ect...
I have been able to solve the problem using multiple...
elseif(){
}
Statements, but need a solution that is scalable to unlimited types.
I know I need to start by changing $type_filter to a list using explode...
$type_filter = explode(",", $user_row['types']);
But I'm still having trouble putting it all together for a short elegant solution.
You will need to confirm that $type_filter does not contain single quotes first otherwise you're an easy target for sql injection attacks.
$day_events = "SELECT COUNT(*) FROM tbl_events WHERE day='".$day_id."' AND type IN ('" . implode("','", explode(',', $type_filter)) . "')";
try something like the follwing sql
select * from ... where type in ('one', 'two', ...) ...
and as a remark - always escape get/post data using mysql_real_escape_string or you are vulnerable to injection attacks.