Get earliest year from multiple tables - php

I have a couple tables where there is a same field added. What I want to do is get the earliest year from all these records.
Tables:
comics | movies | tv | tv_episodes
Code So Far (Doesn't Work):
function getStartYear() {
include("config.php");
$query = "SELECT DATE_FORMAT(added, '%Y') as `added` FROM (comics,movies,tv,tv_episodes) ORDER BY `added` DESC LIMIT 1";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
return $row['added'];
}
}
Error Returned:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in E:\xampp\htdocs\mydb\functions\common.php on line 94
What would be the most efficient way to do this?
UPDATE
So going by Andrew's answer the new query looks like:
function getStartYear() {
include("config.php");
$query = "SELECT MIN(y) FROM (
SELECT MIN(YEAR(added)) AS y FROM comics
UNION SELECT MIN(YEAR(added)) AS y FROM movies
UNION SELECT MIN(YEAR(added)) AS y FROM tv
UNION SELECT MIN(YEAR(added)) AS y FROM tv_episodes
) AS t1";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$finalanswer = mysql_fetch_array($result);
return $finalanswer['t1']; // <-- Line 96
}else{
echo mysql_error();
}
}
New Message:
Notice: Undefined index: t1 in E:\xampp\htdocs\mydb\functions\common.php on line 96

Could retrieve it through SQL using a UNION sub-query:
SELECT MIN(y) FROM (
SELECT MIN(YEAR(added)) AS y FROM table1
UNION SELECT MIN(YEAR(added)) AS y FROM table2
...
) AS t1;

First you should be checking to make sure your SQL statement actually returns the desired data. Run the script itself in some sort of SQL viewer (or phpMySQL), or
echo mysql_error();
just to be sure you don't have an invalid SQL statement.
The invalid resource error you're getting indicates to me that the "$result" of your mysql_query function is not a valid resource.
So:
if (!$result = mysql_query($query))
echo mysql_error();
if you do have an error in your query, diagnose and fix and go from there...
As it stands right now, you're doing a "return" from the middle of a loop, which means you're returning the first object found in the result set.
I would consider instead of "looping", do this:
if (mysql_num_rows($result) > 0)
{
$finalanswer = mysql_fetch_array($result);
return $finalanswer['added'];
}
else
echo mysql_error();
error trapping is kind of a nice thing to get in the habit of. :)

Related

How to get specific data from table1, use it in table2

I'm trying to get specific rows in table 1 (stellingen). I want to store these rows to specify the rows im interested in for the second table (stelling). So lets say table 1 has 5 rows where stelling ID matches REGIOID = 5. These IDS from stelling ID I want to use to fetch the data from the second table. see the code to see what I tried. I'm not managing to find a way in order too make this happen.
So maybe too be clearer because people always say im not clear:
There are two tables. they both have a matching column. Im trying to tell the second table I want data but only if it matches the data of the first table. Like a branch of a tree. Then, I want to output some data that's in the second table.
I've tried something like this before:
SELECT
*
FROM
table2
LEFT JOIN
table1 ON
table1.ID = table2.table1_id
I've tried to create a while loop to get the data before(after the first if statement and the last += was for the variable $amountofstellinge):
$amountOfStellinge = 0;
while ($amountOfStellinge<5){
mysqli_data_seek($result, $amountOfStellinge);
Here is the code what it looks like now, its wrong, i've been messing with t a lot, but maybe it shows you what I'm trying to achieve better.
if($result = mysqli_query($con, "SELECT * FROM stellingen WHERE REGIOID=1;")) {
$row = mysqli_fetch_assoc($result);
$stellingid= $row["Stelling_ID"];
//checking.. and the output is obviously not what I want in my next query
printf($stellingid);
//defining the variable
$Timer=0;
$sql1="SELECT * FROM stelling WHERE stelling_iD=$stellingid ORDER BY Timer DESC;";
$records2 = mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records2);
//max 5 data
if ($recordscheck < 5){
while ($stelling = mysqli_fetch_assoc($records2)){
//At the end, i would like to only have the data that is most recent
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}}
$recordscheck+=1; } // this is totally wrong
EDIT:
I've tried this, #noobjs
$Timer=0;
$sql1="SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.ID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer LIMIT 5 DESC ;";
$records2 = mysqli_query($con, $sql1);
printf($records2);
while ($stelling = mysqli_fetch_assoc($records2)){
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}
with this error:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in
EDIT for more clarification
Here is some sample data
The expected results is:
every page has uses data from a different REGIOID. I expect the page to show data from the table stelling(Table 1). Accordingly to the REGIOID (Table2)
if i understand right:
SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.stellingID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer DESC LIMIT 5 ;

mysql query return boolean but I expect to return id

This is my query:
select id
from inquiry
where id = (select min(id) from inquiry where (id > 108 AND is_deleted=N))
What is wrong in this query?
I'm expecting like in nested where id is compared to 108 and result will be greater than 108 but it returns boolean
calling function with parameters like
nextIdUserInquiry(108, $con, 'N');
and whole function body is below
function nextIdUserInquiry($inquiryId, $conn, $cond)
{
echo "in function";
$qry="select id from inquiry where id = (select min(id) from inquiry where (id > $inquiryId AND is_deleted=$cond))";
echo $qry;
$result = $conn->query($qry);
$row = $result->fetch_assoc();
echo $row["id"];
}
and mysql error is that
Call to a member function fetch_assoc() on boolean in C:\xampp\htdocs\besttour\admin\connect_db_test.php
the inner query returns a queryset, therefore you can't use ...where id=(select... try instead ...where id in (select...
or even better try with the following:
select id
from inquiry
where (id > 108 AND is_deleted=N)
order by id asc
limit 1
(tanks to P.Salmon)

