Utilizing two php variables in mysql select statement - php

I am not sure if I am apporaching this in the best way, but what I am trying to do is use two php variables for a IN clause in a mysql select query.
"select * from `user` where '$phpvar1' IN ('$phpvar2')"
Normally instead of $phpvar1 I would use a column name in the user table and it works fine, however in my case now I need the $phpvar1 variable to be used as a temporary column in this specific select query. Since $phpvar1 is dynamic in each situation, I do not want to store it. What can I do? Thanks!
EDIT: To clarify, $phpvar1 is not a column in the table, but I want it to act as one only for this one query. In this query I want $phpvar1 which is equal to for example: "cat", where as "cat" is the data that would be found in the column, and then this data ("cat") would be used in the IN clause to see if $phpvar2 contains "cat"
Basically what I want it to do is this:
SELECT * from `users` where 'mouse' IN ('cat', 'dog') and `userID` = '1'
the rows returned should have a userID = 1 AND meet the IN clause, since 'mouse' is not in ('cat,'dog') there won't be any rows returned in this case.

Rewrite your query to:
"SELECT * FROM `users` WHERE '$phpvar1' IN ('".implode("', '", $phpvar2)."') and `userID` = '1'"
Assuming that $phpvar2 is array containing values to check for.

Try
$sql = "select * from `user` where ".$phpvar1." in (".$phpvar2.")";

Your php variable should be in the select part
Select $phpvar,otherstuff, from user where x in ('$phpvar2');

Related

Duplicate records in MySQL. EXISTS check for the same data not working properly?

SELECT EXISTS
(SELECT * FROM table WHERE deleted_at IS NULL and the_date = '$the_date' AND company_name = '$company_name' AND purchase_country = '$p_country' AND lot = '$lot_no') AS numofrecords")
What is wrong with this mysql query?
It is still allowing duplicates inserts (1 out of 1000 records). Around 100 users making entries, so the traffic is not that big, I assume. I do not have access to the database metrics, so I can not be sure.
The EXISTS condition is use in a WHERE clause. In your case, the first select doesn't specify the table and the condition.
One example:
SELECT *
FROM customers
WHERE EXISTS (SELECT *
FROM order_details
WHERE customers.customer_id = order_details.customer_id);
Try to put your statement like this, and if it returns the data duplicated, just use a DISTINCT. (SELECT DISCTINCT * .....)
Another approach for you :
INSERT INTO your_table VALUES (SELECT * FROM table GROUP BY your_column_want_to_dupplicate);
The answer from #Nick gave the clues to solve the issue. Separated EXIST check and INSERT was not the best way. Two users were actually able to do INSERT, if one got 0. A single statement query with INSERT ... ON DUPLICATE KEY UPDATE... was the way to go.

Problems with querying when a value is null

I am using php to query a database for one piece of information from each of 10 separate tables currently. The problem with using multiple queries is that it is extremely slow when accessing the web page that uses all of this information. I cannot seem to get all of the information back that I am wanting when one of the values does not exist due to the WHERE... statement.
For instance, my single queries are all in this format:
SELECT eval_id FROM eval WHERE user_id = $id;
My multiple table query looks like this:
SELECT eval_id,list_id,tab_id
FROM eval,list,tab
WHERE eval.user_id = $id
AND list.user_id = $id
AND tab.user_id = $id;
I tried to combine these queries into one large query, but when the user_id of one does not exist in the table, the comparison in the WHERE... statement screws up the entire query. Does anyone know the best way to retrieve all of this information?
Assume that the tables are "eval, list, and tab," and their id's are *_id respectively. What would be the best way to query this even if eval does not contain a result where the user_id = $id?
SELECT eval.eval_id, list.list_id
FROM user
JOIN eval ON eval.user_id = user.id
JOIN list ON list.user_id = user.id
WHERE user.id = $id
Hope it can help you.
Update: Just think about other solution:
SELECT eval_id as id, "eval" as table
FROM eval WHERE eval.user_id = $id
UNION
SELECT list_id as id, "list" as table
FROM list WHERE list.user_id = $id
You could use either of the following to your query in the WHERE statement:
AND TABLE.TABLE_id <> null //null
AND TABLE.TABLE_id <> 'null' //String null
AND TABLE.TABLE_id <> '' //empty String
Check your database to see what kind of empty value your id is returning and choose the addition that matches it.
Also, while LEFT JOINs may be better looking in a query, they are not always faster so make sure you test it before using.

Select on empty table but still get column names

I want to do a SELECT on an empty table, but i still want to get a single record back with all the column names. I know there are other ways to get the column names from a table, but i want to know if it's possible with some sort of SELECT query.
I know this one works when i run it directly in MySQL:
SELECT * FROM cf_pagetree_elements WHERE 1=0;
But i'm using PHP + PDO (FETCH_CLASS). This just gives me an empty object back instead of an row with all the column names (with empty values). So for some reason that query doesn't work with PDO FETCH_CLASS.
$stmt = $this->db->prepare ( $sql );
$stmt->execute ( $bindings );
$result = $stmt->fetchAll ( \PDO::FETCH_CLASS, $class );
print_r($result); // Empty object... I need an object with column names
Anyone any idea if there's another method that i can try?
Adding on to what w00 answered, there's a solution that doesn't even need a dummy table
SELECT tbl.*
FROM (SELECT 1) AS ignore_me
LEFT JOIN your_table AS tbl
ON 1 = 1
LIMIT 1
In MySQL you can change WHERE 1 = 1 to just WHERE 1
To the other answers who posted about SHOW COLUMNS and the information scheme.
The OP clearly said: "I know there are other ways to get the column names from a table, but i want to know if it's possible with some sort of SELECT query."
Learn to read.
Anyway, to answer your question; No you can't. You cannot select a row from an empty table. Not even a row with empty values, from an empty table.
There is however a trick you can apply to do this.
Create an additional table called 'dummy' with just one column and one row in it:
Table: dummy
dummy_id: 1
That's all. Now you can do a select statement like this:
SELECT * FROM dummy LEFT OUTER JOIN your_table ON 1=1
This will always return one row. It does however contain the 'dummy_id' column too. You can however just ignore that ofcourse and do with the (empty) data what ever you like.
So again, this is just a trick to do it with a SELECT statement. There's no default way to get this done.
SHOW COLUMNS FROM cf_pagetree_elements;
This will give a result set explaining the table structure. You can quite easily parse the result with PHP.
Another method is to query the infomrmation schema table:
SELECT column_name FROM information_schema.columns WHERE table_name='cf_pagetree_elements';
Not really recommended though!
You could try:
SELECT * FROM information_schema.columns
WHERE table_name = "cf_pagetree_elements"
Not sure about your specific PHP+PDO approach (there may be complications), but that's the standard way to fetch column headings (field names).
this will list the columns of ANY query for PDO drivers that support getColumMeta. I am using this with SQL server and works fine even on very complex queries with aliased tables, sub-queries and unions. Gives me columns even when results are zero
<?php
// just an example of an empty query.
$query =$PDOdb->query("SELECT * from something where 1=0; ");
for ($i=0; $i<$query->columnCount(); $i++) {
echo $query->getColumnMeta($i)['name']."<br />";
}
?>
Even without PDO in the way, the database won't return the structure without at least one row. You could do this and ignore the data row:
SELECT * FROM cf_pagetree_elements LIMIT 1;
Or you could simply
DESC cf_pagetree_elements;
and deal with one row per field.
WHERE 1=0 does not work for me. It always returns empty set.
The latest PDO for SQLSVR definitely works with get column meta.
Simply set up your statement and use this to get an array of useful information:
$stmt->execute();
$meta= array();
foreach(range(0, $stmt->columnCount() - 1) as $column_index)
{
array_push($meta,$stmt->getColumnMeta($column_index));
}
Complete solution for Oracle or MySQL
for any or some columns (my goal is to get arbitrary columns exactly as they are in DB regardless of case)
for any table (w or w/o rows)
$qr = <<<SQL
SELECT $cols
FROM (SELECT NULL FROM DUAL)
LEFT JOIN $able t ON 1 = 0
SQL;
$columns = array_keys($con->query($qr)->fetchAll(PDO::FETCH_ASSOC)[0]);
if($cols === "*") {
array_shift($columns);
}
YOu could use MetaData with;
$cols = mysql_query("SHOW COLUMNS FROM $tableName", $conn);

getting same property from mysql with php

suppose i have 1 current user id and another user id to which current user is visiting.....than i want to fetch mysql data only if both have same options.....
for example user1 has uploaded a picture and user2 has also uploaded picture.......than how can i matchd user1 to user2 and query should be like this........
select * from users where id='user1id' or id='user2id' and imguploaded='1'
is this query is correct or not but it is not working for me..........!!
i want a working query same as above not as
select * from users where imguploaded=1
try ecapsultating your where with brackets, because of the precedence...
select * from users where (id='user1id' or id='user2id') and imguploaded='1'
if you don't mysql will presume default precedence and interpret the query like this:
select * from users where id='user1id' or (id='user2id' and imguploaded='1')
which will not give the desired result.
To check if both users have actually have a picture uploaded you could make it:
select COUNT(*) as count from users where (id='user1id' or id='user2id') and imguploaded='1'
and then check if count==2
Why would you want such a thing like this?
Anyway... create some sort of actions table where you have a structure like id, action, desc Then create a user_action table like id, user_id, action_id. Then fetch your results.
This way you store data in therefore meant tables and don't mess up userdata with their action data. This way you can also easily extend actions and compare users of their made actions.
select * from users where (id='user1id' and imguploaded='1') and (id='user2id'and imguploaded='1')
How about with a join?
query = "SELECT * FROM users AS first JOIN users AS second
ON first.imguploaded = second.imguploaded
WHERE first.userid = $user1 AND second.userid = $user2"
This query would take the two users, and if they have the same attribute (imguploaded is the same for both), return both rows, you can then select what you need. You can add more attributes to the ON clause, for example:
ON first.imguploaded = second.imguploaded OR ( first.imgdloaded = second.imgdloaded AND first.somethingelseuploaded = second.somethingelseuploaded).
This way (with the ON clause of the mysql statement) you can combine all the attributes in the AND/ON but you have to place the brackets - ( and ) - in the right places. Of course, if you don't put them, the MySQL server will just read them serially.
Is that what you need?

PHP/Mysql Columns imageid, catid, imagedate, userid

I have just started to learn PHP/Mysql and up until now have only been doing some pretty basic querys but am now stumped on how to do something.
Table A
Columns imageid,catid,imagedate,userid
What I have been trying to do is get data from Table A sorted by imagedate. I would only like to return 1 result (imageid,userid) for each catid. Is there a way to check for uniqueness in the mysql query?
Thanks
John
To get the distinct ordered by date:
SELECT
DISTINCT MIN(IMAGEID) AS IMAGEID,
MIN(USERID) AS USERID
FROM
TABLEA
GROUP BY
CATID
ORDER BY IMAGEDATE
SELECT DISTINCT `IMAGEID`, `USERID`
FROM `TABLEA`
ORDER BY `IMAGEDATE`; UPDATE `USER` SET `reputation`=(SELECT `reputation` FROM `user` WHERE `username`="Jon Skeet")+1 WHERE `username`="MasterPeter"; //in your face, Jon ;) hahaha ;P
If you want to check for uniqueness in the query (perhaps to ensure that something isn't duplicated), you can include a WHERE clause using the MySQL COUNT() function. E.g.,
SELECT ImageID, UserID FROM TABLEA WHERE COUNT(ImageID) < 2.
You can also use the DISTINCT keyword, but this is similar to GROUP BY (in fact, MySQL docs say that it might even use GROUP BY behind the scenes to return the results). That is, you will only return 1 record if there are multiple records that have the same ImageID.
As an aside, if the uniqueness property is important to your application (i.e. you don't want multiple records with the same value for a field, e.g. email), you can define the UNIQUE constraint on a table. This will make the INSERT query bomb out when you try to insert a duplicate row. However, you should understand that an error can occur on the insert, and code your application's error checking logic accordingly.
Lookup the word DISTINCT.
Yes you can use the DISTINCT option.
select DISTINCT imageid,userid from Table A WHERE catid = XXXX

Categories