if i have 4 variables and i want to select DISTINCT values form data base
<?php
$var1 = ""; //this variable can be blank
$var2 = ""; //this variable can be blank
$var3 = ""; //this variable can be blank
$var4 = ""; //this variable can be blank
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE **keywords ='$var1' OR author='$var2' OR date='$var3' OR forums='$var4'** ");
?>
note: some or all variables ($var1,$var2,$var3,$var4) can be empty
what i want:
i want to neglect empty fields
lets say that $var1 (keywords) is empty it will select all empty fileds, but i want if $var1 is empty the result will be like
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE author='$var2' OR date='$var3' OR forums='$var4' ");
if $var2 is empty the result will be like
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE keywords ='$var1' OR date='$var3' OR forums='$var4' ");
if $var1 and $var2 are empty the result will be like
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE date='$var3' OR forums='$var4' ");
and so on
Try this.
$vars = array(
'keywords' => '', // instead of var1
'author' => '', // instead of var2
'date' => '', // instead of var3
'forums' => '', // instead of var4
);
$where = array();
foreach ($vars as $varname => $varvalue) {
if (trim($varvalue) != '') $where[] = "`$varname` = '" . mysql_real_escape_string($varvalue) . "'";
}
$result = mysql_query("SELECT DISTINCT title, description FROM table WHERE " . join(" OR ", $where));
Thanks alot every one specially experimentX .. Your answer helped me to get the right function i Just replaced (isset) with (!empty) .. Then every thing will be more than OK
$vars = array(
(!empty($_GET["var1"]))? " keyword = '". $_GET["var1"] ."' ": null,
(!empty($_GET["var2"]))? " author = '". $_GET["var2"] ."' ": null,
(!empty($_GET["var3"]))? " date = '". $_GET["var3"] ."' ": null,
(!empty($_GET["var4"]))? " forums = '". $_GET["var4"] ."' ": null
);
function myfilterarray($var)
{
return !empty($var)?$var: null;
}
$newvars = array_filter($vars, 'myfilterarray');
$where = join(" OR ", $newvars);
$sql = "SELECT DISTINCT title, description FROM table ".(($where)?"WHERE ".$where: null);
echo $sql;
with this function if there is empty variable it will be neglected
Thanks again every one for your helpful suggestion
make your select statement string before you call mysql_query(...) so do something along the lines of this:
$queryString = "Select DISTINCT title, description FROM table WHERE";
if(!empty($var1))
$queryString .= " keywords = $var1";
and so forth for all of your variables. you could also implement a for loop and loop through your $var1 - $var# and check for !empty($var#)
Why do you not simply build a if else structure?
Like
if ($var1!="" && $var2!="" && $var3!="" && $var4!=""){
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE keywords ='$var1' OR author='$var2' OR date='$var3' OR forums='$var4' ")
} else if ($var2!="" && $var3!="" && $var4!=""){
$result = mysql_query("SELECT DISTINCT title,description FROM table WHERE author='$var2' OR date='$var3' OR forums='$var4' ");
} else if {
...
}
(I just posted the below in his duplicate post, so I'm re-posting the below here)
Forgive me if anything is wrong, it's very late here and I just typed this in notepad on Windows, without an environment to test on. * Use with caution * :)
$vars = array(
'blah1' => '',
'blah2' => '',
'blah3' => '',
);
$sql_statement = "SELECT first, last FROM names WHERE";
$clause = "";
foreach($vars as $k=$v)
{
$k = trim($k);
if(!empty($k))
{
$clause .= " `$k` = '$v' OR";
}
}
$clause = rtrim($clause, "OR");
// $clause should have what you want.
Well, there are manu ways of doing this but the shortest way I have found is creating an array of the following form
$vars = array(
(isset($_GET["var1"]))? " keyword = '". $_GET["var1"] ."' ": null,
(isset($_GET["var2"]))? " author = '". $_GET["var2"] ."' ": null,
(isset($_GET["var3"]))? " date = '". $_GET["var3"] ."' ": null,
(isset($_GET["var4"]))? " forums = '". $_GET["var4"] ."' ": null
);
function myfilterarray($var)
{
return !empty($var)?$var: null;
}
$newvars = array_filter($vars, 'myfilterarray');
$where = join(" OR ", $newvars);
$sql = "SELECT DISTINCT title, description FROM table ".(($where)?"WHERE ".$where: null);
echo $sql;
Your result for http://localhost/?var1=sadfsadf&var2=sadfasdf&var3=asdfasdf
SELECT DISTINCT title, description FROM table WHERE keyword =
'sadfsadf' OR author = 'sadfasdf' OR date = 'asdfasdf'
Your result for http://localhost/?
SELECT DISTINCT title, description FROM table
Related
I have two arrays with ID and description.
In database I have same ID but doesn't have description.
How I can add each description form array to current ID?
This is full code
foreach($product->find('.block-d .btns-d .btn-buy') as $productId) {
if(!empty($productId)) {
dataId = $productId->{'data-offerid'};
}
}
foreach($product->find('.description div div p') as $description) {
if(!empty($description)) {
$query = "UPDATE snowcore_parser_products SET description = " . $description . " WHERE remote_id = " . $dataId . " ';";
$sql = mysqli_query($db, $query);
}
}
If I try to use just simple value without array it works. For example
$query = "UPDATE snowcore_parser_products SET description = '1';";
I think your query is malformed. It doesn't have quotes around the description to indicate it is a string. For example, if the value for description is "stackoverflow" and the id is "1", your query would look like so:
UPDATE snowcore_parser_products SET description = stackoverflow WHERE remote_id = 1 ';
So to fix this, the last quote should disappear and the value for description should be surrounded with quotes. Like this:
$query = "UPDATE snowcore_parser_products SET description = '" . $description . "' WHERE remote_id = " . $dataId . ";
Also I recommend you to read this article on SQL injection, as this query isn't safe.
just use foreach and that`s all, try this:
$ids = [1,2,3];
$descriptions = [1,2,3];
foreach($ids as $key => $id) {
$query = "UPDATE snowcore_parser_products SET description = " . $descriptions[$key] . " WHERE remote_id = " . $id . " ';";
$sql = mysqli_query($db, $query);
}
I'm working on a search query and i hit a little bump... So as you see in the code below, i'm adding values to a array to execute it later in the script, but it's not really working... So when i var_dumped all of this, it returned like it is supposed to but the :q was not changed to the value which was entered in the link.
$query = "SELECT * FROM articles";
$columnsQuery = [];
$values = [];
if(isset($_GET['q']) && !empty($_GET['q']))
{
$columnsQuery[] = " WHERE MATCH (title) AGAINST (':q' IN NATURAL LANGUAGE MODE)";
$values[":q"] = $_GET['q'];
}
$fullQuery = $query . implode(" ", $columnsQuery)
. " ORDER BY id DESC"
. " LIMIT {$paginator->getLimitSQL()}";
$getArticles = $db->prepare($fullQuery)->execute($values);
$query = "SELECT * FROM articles";
$columnsQuery = [];
$values = [];
if(isset($_GET['q']) && !empty($_GET['q']))
{
$columnsQuery[] = " WHERE MATCH (title) AGAINST (':q' IN NATURAL LANGUAGE MODE)";
$values["q"] = $_GET['q']; // TRY WITHOUT COLON
}
$fullQuery = $query . implode(" ", $columnsQuery)
. " ORDER BY id DESC"
. " LIMIT {$paginator->getLimitSQL()}";
$getArticles = $db->prepare($fullQuery)->execute($values);
You should not use colon in the place of $values["q"] = $_GET['q'];
$query = "SELECT * FROM articles";
$columnsQuery = [];
$values = [];
if(isset($_GET['q']) && !empty($_GET['q']))
{
$columnsQuery[] = " WHERE MATCH (title) AGAINST (':q' IN NATURAL LANGUAGE MODE)";
$values["q"] = $_GET['q']; // TRY WITHOUT COLON
}
$fullQuery = $query . implode(" ", $columnsQuery)
. " ORDER BY id DESC"
. " LIMIT {$paginator->getLimitSQL()}";
$getArticles = $db->prepare($fullQuery)->execute($values);
$query = "SELECT * FROM articles";
$values = array();
if(!empty($_GET['q'])) {
$query .= " WHERE MATCH (title) AGAINST (q IN NATURAL LANGUAGE MODE)";
$db->bindParam(':q', $_GET['q']);
}
$fullQuery = $query . " ORDER BY id DESC" . " LIMIT {$paginator->getLimitSQL()}"
$getArticles = $db->prepare($fullQuery)->execute();
So after a while i figured it out, You're not supposed to use parameters while binding in the query, and like #Poiz pointed out i shouldnt use colons in the array either
Thx to everyone who tried helping :)
I am setting a variable that contains an array as a constraint to a SELECT sql statement. However the constraint seems only to apply to one piece of data in the array. Why is this?
Code below:
<?php
include 'connection.php';
$Date = $_POST['date'];
$Unavail = 0;
$Avail = 0;
$Availid = 0;
$low = 99999;
$query = "SELECT username FROM daysoff WHERE date = '$Date'";
$dayresult = mysql_query($query);
while($request = mysql_fetch_array($dayresult)) {
$Unavail = $request;
echo "<span>" . $Unavail['username'] . " is unavailable.</br>";
}
$query1 = "SELECT Username, name, work_stats FROM freelance WHERE Username != '$Unavail[username]'";
$dayresult1 = mysql_query($query1);
while($request1 = mysql_fetch_array($dayresult1)) {
echo "<span>" . $request1['name'] . " is available.</br>";
if ($request1['work_stats']<=$low) {
$low = $request1['work_stats'];
$Availid = $request1['name'];
}}
echo "<span>" . $Availid . " is available on " . $_POST['date'] . " and is on workstat level " . $low . ".</span></br>";
?>
The output shows two names in the first echo but then shows one of those names as available in the second echo (these echos are only in place as part of my testing),
Many Thanks
The first query can have multiple results.
SELECT username FROM daysoff WHERE date = '$Date'
Let's say if gives two rows: Dave and John.
You're only keeping the last record so it will seem like Dave is available.
You should probably do something like:
$query = "SELECT username FROM daysoff WHERE date = '$Date'";
$dayresult = mysql_query($query);
$unavailable_users = array();
while($request = mysql_fetch_array($dayresult)) {
$unavailable_users[] = $request["username"];
echo "<span>" . $Unavail['username'] . " is unavailable.</br>";
}
$query1 = "SELECT Username, name, work_stats FROM freelance
WHERE NOT Username IN ('" . implode("','", $unavailable_users) . "')";
// etc
Or in one go with a LEFT JOIN:
SELECT `Username`, `name`, `work_stats`
FROM `freelance`
LEFT JOIN `daysoff` ON `freelance`.`Username` = `daysoff`.`username`
AND `daysoff`.`date` = '$Date'
WHERE
`daysoff`.`username` IS NULL
This query is not returning any result as there seems to be an issue with the sql.
$sql = "select region_description from $DB_Table where region_id='".$region_id."' and region_status =(1)";
$res = mysql_query($sql,$con) or die(mysql_error());
$result = "( ";
$row = mysql_fetch_array($res);
$result .= "\"" . $row["region_description"] . "\"";
while($row = mysql_fetch_array($res))
{
echo "<br /> In!";
$result .= " , \"" . $row["region_description"] . "\"";
}
$result .= " )";
mysql_close($con);
if ($result)
{
return $result;
}
else
{
return 0;
}
region_id is passed as 1.
I do have a record in the DB that fits the query criteria but no rows are returned when executed. I beleive the issue is in this part ,
region_id='".$region_id."'
so on using the gettype function in my php it turns out that the datatype of region_id is string not int and thus the failure of the query to function as my datatype in my tableis int. what would be the way to get parameter passed to be considered as an int in php. url below
GetRegions.php?region_id=1
Thanks
Try it like this:
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
The region_id column seems to be an integer type, don't compare it by using single quotes.
Try dropping the ; at the end of your query.
First of all - your code is very messy. You mix variables inside string with escaping string, integers should be passed without '. Try with:
$sql = 'SELECT region_description FROM ' . $DB_Table . ' WHERE region_id = ' . $region_id . ' AND region_status = 1';
Also ; should be removed.
try this
$sql = "select region_description from $DB_Table where region_id=$region_id AND region_status = 1";
When you are comparing the field of type integer, you should not use single quote
Good Luck
Update 1
Use this.. It will work
$sql = "select region_description from " .$DB_Table. " where region_id=" .$region_id. " AND region_status = 1";
You do not need the single quotes around the region id i.e.
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
I have 3 tables:
Users - uID (INT AUTO_INCREMENT), name (VARCHAR)
Movies - mID (IN AUTO_INCREMENT), title (VARCHAR)
Watched - uID (INT), mID (INT)
I'm writing a php function that constructs a query which adds records of movies watched by a particular person. Here's what I've come up with so far:
function set_watched($name, $movies){
$sql = "SET #userid = (SELECT uID FROM users WHERE name = '$name' LIMIT 1); ";
$sql .= "INSERT INTO watched (uID, mID) VALUES ('";
foreach ($movies as $index => $movie){
}
}
My question:
Is there a way to combine the #userid variable with the results of a SELECT mID FROM MOVIES WHERE title = $movie OR title = $movie [generated with foreach]?
I don't want to generate separate SELECT statements for every movie title. Perhaps I don't even have to use the #userid variable at all?
Try something like this:
$sql = "INSERT INTO watched (uID, mID)
SELECT User.uID, Movies.mID
FROM (SELECT uID FROM Users WHERE Users.name = '$name' LIMIT 1) AS User, Movies
WHERE ";
foreach ($movies as $index => $movie){
$sql .= "Movies.title = '$movie' OR ";
}
$sql = substr($sql, 0, -4) . ";";
I prefer using arrays and imploding them for this sort of an application. Also, I wouldn't try and force these two things into one query. I would either:
Modify the function parameters to accept uID as its input, instead of name
Change the logic to two queries.
Besides, PHP's mysql_query function doesn't support multiple queries, so if you're using the standard mysql functions, you can't execute two queries with one call to mysql_query.
Running with case #2, you can use something like this (untested, of course):
$sql = 'SELECT uID FROM users WHERE name = "' . $name. '" LIMIT 1';
$result = mysql_query( $sql);
$row = mysql_fetch_row( $result);
mysql_free_result( $result);
$values_array = array();
foreach ($movies as $index => $movie)
{
$values_array[] = '( "' . $row['uID'] . '", "' . $movie . '")';
}
$sql = 'INSERT INTO watched (uID, mID) VALUES ' . implode( ', ', $values_array);
$result = mysql_query( $sql);