PHP left join not displaying results

I am trying to left join to tables in PHP. I am a total noob to left join and I can't figure out what I'm doing wrong!
$value=$_GET['value'];
$storeid=$_GET['store'];
$id=$_GET['id'];
$latitude=$_GET['lat'];
$longitude=$_GET['long'];
$result = mysqli_query($con,"SELECT carlist.id, carlist.vin, link_qr.qr, link_qr.vin
FROM link_qr, carlist LEFT JOIN link_qr.vin ON carlist.vin
WHERE qr="$value";");
while($row = mysqli_fetch_array($result)) {
echo $row['id'];
echo $row['vin'];
echo $row['qr'];
}
Here is the table structure
Table: link_qr
id------vin---------qr------webid---------other
Table: carlist
id---stknum---vin----vt----stat---other---store_id---web_code---qrcode
When all done I would like to have the following.
I would like to join the carlist and the link_qr where the vins are equal to each other and then I need it to return the carlist id where that vin is equal to qr.
Here are the errors I'm getting:
**Notice: Undefined index: store in /api/app_request/left_join.php on line 13
Notice: Undefined index: id in /api/app_request/left_join.php on line 14
Notice: Undefined index: lat in /api/app_request/left_join.php on line 15
Notice: Undefined index: long in /api/app_request/left_join.php on line 16
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in api/app_request/left_join.php on line 22**
There are a couple things to note:
First, your SQL query is incorrect:
SELECT carlist.id, carlist.vin, link_qr.qr, link_qr.vin
FROM carlist
LEFT JOIN linkqr ON linkqr.vin=carlist.vin
WHERE qr="$value";
Should be the correct format so long as those tables and columns exist. Secondly, however, you should not be querying a database with an unescaped value. This leads to SQL Injection. More appropriately you could write your query like:
$query = <<<SQL
SELECT carlist.id, carlist.vin, link_qr.qr, link_qr.vin
FROM carlist
LEFT JOIN linkqr ON linkqr.vin=carlist.vin
WHERE qr=?
SQL;
$stmt = mysqli_prepare($query);
mysqli_bind_param($stmt, "s", $value); // this sets the ? in the sql query to $value
mysqli_execute($stmt);
$result = mysqli_get_result($stmt);
while($row = mysqli_fetch_array($result)) {
echo $row['id'];
echo $row['vin'];
echo $row['qr'];
}
Why not do:
"SELECT C.PrimaryId, Field, AnotherField
FROM tablename AS C
LEFT JOIN tablename AS L ON C.matching_id = T.matching_id
WHERE tablename.fieldname = :fieldname
?

Error when using "ORDER BY count" in query

I'm using the following query to display some information:
$result = mysqli_query ($con,"SELECT * FROM files,members,member_group WHERE files.member_id = members.member_id AND members.member_id = member_group.member_id AND group_id='$id' ORDER BY count DESC ");
My issue is it works fine when I leave out ORDER BY count DESC but when it is there I get the following error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /proj/co600/project/repo/public_html/select_field3.php on line 227
Count is a column in my database which records the number of times a publication is downloaded.
count is an aggregate function, so you need to surround it with backticks.
To get a clear cut picture of your error.. You need to change your code like..
$result = mysqli_query ($con,"SELECT * FROM files,members,member_group WHERE files.member_id = members.member_id AND members.member_id = member_group.member_id AND group_id='$id' ORDER BY count DESC ");
if(!$result)
{
die(mysqli_error($con));
}
You are having MySQL reserved keyword as column name in table.
Use Below query:
$result = mysqli_query ($con,"SELECT * FROM files,members,member_group WHERE files.member_id = members.member_id AND members.member_id = member_group.member_id AND group_id='$id' ORDER BY `count` DESC ");

SQL query doesn't give any results in PHP

I am using the following query:
$query = "SELECT (SELECT count(*) FROM survey_ptw WHERE erfh= '0') AS F01,
(SELECT count(*) FROM survey_ptw WHERE erfh='10') AS F02,
(SELECT count(*) FROM survey_ptw WHERE erfh='50') AS F03";
$result = mysql_query($query);
print sprintf('Erf: <table><tr><td>none</td><td>%s</td></tr><tr><td>more</td><td>%s</td></tr></table>', $F01,$F02);
When I'm doing the above query in phpMyAdmin, it displays the variables nicely with the correct result values. Doing the same in PHP however, no results are displayed (empty strings)!
mysql_errno() and mysql_error() don't return errors. The DB has been open and selected further up in the code.
Any idea what's going on?
Because you aren't doing anything with the results.
From the documentation for mysql_query():
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
So, to retrieve the results, you can use a while loop as below:
while ($row = mysql_fetch_assoc($result)) {
# code...
}
check $res=mysql_fetch_assoc($result); then print_r(); to check the result. it will work.
$query = "SELECT (SELECT count(*) FROM survey_ptw WHERE erfh= '0') AS F01,
(SELECT count(*) FROM survey_ptw WHERE erfh='10') AS F02,
(SELECT count(*) FROM survey_ptw WHERE erfh='50') AS F03";
$result = mysql_query($query);
$res=mysql_fetch_assoc($result);
$res=$res[0];
sprintf('Erf: <table><tr><td>none</td><td>%s</td></tr><tr><td>more</td><td>%s</td></tr></table>', $res['F01'],$res['F02']);

Categories