Multiple selection in a single table using php mysql - php

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");)

Related

Search function on multiple rows in the same table

I'm wondering how do I add more row's on my search script to be searched.
Here's my php script:
<?php
$con = new PDO("mysql:host=localhost;dbname=db",'user','');
if (isset($_POST["submit"])) {
$str = $_POST["search"];
$sth = $con->prepare("
SELECT *
FROM `players`
WHERE region = '$str'
");
$sth->setFetchMode(PDO:: FETCH_OBJ);
$sth -> execute();
if($row = $sth->fetch())
{
?>
As you can see this:
SELECT * FROM `players` WHERE region = '$str'
I want to it to search on region and rank rows.
I tried:
SELECT * FROM `players` WHERE region, rank = '$str'
.... it's showing 0 results.
Thank you in advance.
Is this what you want?
SELECT * FROM players WHERE ? IN (region, `rank`)
This searches for the parameter in both columns region and rank.
Side notes:
For this to properly and consistently work, both columns must be of the same datatype
Use prepared statements! Do not concatenate variables in the query string; this is inefficient, and opens up your code to SQL injection. See How can I prevent SQL injection in PHP?
Starting version 8.0.2, rank is a reserved word in MySQL, hence not a good choice for a column name

How to write an SQL statement for two variables, one carrying the table name, and the other the specific column in a table?

$select = $_POST['select'];
$search = $_POST['search'];
$sql = "SELECT * FROM '$select' WHERE $select = '$search'";
I have 2 variables carrying the aforementioned table name and column name. I want the user to be able to select a table name and then select a specific column and output the requested record.
I only have a problem with writing the sql statement. Thanks in advanced!
you may use the following query without any problem...
$sql="SELECT * from $select WHERE field_name='$search' ";
In the above query field_name is the that field name in which you want to search value of mattch the value.
you are using table instead of column
$sql = "SELECT * FROM '$select' WHERE $select = '$search'";
^^^^^^----//this should be column not table
this is bad idea you are doing. FULL of sql injection
switch to pdo or mysqli.
Escape your variables.

MySQL how to add all of a column together where pid= X

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.

Using PHP & MySQL to sort Events by multiple types.

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.

Search mySQL with PHP, using a WHERE wildcard or an IF statement?

I'm letting users search my database for data by city.
My query looks like:
$results = mysql_query("SELECT * FROM mydb WHERE City='".$city."' LIMIT 10");
I want a user to be able to search 'all cities', so I'd like to either remove the WHERE statement if $city=='all cities'; or use a wildcard for the WHERE statement that matches all cities in the db.
I used to have an IF statement that switched between two queries, but I want to add more filters like country/all countries, zipcode/all zipcodes, etc, So I'd rather keep one dynamic SQL query.
Well, you could still have just one query and build the where clause dynamically, as such:
$where = '';
// conditional statements (if/else, switch) for populating the where clause
$where .= " WHERE City = '{$city}'";
$where .= " AND Country = '{$country}'";
$results = mysql_query("SELECT * FROM mydb{$where} LIMIT 10");
One way would be a case statement:
WHERE City = case when '$city' = 'All cities' then City else '$city' end
If the user is searching for 'All cities', this turns the WHERE statement into:
WHERE City = City
Which is always true (at least for non-null cities ;))
P.S. Make sure you're running these queries using a read-only MySQL account. The user could enter funny stuff into the $city parameter!
You could try
WHERE City like '$city'
and permit the users to enter wildcards, if you think they'd be up to it.
although not PHP programmer, this pseudocode might offer an option... conditionally build out your where clause. Additionally, I would do it with parameterized queries instead of direct string building to prevent sql-injection attacks.
cYourSQL = "select * from YourTable where "
cAndRequired = ""
if city is NOT "all cities"
cYourSQL = cYourSQL + cAndRequired + " city = 'YourParameterValueProvided' "
cAndRequired = " AND "
endif
Now, always add your country selection
cYourSQL = cYourSQL + cAndRequired + " country = 'YourCountryValue' LIMIT 10 "
Run the query

Categories