Right join cannot access Row from other table in PHP - php

$query = "SELECT `Title`, `Date`, `Url`, `Url_Hash`
FROM filings
RIGHT JOIN form_attributes ON
filings.Url_Hash=form_attributes.Unique_Hash
ORDER BY filings.Date ASC
$result = mysqli_query( $mysqli, $query);
while ($row = mysqli_fetch_assoc($result)):
$title = row['col_name_in_form_attributes']; // undefined index error
This is pretty basic but has me stuck. I have 2 tables, filings and form_attributes. I want to access the row names of form_attributes, but get an Undefined index error.
As a workaround, I suppose I could do this with STMT like so:
$stmt = $mysqli->prepare($query);
$stmt->execute();
$stmt->bind_result($result1, $result2, /* etc */);
$stmt->store_result();
However, bind_result() is inefficient as I have over a dozen columns. Much easier to use $row['xyz']; STMT also does not work with MySQL full text search which I am using. Is there a way to do this with mysqli_query or is my SQL incorrect? Thanks.

Not an answer, but FWIW, I find this easier to conceptualise...
SELECT Title
, Date
, Url
, Url_Hash
FROM form_attributes a
LEFT
JOIN filings f
ON f.Url_Hash = a.Unique_Hash
ORDER
BY f.Date ASC

I was forgetting to explicitly call the name of the table plus the column name in my query. Example:
`form_attributes`.`Contact_Info`
Works now!

Related

PHP Prepared Statement variable binding error with subquery

I have a query with a few subqueries like so
SELECT ...
FROM (SELECT ...
FROM ...
GROUP BY ...) as speedLimitCalc INNER JOIN
(SELECT ...
FROM date a INNER JOIN HOURLY_TEST b ON a.[FULL_DAY_DT] = b.DATE
WHERE (b.DATE BETWEEN '".$date_s."' AND '".$date_e."')
AND HOUR BETWEEN ".$time_s." AND ".$time_e."
AND(LKNO BETWEEN '".$lkno_s."' and '".$lkno_e."')
AND RDNO= '".$rdno."'
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (".$dayquery.")
GROUP BY RDNO, LKNO, PRESCRIBED_DIRECTION, CWAY_CODE) as origtable ON ...
,(SELECT ...
FROM [Dim_date]
WHERE (FULL_DAY_DT BETWEEN '".$date_s."' AND '".$date_e."')
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (".$dayquery.") ) as c
ORDER BY ...
where I am inserting variables in the inner query where clause.
I am trying to parametrize this query using odbc_prepare and odbc_execute, however I am running into issues of binding the variables. At present, when I use the following
$result = odbc_prepare($connection, $query);
odbc_execute($result)or die(odbc_error($connection));
to run this query, everything works fine. However, when I try to bind a variable, such as
AND RDNO= ?
...
odbc_execute($result, array($rdno))or die(odbc_error($connection));
I get the following error message.
PHP Warning: odbc_execute() [/phpmanual/function.odbc-execute.html]: SQL error: [Microsoft][ODBC SQL Server Driver]Invalid parameter number, SQL state S1093 in SQLDescribeParameter
My guess is that it's because I'm binding a variable in a subquery, since this procedure works when the Where clause is in the top Select query.
I was wondering whether anyone else has encountered this issue before, and how they solved it? Thanks
Fixed the issue by removing the need for parameters in the subquery by separating the query into multiple queries using temporary tables.
$query = "SELECT ...
INTO ##avgspeedperlink
FROM Date a INNER JOIN HOURLY_TEST ON a.[FULL_DAY_DT] = b.DATE
WHERE (b.DATE BETWEEN ? AND ?)
AND HOUR BETWEEN ? AND ?
AND(LKNO BETWEEN ? and ?)
AND RDNO= ?
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (?,?,?,?,?,?,?)
GROUP BY RDNO, LKNO, PRESCRIBED_DIRECTION, CWAY_CODE";
$result = odbc_prepare($connection, $query);
odbc_execute($result, array($date_s,$date_e,$time_s,$time_e,$lkno_s,$lkno_e,$rdno,$daysanitised[0],$daysanitised[1],$daysanitised[2],$daysanitised[3],$daysanitised[4],$daysanitised[5],$daysanitised[6]))or die(odbc_error($connection));
$query = "SELECT ...
INTO ##daysinperiod
FROM [RISSxplr].[dbo].[Dim_date]
WHERE (FULL_DAY_DT BETWEEN ? AND ?)
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (?,?,?,?,?,?,?)";
$result = odbc_prepare($connection, $query);
odbc_execute($result, array($date_s,$date_e,$daysanitised[0],$daysanitised[1],$daysanitised[2],$daysanitised[3],$daysanitised[4],$daysanitised[5],$daysanitised[6]))or die(odbc_error($connection));
$query = "SELECT ...
FROM ##avgspeedperlink, ##daysinperiod
ORDER BY LKNO, OUTBOUND
drop table ##avgspeedperlink
drop table ##daysinperiod";
Note that I had to use double ## for making the temporary tables (single # means that table is local to the query, ## means that the temporary table becomes global for multiple queries).

PDO MYSQL nested COUNT breaks my query

