sql query from 2 tables and php - php

I have a simple php code that fetches data from a sql table.
TABLE 1
date_time
name
and another table which store name(same as TABLE1) and picture link.
TABLE 2
name
pic
PHP
$db = new PDO("mysql:host=$host;dbname=$dbname", "$username", "$password");
$sql = "select * from table1";
foreach ($db->query($sql) as $row) {
echo '<span class=name>'.$row['name'].'</span>';
echo "<img src=".$row['pic']." width='25px' height='25px'/>";
$db = null;
}
What i want is to be show the picture of the name from TABLE 2($row['pic']) according to name in TABLE 1.
How the sql statement and the php code should be in order to achieve this?
I run a sql statement in phpMyadmin and got it,but couldnt translate it in php code.
select table1.name,table2.pic from table1,table2 where table1.name=table2.name;

How about using JOIN:
SELECT table1.name, table2.pic
FROM table1
INNER JOIN table2
ON table1.name = table2.name

try this, use as keyword to alias your column names, so that you can get 'name' and 'pic' index in the loop.
select
table1.name as `name`,
table2.pic as `pic`
from table1, table2
where table1.name = table2.name;
a better way to do it use joins
select
`table1`.`name` as `name`,
`table2`.`pic` as `pic`
from `table1`
inner join `table2`
on `table1`.`name` = `table2`.`name`;

Related

How to assign two SELECT queries results to single array variable($row)?

There are two queries with same fields names but different tables. I want fetch both select query's results in same array variable $result. I tried few things but nothing working for me. May b my bad day.
two table, need to be fetch in same variable $result.
$sql1="SELECT city,phone,name from table1 where city='NY'";
$result = $conn->query($sql1);
$sql2="SELECT city,phone,name from table2 where city='NY'";
$result = $conn->query($sql2);
I don't want $result lost $sql1 data after assigning same variable ($result) to second query. Please help
You can use UNION and along with that table record identifier to identify table records differently.
$sql1 = "(SELECT city,phone,name, 't1' ttype from table1 where city='NY')
UNION (SELECT city,phone,name,'t2' ttype from table2 where city='NY')";
$result = $conn->query($sql1);
Note: MySQL uses the DISTINCT clause as default when executing UNION queries if nothing is specified.
If you want duplicate records too, then use UNION ALL.
$sql1="SELECT city,phone,name from table1 where city='NY'
UNION
SELECT city,phone,name from table2 where city='NY'";
$result = $conn->query($sql1);

PHP PDO - Get same field name values of three tables in join

query = SELECT * FROM design_trip,meal_pref,types where design_trip.meal_id = meal_pref.meal_id and design_trip.triptype_id = types.type_id;
There is two columns called "name_en", when i write in foreach
<?php echo $value->budget; ?>
its getting just first table value.
I'm using this in PDO query to get values from 3 table join, how can i print this values separately?
You could give separate names when selecting for the fields. Like
SELECT design_trip.meal_id as designtripmealId
FROM design_trip,meal_pref,types
where design_trip.meal_id = meal_pref.meal_id
and design_trip.triptype_id = types.type_id;
To get all the fields incase you don't want to specify the rest of the fields, you can use table_name.*.
try this
SELECT * FROM table1
JOIN table2 ON table1.userid = table2.userid
WHERE table1.userid = 1

SQL Error returned in php for query with joins

I am trying to populate a table by executing the below query for a php application:
$sql3 = "SELECT distinct(`t1.testName`), `t2.comments AS C1` from `sample AS t1` left join `sample AS t2` ON `t1.testName`= `t2.testName` where `t1.buildNumber`= 181 and `t2.buildNumber`= 180 and `t1.errorStackTrace` is not null";
$result3 = mysqli_query($dbconnect,$sql3);
if(!mysqli_query($dbconnect, $sql3)){
printf("error message: %s\n",mysqli_error($dbconnect));
}
I am seeing the following error returned:
error message: Table 'testdata.sample as t1' doesn't exist
I have tried a lot to fix this but couldn't. The query runs fine when run on mysql.
Any help would be appreciated.
Thanks
You have to use the backticks only arround table names or column names not including the alias:
$sql3 = "SELECT distinct(`t1`.`testName`), `t2`.`comments` AS C1 from `sample` AS ` left join `sample` AS t2 ON t1.testName= t2.testName where t1.buildNumber= 181 and t2.buildNumber= 180 and t1.errorStackTrace is not null";
You are escaping the table name incorrectly. Use this raw query:
SELECT DISTINCT(t1.testName),
t2.comments AS C1
FROM `sample` AS t1
LEFT JOIN `sample` AS t2
ON t1.testName = t2.testName
WHERE t1.buildNumber = 181 AND
t2.buildNumber = 180 AND
t1.errorStackTrace IS NOT NULL
I don't think you really need backticks anywhere. But in any case, only column names need to be backticked, never aliases, e.g.
t1.`testName` but NOT `t1.testName`
Wrong back quote, try this:
$sql3 = "SELECT distinct(t1.`testName`), t2.`comments` AS C1 from `sample` AS t1 left join `sample` AS t2 ON t1.`testName`= t2.`testName` where t1.`buildNumber`= 181 and t2.`buildNumber`= 180 and t1.`errorStackTrace` is not null";

