I am pretty new to PHP and don't know how to get results from the mysqli_fetch_assoc() function if my select statement has table joins and those joins are handled with table aliases.
The code looks like following:
$sql = 'SELECT T1.update_text, T1.created_at, T2.username, T3.group_name FROM updates AS T1
INNER JOIN users AS T2 ON T2.user_id = T1.user_id_fk
INNER JOIN groups AS T3 ON T3.group_id = T1.group_id_fk
WHERE T1.user_id_fk = "1"';
And the PHP Code afterwards:
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
printf ("%s (%s)\n",$row["username"],$row["T1.created_at"]);
}
For the "username" row I am not getting an error, but nothing is displayed. For the second one I am getting an Index undefined error. (This is only a snippet of the code)
Change the SQL Query as following,
$sql = 'SELECT T1.update_text as update_text, T1.created_at as created_at, T2.username as username, T3.group_name as group_name FROM updates AS T1
INNER JOIN users AS T2 ON T2.user_id = T1.user_id_fk
INNER JOIN groups AS T3 ON T3.group_id = T1.group_id_fk
WHERE T1.user_id_fk = "1"';
then change the PHP code as following,
$result = $mysqli->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = $results->fetch_object())
{
echo $row->username.$row->created_at."<br/>";
}
}
Related
I am using following query to get all bank accounts from a database table (tb_bank_accounts).
There is another table called tb_movements, and I need to add as new column in the query the SUM of the column 'income' from all records from the table tb_movements where the column 'bank' is equal to the column id_bank_account in the query.
$query="SELECT * from tb_bank_accounts LEFT JOIN tb_currencies ON tb_bank_accounts.currency = tb_currencies.id_currency";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = $row;
}
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
I guess I should use another LEFT JOIN to do it...
It might be easiest to do using a correlated subquery. Something like this:
SELECT a.*, c.*,
(SELECT SUM(m.income)
FROM movements m
WHERE m.bank_id = a.bank_id
) as income
from tb_bank_accounts a LEFT JOIN
tb_currencies c
ON a.currency = c.id_currency;
I'm using autocomplete for my panel and get stuck with queries. I'm getting products from prestashop database and do the following (example with 1 query):
$return_arr = array();
if ($ps_DB_con) {
$ac_term = "%".$_GET['term']."%";
$query = "SELECT ps_product.id_product
AS id_product, ps_product.id_manufacturer
AS producent_id, ps_manufacturer.name
AS producent, ps_product_shop.price
AS cena, ps_product_shop.active
FROM ps_product
LEFT JOIN ps_product_shop ON ps_product.id_product=ps_product_shop.id_product
LEFT JOIN ps_manufacturer ON ps_product.id_manufacturer=ps_manufacturer.id_manufacturer
WHERE ps_product.id_product LIKE :term";
$result = $ps_DB_con->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$return_arr[] = array('id_product' => $row['id_product'], 'producent' => $row['producent'], 'label' => "{$row['id_product']}");
}
echo json_encode($return_arr);
I would like to put 2nd query to this and join results to return_arr[] in while loop.
Select ps_feature_value_lang.value as szerokosc from ps_feature_value_lang
left join ps_feature_product on ps_feature_value_lang.id_feature_value= ps_feature_product.id_feature_value
left join ps_feature_lang on ps_feature_product.id_feature=ps_feature_lang.id_feature
where ps_feature_product.id_product LIKE :term and ps_feature_product.id_feature='17'
Select ps_feature_value_lang.value as profil from ps_feature_value_lang
left join ps_feature_product on ps_feature_value_lang.id_feature_value= ps_feature_product.id_feature_value
left join ps_feature_lang on ps_feature_product.id_feature=ps_feature_lang.id_feature
where ps_feature_product.id_product LIKE :term and ps_feature_product.id_feature=18
How can I join those queries into one?
function sum($nomId){
$sql = "SELECT SUM(nomDetCantidad) FROM table2 where Id = $nomId";
$Resultado=$this->ProcesaSQLQueryList($sql);
if($Resultado>0){
foreach($Resultado as $key => $valor){
$cantidadTotal = $valor[0];
}
}
if($Resultado=='null'){$cantidadTotal=0;}
$sql = "UPDATE table1 SET nomCantidadTotal=$cantidadTotal,nomActualizado = NOW() WHERE nomId= $nomId";
return $this->ProcesaSQLQueryUpdate($sql);
and this is the function I call
function ProcesaSQLQueryList($SQLQuery){
$row= array();
if(!$this->link_mysql) $this->link_mysql = conectarManager();
if($res = mysql_query($SQLQuery,$this->link_mysql)){
while($r = mysql_fetch_array($res)){
$row[] = $r;
}
mysql_free_result($res);
return $row;
}else{
$this->last_error = $SQLQuery . " - " . mysql_error();
return -1;
}
}
So I sum up whatever I have in a field table 2 with the foreign key of table 1 then my result gets updated to the table 1 field but if I delete the fields in table 2 result wont get updated to 0 any suggestions I'm pretty sure this is an easy one but can't seem to find it
$sql = "SELECT SUM(nomDetCantidad) FROM table2 where nominaId = $nomId";
$Resultado = $this->ProcesaSQLQueryList($sql);
if ($Resultado > 0) {
foreach ($Resultado as $key => $valor) {
$cantidadTotal = $valor[0];
}
}
if ($cantidadTotal == '') {
$cantidadTotal=0.00;
}
$sql = "UPDATE table1 SET nomCantidadTotal=$cantidadTotal,nomActualizado = NOW() WHERE nomId = $nomId";
return $this->ProcesaSQLQueryUpdate($sql);
There! It was sending me a blank variable xD but fixed and there are more suitable ways to do it, I agree with Spencer but if a client wants a red swing he has to get a red swing you know? :) thanks for the help guys!
If you need a zero returned when there are no "matching" rows in table2, then wrap the return expression in an IFNULL function.
SELECT IFNULL(SUM(nomDetCantidad),0) FROM table2 ...
You could significantly reduce the amount of code you have, reduce the number of roundtrips to the database, and improve performance by doing all this work in a single UPDATE statement. You can use either a correlated subquery or an OUTER JOIN:
-- using a correleated subquery
UPDATE table t1
SET t1.nomActualizado = NOW()
, t1.nomCantidadTotal =
( SELECT IFNULL(SUM(t2.nomDetCantidad),0) AS nomCantidadTotal
FROM table2 t2
WHERE t2.Id = t1.nomID
)
WHERE t1.nomId = $nomId
-- using an OUTER JOIN
UPDATE table1 t1
LEFT
JOIN (SELECT t2.Id, SUM(t2.nomDetCantidad) AS nomCantidadTotal
FROM table2 t2
WHERE t2.Id = $nomId
GROUP BY t2.Id
) s
ON s.Id = t1.nomID
SET t1.nomCantidadTotal = IFNULL(s.nomCantidadTotal,0)
, t1.nomActualizado = NOW()
WHERE t1.nomID = $nomId
It's not at all clear why you need to store this total on table1, when you could derive it from table2 whenever you need it, without storing that value on table1 at all...
SELECT t1.nomId
, IFNULL((SELECT SUM(t2.nomDetCantidad) AS nomCantidadTotal
FROM table2 t2
WHERE t2.Id = t1.nomID
),0) AS nomCantidadTotal
FROM table1 t1
WHERE t1.nomId = $nomId
Is it possible to strip away columns from the response I get in a query where I join 3 tables and need more or less all columns for the query itself so that some columns aren't visible in the response?
This is the query I have:
$sth = mysql_query("
SELECT
tbl_subApp2Tag.*,
tbl_subApp.*,
tbl_tag.*
ISNULL(tbl_userDeviceNOTTag.userDevice_id) AS selected
FROM tbl_subApp2Tag
LEFT JOIN tbl_subApp
ON tbl_subApp.id = tbl_subApp2Tag.subApp_id
AND tbl_subApp.subApp_id = '".$sub."'
LEFT JOIN tbl_tag
ON tbl_tag.id = tbl_subApp2Tag.tag_id
LEFT JOIN tbl_userDeviceNOTTag
ON tbl_userDeviceNOTTag.tag_id = tbl_tag.id
AND tbl_userDeviceNOTTag.userDevice_id = '".$user."'
WHERE tbl_subApp2Tag.subApp_id = tbl_subApp.id
ORDER BY tbl_tag.name ASC ");
if(!$sth) echo "Error in query: ".mysql_error();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
You do not need to include columns in the result table, just because they are referenced elsewhere in the query. Just select the columns that you need.
I have a simple mysql query which is as following:
SELECT DISTINCT(node.nid) AS nid,
node_counter.totalcount AS node_counter_totalcount,
node.title AS node_title,
node_data_field_dep.field_dep_value AS node_data_field_dep_field_dep_value,
node.type AS node_type,
node.vid AS node_vid,
node_data_field_type.field_type_value AS node_data_field_type_field_type_value
FROM node node
LEFT JOIN node_counter node_counter ON node.nid = node_counter.nid
LEFT JOIN content_field_dep node_data_field_dep ON node.vid = node_data_field_dep.vid
LEFT JOIN content_type_project node_data_field_type ON node.vid = node_data_field_type.vid
WHERE (node.type in ('project')) AND (node.status <> 0)
GROUP BY nid
ORDER BY node_counter_totalcount DESC
so i execute the following statements:
$result = mysql_query($query);
where $query is the above SQL query.
Usually, I use mysql_fetch_array($result) or mysql_fetch_row($result) to access the data, but these are not working now and instead giving some error. Is there any other way to use them. I want to print the data selected in a formatted manner.(Say, a table)
It means your query is not executed, there is some error in it or maybe in the connection.
You can find out what the error is using mysql_error() like this:
$result = mysql_query($myquery) or die(mysql_error());
or you can use
$row = mysql_num_rows($result);
echo($row);
If it returns 1 or higher it means your query is returning results.