I have query like this:
$query = $con->prepare("SELECT `Id`,
(SELECT count(`Id`)
FROM `images`
WHERE `parentId` = :recId) as `numImgs`
FROM `records`
WHERE `id`= :recId LIMIT 1");
$query->execute(array('recId' => $recId));
$rec = $query->fetch(PDO::FETCH_ASSOC);
When I do this without the nested (SELECT Count(Id)) the query works.
If I take out the SELECT(COUNT(Id)) and do it on it's own, it also works.
For some reason the above query doesn't work. I don't get any errors, just no results. However if I run the query inside phpMyAdmin, it works without any problem and returns two columns, Id and numImgs, eg:
----------------
| id | numImgs |
----------------
| 50 | 10 |
----------------
I've tested the value I'm passing, it is being correctly populated from $recId so there's no issue there. Can anyone point me in the right direction as to what's going wrong with this?
Thanks!
NOTE: this works perfectly, but I don't understand why I can't do it with one query:
try{
$query = $con->prepare("SELECT `Id`
FROM `records`
WHERE `id`= :recId
AND `ownerId` = :userId
LIMIT 1");
$query->execute(array('recId' => $recId, 'userId' => $userId));
$rec = $query->fetch(PDO::FETCH_ASSOC);
}catch(PDOException $e) {
dump_exception('Exception selecting record.', $e);
}
if($rec){
try{
$picQuery = $con->prepare("SELECT COUNT(`Id`)
FROM `images`
WHERE `parentId`= :recId");
$picQuery->execute(array('recId' => $recId));
$numPics = $picQuery->fetchColumn();
}catch(PDOException $e) {
dump_exception('Exception counting pictures.', $e);
}
Can't you use JOINs and GROUP BY? It would look like this if I got your question right.
SELECT `id`, COUNT(*) AS `numImgs`
FROM `records` r
INNER JOIN `images` i ON i.parentId = r.id
WHERE r.id = :recId
AND r.ownerId = :userId
GROUP BY r.id
LIMIT 1
Looks like I've found the problem thanks to #RyanVincent's comment below. Whilst I have other working queries which use the same parameter more than once without it having to be passed into the "execute" array more than once, in this case, it seems that only listing the parameter once is causing the issue. I suspect that because it's a nested query, it treats it as two independent queries and as such, one has no access to the parameters of another. That's just a guess, I may be wrong, but it seems to make sense based on my results. Not only does the parameter have to be listed twice, but it must also be uniquely named otherwise you get exactly the same problem. So this code fixed the problem:
$query = $con->prepare("SELECT `Id`,
(SELECT count(`Id`)
FROM `images`
WHERE `parentId` = :recIdOne) as `numImgs`
FROM `records`
WHERE `id`= :recIdTwo LIMIT 1");
$query->execute(array('recIdOne' => $recId, 'recIdTwo' => $recId));
$rec = $query->fetch(PDO::FETCH_ASSOC);

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

How to look at the result of a query

I have a SQL Query, although it is executing, but how should i verify if it is giving me the desired result.
For example: My query
$query3 = "SELECT COUNT(DISTINCT(uid)) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
In the above query i am trying to count the number of distinct user ID's(uid) from the table named user-infowhere date is 2011-10-10.
How should i display the count which is calculated for the given date?.I need to know it and perform some further operations on it!
$query3 = "SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'";
$result = mysql_query($query3);
$row = mysql_fetch_array($result);
echo $row['num'];
Just do:
SELECT COUNT(DISTINCT uid) AS `num`
FROM `user_info`
WHERE date(starttime)='2011-10-10'
This SO post goes into some details about how count and count(distinct ...) work. With just count, there is a hidden/assumed function of count(all ... ) actually happening (it's just the default value). If you want to only count distinct things, switch it to the non-default and do the count(distinct ...) instead. I didn't know it existed for my first 6 months of writing sql or so...
You can set a variable sing the result...
SET #userVar=SELECT
COUNT(DISTINCT uid)
FROM
user_info
WHERE
DATE(starttime)='2011-10-10';
Then you can use that variable in your next operation or query.

MySQL: Error in query with UPDATE and JOIN, when ORDER BY is used

I have a problem, where I can't find help. When I delete the ORDER BY and LIMIT addtions, then this query works fine. But with them it causes an "Call to a member function execute() on a non-object"-Error. Using LEFT or INNER JOIN makes no difference.
$sql = "UPDATE tasks JOIN service
ON tasks_account_id = service_id
SET `tasks_status` = 'prog' ,
tasks_user = '".$user."'
WHERE `tasks_status` = 'free' AND `service_besetzt` = '0'
ORDER BY `tasks_client_date` ASC, `tasks_id` ASC
LIMIT ".$limit."";
$result = $db->prepare( $sql );
$result->execute();
Has someone an idea?
Thanks!
The issue is that you are using multiple-table UPDATE and ORDER BY and LIMIT clauses cannot be used with it; however they work nice with a single-table UPDATE. Please refer para 2 on http://dev.mysql.com/doc/refman/5.0/en/update.html.
$db->prepare($sql) is returning null. :)
Maybe the prepare method cannot handle LIMIT/ORDER BY... which makes sense as you cannot order an UPDATE query.

Categories