$option_meno = ["Lukas", "Ivka"];
$sql = "SELECT *
FROM uctovnictvo
WHERE meno IN ('$option_meno[1]', '$option_meno[0]')
AND datum BETWEEN '$date_start' AND '$date_end'
ORDER BY $order ";
For sure there has to be a better way how to select user based on name (meno). There can be more or fewer names in the $option_meno array.
I would like to make especially this more simple than listing out each index in the option array ('$option_meno[1]','$option_meno[0]').
You could use some array functions to auto generate the correct IN statement
$option_meno = ["Lukas","Ivka"];
$in = implode(',', array_map(function($item) use ($pdo) {
return '"' . $pdo->quote($item) . '"';
}, $option_meno);
$sql = "SELECT * FROM uctovnictvo WHERE meno IN ($in)...";
instead of PDO::quote you could use also mysqli_real_escape_string, etc. (depends on your connection).
You can use implode() :
$sql = " SELECT *
FROM uctovnictvo
WHERE meno IN ('" . implode('\', \'', $option_meno) . "')
AND datum BETWEEN '$date_start' AND '$date_end'
ORDER BY $order ";
Related
I'm trying to build a MySQL query using a loop for the where clause. I have a solution, but I feel like there should be a better solution. My code is as follows
$query = 'SELECT * FROM `t1` WHERE';
$names = ['John','Steve','Robert'];
foreach($names as $name){
$query .= " `name` = '$name` OR";
}
echo $query;
In this case query ends with "OR" that makes it invalid. The solution I have is to trim it using
echo rtrim($query," OR");
I feel like there should be a cleaner way of doing it. Any suggestions?
You can fix your query using where in and join. In your case it should be :
$query = 'SELECT * FROM `t1` WHERE name IN (\'' . join($names,'\',\'') . '\')';
Note: join is aliases for implode. It help code readability. Be careful with SQL Injection. You might want to validate the input or using PDO.
You could push the tests to an array and then implode them with OR:
$query = 'SELECT * FROM `t1` WHERE';
$names = ['John','Steve','Robert'];
$tests = array();
foreach($names as $name){
$tests[] = "`name` = '$name'";
}
$query .= implode(' OR ', $tests);
Demo on 3v4l.org
I do what you do in my applications, just becareful with more complicated WHERE clauses in the future.
For example, if your array is empty, you should omit "WHERE"
$query = 'SELECT * FROM `t1`';
if ($names) $query .= " WHERE";
if your where clause will have AND you should give attention to that AND is having higher precedence than OR and to use the proper brackets ()
In the code example you provided you can also do this to avoid rtrim
$names = ['John','Steve','Robert'];
foreach ($names as &$name) $name = "'$name'";
unset($name);
$query = 'SELECT * FROM `t1` WHERE `name` IN (' . implode(', ', $names) . ') ';
I have an array $friends and I used $friend_new = join(',',$friends ); to get name1,name2,name3.
But when I use this query I got error:
$query = mysqli_query($connect_db, "SELECT * FROM post WHERE name IN ($friend_new )");
Does anyone know where the problem is?
You should use implode("','", $friends) and IN ('$friends_new') as these are string values.
Your code is vulnerable to injection. You should use properly parameterized queries with PDO / mysqli
Your list has to look like:
... IN ('friend1','friend2','friend3')
If you have an array of friends such as:
$friends = array("friend1","friend2","friend3");
You can use implode to prepare for use with an IN:
$friend_new = "'" . implode("','", $friends) . "'";
Finally,
SELECT * FROM post WHERE name IN ($friend_new)
The way you do it the individual strings won't be quoted, and that causes the error. As join allows you to specify a "glue" longer than 1 character you can do as follows:
$query = mysqli_query($connect_db,
"SELECT * FROM post " .
"WHERE name IN ('".join("', '", $friends)."') ";
or
$friend_new = join("', '", $friends);
$query = mysqli_query($connect_db,
"SELECT * FROM post " .
"WHERE name IN ('$friend_new') ";
that is, have join write the intermediate ', ' , and surround with ''
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);
I've got a SQL query within a foreach loop. Sometimes there can be many, and I mean a lot of queries to do, depending on several criteria, up to 78 queries potentially.
Now, I know that premature optimisation is root cause of all evil, but I don't want to see 78 queries - it's just not healthy.
Here's the code:
$crumbs = explode(",", $user['data']['depts']);
foreach ($crumbs as &$value) {
$data = $db->query("SELECT id FROM tbl_depts WHERE id = '" . $value . "'");
$crumb = $data->fetch_assoc();
$dsn = $db->query("SELECT msg, datetime FROM tbl_motd WHERE deptid = '" . $value . "'");
$motd = $dsn->fetch_assoc();
if ($motd['msg'] != "") {
<?php echo $motd['msg']; ?>
}
}
Can I make it any better?
Use IN MySQL operator to search over a set of values for id:
$ids = '"' . implode('", "',$crumbs) . '"';
$query1 = "SELECT id FROM tbl_depts WHERE id IN (" . $ids . ")";
$query2 = "SELECT msg, datetime FROM tbl_motd WHERE deptid IN (" . $ids . ")";
And so you will not need to retrieve all data you need using foreach loop, so you will have only 2 queries instead of 78.
Example: I have a table named table with 10 records which ids are: 1,2,3,4,5,6,7,8,9,10 (auto-incremented). I know I need records with ids 1,5,8. My query will be:
$sql = "SELECT * FROM `table` WHERE id in (1,5,8);";
And I don't understand why do you need to use & operator in foreach loop if you don't modify the $crubms arrays values.
I think this is want you want.
SELECT msg, datetime
FROM tbl_depts td
INNER JOIN tbl_motd tm ON td.id = tm.deptid