Error in search from multi-tables by php and my sql - php

Now I'm trying to search in multi table but now my problem how to know which table you got the data ??
$query="(SELECT name FROM news WHERE name like '%$SER%' )
UNION ALL
(SELECT name FROM media WHERE name like '%$SER%') ";
$res=mysql_query($query);
while($row=mysql_fetch_array($res)){
echo $row[prog]."<br>";
}
mysql_num_rows($res);
How to know the result got from which table !!!

Add an extra column
select 1 as FromTable
UNION
select 2 as FromTable;
Anything from the second select will have 2 as $row["FromTable"]
You also NEED to read about SQL injections, and use the mysqli APIs instead ideally (? saves both parsing time, escaping time and the need to escape!)

Related

I PHP + MySql noob) How to select data in mysql for query

User send to site acesskey, in MySql in table users there is his data(id, name, acesskey, friends). How to select he ID and echo from table messages all message where id_from = id?
Basically, you need to combine 2 select query results. Try looking at this. It might explain everything.
JOIN two SELECT statement results

avoid duplicate in php sql

I'm working on a page which displays set of data from mysql.
I wanted to know is there any way to avoid displaying a data with same name?
for example if i have 2 skills in database as PHP and php then it should only display either one of those .
Use group by in your SQL query to group the skills and appear only one.
If the column name is skill append the following line to the query
GROUP BY LOWER(skill);
Use DISTINCT keyword.
e.g SELECT DISTINCT skill FROM skills
Database is case-insenstive (at least MySQL), so php and PHP will be treated as duplicates.
Hence, the problem gets solved.
try this query
SELECT DISTINCT column_name,column_name FROM table_name;
SELECT DISTINCT col1 FROM skills
DISTINCT keyword is used to return only distinct (different) values.

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

Using UNION in a query with PHP

I have an SQL query which links 3 tables using UNION:
$sql ="(SELECT Drive.DriveID,Ram.Memory from Drive,Ram where Drive.DriveID = Ram.RamID) UNION
(SELECT Drive.DriveID,External.Memory from Drive, External where Drive.DriveID = External.ExtID)";
Suppose I want to get Ram.Name as well. How do I do this? If I use Ram.Name in the first SELECT statement it would not produce the correct result.
Any method for tackling this? I want to do it using UNION.
In a Union query, all of the columns must be specified in all of the statements in the same order.
Therefore you'd need to have
(SELECT Drive.DriveID,Ram.Memory,Ram.Name
from Drive,Ram
where Drive.DriveID = Ram.RamID)
UNION
(SELECT Drive.DriveID,External.Memory, '' as Name
from Drive, External
where Drive.DriveID = External.ExtID)
Or if your External table has a Name field you could Include that one instead of an empty string.

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