i had to check if a value (string) is in my database.
at the moment i do a
select a.email,b.vuid from user a, verteiler_user b where a.email=\''.$email.'\' and a.kid=' . $kid.' and b.vid=' . $vid . ' and a.uid = b.uid
as query with a mysql_num_rows, then check if >=1
But is it faster to do a query with limit 1; ? and check if a row is coming back ?
Yes. It would be faster to run a limit 1 query. And if all you're doing is checking for the existence of a row, why bother returning all those columns? Simply select 1. That will be (negligibly) faster. BTW: Your code looks vulnerable to SQL injection attacks. Consider sanitizing the dynamic parts of your query with mysql_real_escape_string() or a similar function.
LIMIT 1 will have better performance because it will stop matching when the LIMIT has been satisfied.
If you only ever expect 1 row, add LIMIT 1 to your query.
Also, if you are only checking for the presence of that string in the query, there is no need to use column names with SELECT in the query. Just use SELECT 1....
you could try:
select count(*) from user a, verteiler_user b
where a.email=\''.$email.'\' and a.kid=' . $kid.' and b.vid=' . $vid . ' and a.uid = b.uid
and get the count by:
$row=mysql_fetch_array(...);
if ($row[0] > 0) // is there a hit?
...
Related
I need to check and update with same query my database.
The error says it is not possble to update same table which is included in the select statement. Is there any workaround of this to happen in 1 mysql query? Here is the query:
$query='update option_values_to_products set available="0" where id in (
select ovtp.id from option_values ov,option_values_to_products ovtp,options o where
ovtp.product_id="1657" and ovtp.option_values_id=ov.id and ov.options_id=o.id and
o.name="Size" group by ovtp.id )';
Yes, this is a nagging feature of mysql and there is a workaround to it: wrap the subquery within the IN() clause into another subquery.
update option_values_to_products set available="0" where id in (select id from (
select ovtp.id from option_values ov,option_values_to_products ovtp,options o where
ovtp.product_id="1657" and ovtp.option_values_id=ov.id and ov.options_id=o.id and
o.name="Size" group by ovtp.id ) as t)
Avoid using nested queries for many reasons like performance and memory issue, also it can be very hard to be understood for the next developers
Good practice Split your query into 2 parts :
<?php
$qSelect = 'select ovtp.id from option_values ov,option_values_to_products ovtp,options o where
ovtp.product_id="1657" and ovtp.option_values_id=ov.id and ov.options_id=o.id and
o.name="Size" group by ovtp.id';
$res = DATABASE_MANAGER::exec($qSelect);
$qUpdate = 'update option_values_to_products set available="0" where id in (' . implode(",", $res) .')';
$res2 = DATABASE_MANAGER::exec($qUpdate);
$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.
We have a registration system Database and basically what this query does is check the students that are in the class so that they can be selected to be marked as absent if they are absent. For some reason, it takes 30 seconds. Does anybody know why?
FROM Stdts
LEFT JOIN StdtReg ON StdtReg.StdtID = Stdts.ID
LEFT JOIN usrs ON StdtReg.userID = usrs.ID
WHERE (SELECT ID FROM ClssInstncEnrol cie WHERE cie.status = 0 AND classInstanceID={$_GET['ci']} AND StdtID = Stdts.ID LIMIT 1) IS NOT NULL
OR (SELECT ID FROM DropIns di WHERE di.type <> -1 AND classInstanceID= {$_GET['ci']} AND StdtID = Stdts.ID LIMIT 1) IS NOT NULL
AND (CONCAT(Stdts.firstName, ' ', Stdts.lastName) OR CONCAT(usrs.firstName,' ', usrs.lastName))
ORDER BY firstName, lastName
Run the query with "EXPLAIN " before it and it will tell you how each table is being joined and where you might be missing an index.
Also, you have an SQL injection waiting to happen with queries of this form with HTTP params interpolated directly in the query.
Finally, you've left off some of the query and the schema, but this strikes me as something that could be done with joins rather than subselects, or even as separate queries to generate the list of student ids more efficiently before you even run the main query.
Try to check the execution plan of your query to see what could be wrong (if you have huge tables and do not use appropriate index it can be long)
Maybe this:
AND (CONCAT(Stdts.firstName, ' ', Stdts.lastName) OR CONCAT(usrs.firstName,' ', usrs.lastName))
should be:
AND (CONCAT(Stdts.firstName, ' ', Stdts.lastName) = CONCAT(usrs.firstName,' ', usrs.lastName))
If I have a PHP function that generates a random number, is it possible to pass that variable into the sql statement in the WHERE clause? I'm using CodeIgniter, so this is my code using its syntax.
$random = rand(1, 572);
$result = $this->db->query( ' SELECT part1, part2, _id FROM `questions` WHERE `_id` >= '$random' LIMIT 0,1 ');
Is this even possible to do?
EDIT: The reason I want the php to execute the random number is because I need to call it multiple times throughout my pages, and it needs to do another call to another database using a sql query
Yes it is possible if you concatenate the variable with the string:
$query = "SELECT
part1,
part2,
_id
FROM
questions
WHERE _id >= " . $random . " LIMIT 0,1";
$result = $this->db->query($query);
But if what you want is to select a random row, then you might want this query
SELECT part1, part2, _id FROM questions ORDER BY RAND() LIMIT 1
EDIT
I understand that _id will be random, but you are specifying the min and max for rand(), right? So you'd have to change it whenever you insert a new row, or you'd have to use two queries if you want to make sure rand() does not return a value too high. By using ORDER BY RAND() you are free from both problems. You simply have to get the value of _id that was returned from the query.
This might just be a mater of using double quotes instead of single quotes on the outside of your string.
$result = $this->db->query("SELECT part1, part2, _id FROM `questions` WHERE `_id` >= '$random' LIMIT 0,1 ");
Try this:
$result = $this->db->query("SELECT part1, part2, _id FROM questions WHERE _id >= '".$random."' LIMIT 0,1 ");
Im not to versed in mysql JOINS, but I think that is what is required for what I am trying to do.
With the help of SO, I got this excellent piece of SQL for calculating a count of items in my database (by categories):
SELECT SUM(`tid` IS NULL) AS `total_null`,
SUM(`tid` = 0) AS `total_zero`,
COUNT(DISTINCT `tid`) AS `other`
FROM `mark_list`
WHERE `user_id` = $userid
Now what I need the query to do is check another table: mark_options to see if the value groupthem = 1. If groupthem = 1 then the above query should be used. If groupthem = 0 then I would like to use the following query:
SELECT tid,
COUNT(*) AS other
FROM mark_list
WHERE userid = $userid
Is it better to run 2 queries, the first one to check if groupthem = 1 or 0, then have PHP decide which final query to run, or to use an SQL JOIN (or other method) to do the same function in a single query?
Thanks!!
Plz send teh reps. Kthx bai.
SELECT SUM(`mark_list`.`tid` IS NULL) AS `total_null`,
SUM(`mark_list`.`tid` = 0) AS `total_zero`,
COUNT(DISTINCT `mark_list`.`tid`) AS `other`,
COUNT(`mark_list`.`tid`) AS `ungrouped`,
`mark_options`.`groupthem`
FROM `mark_list`, `mark_options`
WHERE `mark_list`.`user_id` = $userid
GROUP BY `mark_options`.`groupthem`