Getting Empty array on INNER query in MySQL - php

I am a newbie in PHP/MySQL and this is my first question on stackoverflow, so please ignore any mistake if I have made any.
I am trying to get records from a table through this query.
$CId = $this->input->post('Child_id'); //child_id is the value from a textfield
$r_detail = ("SELECT *
FROM `result_details`
WHERE ResultId
IN (SELECT Result_Id
FROM `results`
WHERE childId = '".$CId." ') " );
this query is returning an empty $r_detail. However when I query the same statement in PHPMyAdmin in localhost and change "$CID" to a number, I get the desired records.
Any Help will be much appreciated.

You have a space in INNER JOIN WHERE: '".$CId." ' should be '".$CId."'.

$r_detail = ("SELECT *
FROM `result_details`
WHERE ResultId
IN (SELECT Result_Id
FROM `results`
WHERE childId = '".$CId." ') " );
has just string...you need to call some db function to get the data such as in code igniter may be
$this->db->query($r_detail);

Related

Query works in phpmyadmin but same query won't return in PHP script

This is NOT a duplicate. None of the already existing threads have the same problem as me.
I have a database that stores athlete performances. It contains sessions, each session has sets, each set has "tables" (such as 4x100m, 12x50m and so on), and each table has times. I also have a table for athletes. Each athlete has an ID, each time links with the athlete through the AthleteID. Every session, set, timetable and time also have each unique IDs, used to link them with each other.
I want to make it so that when passing a session ID, it will return all the athletes that have at least 1 time in that session. I made a page that gets requests and the session ID is passed as GET search data (will make it POST later on). The request system works fine, but the problem is in the query. To do it I used inner joins to connect each table. This is my query (it is not the fastest method, but that's for another thread):
$q = "SET #evID = " . $method['sessID'] . ";";
$q .= "SELECT `athletes`.* FROM `events`
INNER JOIN `sets` ON `sets`.`EventID` = `events`.`EventID`
INNER JOIN `timetables` ON `timetables`.`SetID` = `sets`.`SetID`
INNER JOIN `times` ON `times`.`TableID` = `timetables`.`TableID`
INNER JOIN `athletes` ON `athletes`.`ID` = `times`.`AthleteID`
WHERE `events`.`EventID` = #evID
AND `times`.`TimeID` IN(
SELECT MIN(`TimeID`)
FROM `times`
WHERE `TableID` IN(
SELECT `TableID`
FROM `timetables`
WHERE `SetID` IN(
SELECT `SetID`
FROM `sets`
WHERE `EventID` = #evID
)
)
GROUP BY `AthleteID`
)";
Every single time I ran that in phpmyadmin it returned all the athletes, and the data was correct. However, when I run it in my script, the query value is false (such as if there is an error). I tried debugging like this:
$r = $db -> query($q);
var_dump($q);
var_dump($r);
var_dump($db->error);
The query is returned just fine (only difference is lack of newline characters), and when I copy what's returned in phpmyadmin the data is just the same. The rest however:
bool(false)
string(228) "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT `athletes`.* FROM `events` INNER JOIN `sets` ON `sets`.`EventID` = `...' at line 1"
Other users with the same problem have not really gone that far to find out if they're wrong, but I have. This post is not a duplicate, and I didn't find any solutions online. Could this be a problem with the amount of queries in a single string? (There is one for setting #evID and one for the actual selection). Please explain the solution and methods kindly as I'm only 13 and still learning...
As #NigelRen has suggested, please use parameterized prepared statement.
Assuming that
$sessionid is storing the value for EventID, and assuming that this variable is of integer type; and
$conn is the connection
Then for Mysqli, you can use:
//$q = "SET #evID = " . $method['sessID'] . ";";
$sql = "SELECT `athletes`.* FROM `events`
INNER JOIN `sets` ON `sets`.`EventID` = `events`.`EventID`
INNER JOIN `timetables` ON `timetables`.`SetID` = `sets`.`SetID`
INNER JOIN `times` ON `times`.`TableID` = `timetables`.`TableID`
INNER JOIN `athletes` ON `athletes`.`ID` = `times`.`AthleteID`
WHERE `events`.`EventID` = ?
AND `times`.`TimeID` IN(
SELECT MIN(`TimeID`)
FROM `times`
WHERE `TableID` IN(
SELECT `TableID`
FROM `timetables`
WHERE `SetID` IN(
SELECT `SetID`
FROM `sets`
WHERE `EventID` = ?
)
)
GROUP BY `AthleteID`
)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $sessionid, $sessionid);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$row = $result->fetch_assoc(); // fetch data
// do other things you want , such as echo $row['fieldname1'];

Selecting data from 2 tables where columns are the same, query not quite right?

I'm trying to fetch data from 2 tables where the prop_slug and prop_gallery_id match. I've written the following statement only I cant seem to get it to work and keep getting an error with my syntax - can anybody see if there's a glaring mistake in my query?...
$listings = $db->query('
SELECT *
FROM listing_details
JOIN prop_gallery
ON prop_gallery.prop_gallery_id = listing_details.prop_slug
WHERE (listing_details.prop_slug LIKE \'prop_gallery_id\' OR prop_gallery.prop_gallery_id LIKE \'prop_slug\')
AND
WHERE listing_details.prop_mandate = 1
LIMIT 3')->fetchAll();
You don't need the second WHERE
$listings = $db->query('
SELECT *
FROM listing_details
JOIN prop_gallery
ON prop_gallery.prop_gallery_id = listing_details.prop_slug
WHERE (listing_details.prop_slug LIKE \'prop_gallery_id\' OR prop_gallery.prop_gallery_id LIKE \'prop_slug\')
AND listing_details.prop_mandate = 1
LIMIT 3')->fetchAll();

Relational table query gives me a null value in the field 'id' in table

I am creating a query and I used the LEFT JOIN to join two tables. But I'm having trouble in getting the fb_id value from the table, it gives me an empty result. Here is my code:
$sql = "SELECT * FROM tblfeedback a LEFT JOIN tblreply b ON a.fb_id = b.fb_id WHERE a.fb_status = 1 ORDER BY a.fb_id DESC";
$res = $con->query($sql);
....
....
The query above would give me a result like this :
I think that's why I don't get the fb_id value is because the last column is null. How do I get the value of fb_id from the first column? Thanks. I am really having trouble with this. I hope someone can enlightened my mind.
You should give an alias to the column in the parent table, because the column names are the same in both tables. When fetch_assoc() fills in $row['fb_id'], it gets the last one in the result row, which can be NULL because it comes from the second table.
SELECT a.fb_id AS a_id, a.*, b.*
FROM tblfeedback a
LEFT JOIN tblreply b ON a.fb_id = b.fb_id
WHERE a.fb_status = 1
ORDER BY a_id DESC
Then you can access $row['a_id'] to get this column.
More generally, I recommend against using SELECT *. Just select the columns you actually need. So you can select a.fb_id without selecting b.fb_id, and it will always be filled in.
Because you are using a left join, the 2 rows in your result set image are the rows from tblfeedback whose fb_id were not found in tblreply. We know this is true because all the tblreply columns in the result set are null.
With that said, its not real clear what you are asking for. If you are asking how you access the tblfeedback.fd_id column from your query via php, you can use the fetch_array method and use the 0 index.
$sql = "SELECT * FROM tblfeedback a LEFT JOIN tblreply b ON a.fb_id = b.fb_id WHERE a.fb_status = 1 ORDER BY a.fb_id DESC";
$res = $con->query($sql);
while($row = $res->fetch_array()) {
echo "fb_id: " . $row[0] . "<br>";
}

Multiple Select Query MySQL without while loop

I have two different tables where I need to fetch the list of store ids from one table and then find the list of coupons for those store ids.
Currently,
SELECT `storename` FROM `stores` where `brandname` = 21
This will return something like
Store 1
Store 2
Store 3
Store 4
And I need to to run another query like
SELECT * FROM `coupons` where `storename` = {{All these stores}}
I can't use while loops because, the number of stores comes from first query can't be determined and the the output I want was not coming as expected while using while loop as I am trying to do something like
while(first query output get storename)
{
do query here
while(second query output get all coupons per store)
{
// All coupons display here.
}
}
This is making quite complicated as well, is there anyway that I can tweak my SQL query and get results easily?
Thanks
you can use this query:
SELECT * FROM `coupons`
where `storename` IN (
SELECT `storename` FROM `stores` where `brandname` = 21);
$query = 'SELECT t.storename, h.couponid AS couponsid, h.coupon AS couponvalue'
. ' FROM #__stores AS t'
. ' LEFT JOIN #__coupons AS h ON h.storename = t.storename'
. ' where `brandname` = 21'
. ' ORDER BY anything you like'
;

Get Duplicate data from the Database

i want to fetch duplicate data from the database but the problem is:
i have userids in an array like :
1235, 1235, 5468, 84321, 1235
i used implode and to make that array in string in implement into the database like:
"select * from tbl_name where userid in ('" . $implode_arr . "') limit 0, 10";
which is give me the result like 1235, 5468, 84321 but i want all the data, solution for this is simply run the query in the FOR LOOP or else
but i want same because i add the pagination within the query.
I don't want any code because its already working but the problem is to add pagination Please help to resolve the problem :(
It sounds like you want to join in the user data into this query. You can do that using a LEFT JOIN like this:
SELECT *
FROM tbl_name
LEFT JOIN database_name.user ON database_name.user.id = tbl_name.userid
WHERE userid IN (...)
LIMIT 0, 10
This is assuming your users are stored in the user table in the database_name database, and that the user table has an id field which matches up to the tbl_name field userid. If your fields or table names are different, just change them in this query. In PHP that would be:
"SELECT * FROM tbl_name LEFT JOIN database_name.user ON database_name.user.id = tbl_name.userid WHERE userid IN ('" . $implode_arr . "') LIMIT 0, 10"
Note that to connect two databases, both must be accessible by your same connected user.
Try this it would also work as expected
select * from tbl_name where FIND_IN_SET(user_id,'1235, 1235, 5468, 84321, 1235
') limit 1,10
Check this to remove duplicates

Categories