Can't insert query result into table using PHP

I am trying to insert some information to a new table in my database. For this I query information from two tables and a xref table, then I try to do the insert as I usually do. This is not working.
Here is the code,
$query = "select listaA.product_s_desc, category_name, listaA.product_desc, listaA.product_sku
from listaA, jos_vm_category, jos_vm_product_category_xref
where listaA.product_id = jos_vm_product_category_xref.product_id
and jos_vm_category.category_id = jos_vm_product_category_xref.category_id limit 10";
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die;
do{
$imagen = 'http://accesoriosazteca.mx/imagesite/'.$row['listaA.product_sku'].".png";
mysql_query("insert into lista_importat (id, activo, sku, nombre, categoria, descripcion_corta, descripcion_larga, pedidos, mostrar_precio, imagen)
values ('$row['listaA.product_id']', '1', '$row['listaA.product_sku']', '$row['listaA.product_s_desc']', '', '$row['listaA.product_s_desc']', '$row['listaA.product_desc']', '0', '0', '$imagen')");
}while($row = mysql_fetch_array($result));
With the code above I get a blank screen, and nothing is inserted into the new table. Any ideas?
If the query starting...
select listaA.product_s_desc, ...
returns a resultset, the first column in the resultset will have a column name of product_s_desc, not listaA.product_s_desc.
(Running the query in the mysql command line client will demonstrate this behavior.)
To reference to the value of that column in $row:
$row['product_s_desc']
Note that the query does not return a column with a name of listaA.product_id.
A few notes, beyond answering the question you asked:
For the benefit of readers, I recommend you ditch the old school comma syntax for the join operation and use the JOIN keyword in it's place, and relocate the join predicates from the WHERE clause to an ON clause. I also recommend the use of short table aliases, and also qualifying ALL column references. For example:
SELECT a.product_s_desc
, c.category_name
, a.product_desc
, a.product_sku
FROM listaA a
JOIN jos_vm_product_category_xref r
ON r.product_id = a.product_id
JOIN jos_vm_category c
ON c.category_id = r.category_id
ORDER BY 1
LIMIT 10

Why is this not changing the class of the table in my row? [duplicate]

How can I make an argument if/else with the following. I would like to define the variable $condition as the intersection of Table A and Table B, and ultimately, where this condition is true, then execute some code.
Here is the PHP I have (I am trying to match up the table1.field1 and table2.field1 and where true, then I will add a CSS class to the <tr>)
$result = $dbh->query("SELECT field1, field2, field3, field4 FROM table1 ORDER BY field1 DESC");
$result->setFetchMode(PDO::FETCH_ASSOC);
$match = $dbh->query("SELECT table1.field1 FROM table1 INNER JOIN table2 WHERE table2.field1 = table1.field1");
$condition = **???????**
Also, is there a way to simplify this code? I feel like its too long. Mark Twain has a saying... "I'm sorry this letter is too long, I didn't have time to make it shorter". I wish I could say that this is relevant here, but I've been at this for a while! Any help would be greatly appreciated.
What about something like (in your first and then-only query)
$result = $dbh->query("
SELECT
t1.field1,
t1.field2,
t1.field3,
t1.field4,
IF(t2.field1 IS NULL, 0, 1) `match`
FROM
table1 t1
LEFT JOIN table2 t2 ON t2.field1 = t1.field1
");
(you should put backticks (`) around match, since it's a MySQL keyword)
and in your loop
<tr class="<?=$v["match"] ? "match" : ""?>">

Categories