I have two tables in a DB (table_1
and table_2
), Each of them has a mutual column called Name
.
I am currently using the following code to import some data (Name
,status
) only from table_1
:
/* database section start */
$mysqli = new mysqli("z","z","z","z");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* database section end */
// Choose Relevant items, and turn them into an array
$item_array = array(
'item1',
'item2',
'item3'
);
//implode items, turn into string
$item_implode = join("','", $item_array);
//declare an overall array for result
$product = array();
$result = $mysqli->query("SELECT Name, Status as status from table_1 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
while($row = $result->fetch_assoc()) {
$product_name = $row['Name'];
// find all keys in $item_array which value is the products
$keys = array_keys($item_array, $product_name);
foreach ($keys as $key) {
// add values for these keys
$product[$key + 1]["Name"] = $row['Name'];
$product[$key + 1]["status"] = $row['status'];//
}
}
What should I add to this code if I want to import data from table_2
as well (e.g., columns named color
, date_added
)?
My objective is to have these keys:
$product[$x]["Name"]
$product[$x]["status"]
$product[$x]["color"]
$product[$x]["date_added"]
EDIT:
That long thread doesn't answer my question. The code isn't similar to the code I'm using, and I want to know how to apply the UNION exactly in this concrete case.
I've tried using:
$result = $mysqli->query
("(SELECT Name, status as status from table_1 )
UNION
(SELECT Name, color as color from table_2 )
where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
while($row = $result->fetch_assoc()) {
But I get fatal error on the last line.
EDIT2:
Still getting an error:
$result = $mysqli->query
("(SELECT Name, status as statu table_1 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode') )
UNION (SELECT color from table_2 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode') );");
while($row = $result->fetch_assoc()) {