Sqlite3 synthax error while joining tables using PDO - php

I have a problem with PDO and sqlite3. While trying to join tables I am getting an error:
object(PDO)#1 (0) { } {"error":true,"message":"SQLSTATE[HY000]: General error: 1 near \u0022FROM\u0022: syntax error"
my connection and sql query looks like this. The sublime-text 2 also does not color JOIN like others.
$objDb = new PDO('sqlite:../dbase/shopping-list');
var_dump($objDb);
$objDb -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT `i`.*,
`t`.`name` AS `type_name`
FROM `items` `i`
JOIN `types` `t`
ON `t`.`id` = `i`.`type`
ORDER BY `i`.`date` ASC";
$result = $objDb->query($sql);
if(!$result) {
throw new PDOException("The result returned no object");
}
I follow a tutorial and he can use this statement with mac. I use arch linux but I dont think so it is related.
When I check sqlite database with cli, I can get the types table :
sqlite> SELECT * FROM `types`;
1|Qty
2|Kg
Is there anyway to accomplish this query ?
edit : I have changed db and removed backticks ... Now I can get the items but still I have an error and they dont work inside my angularjs frontend.
object(PDOStatement)#3 (1) { ["queryString"]=> string(37) "SELECT * FROM types ORDER BY id" } {"error":false,"items":[{"id":"1","item":"Butter","qty":"1","type":"1","done":"0","date":"2014-10-06 02:45:51","type_name":"Qty"}],"types":[{"id":"1","name":"Qty"},{"id":"2","name":"Kg"}]}
here is correct sql query with JOIN
$sql = "SELECT item.* ,
t.name AS type_name
FROM items item
INNER JOIN types t
ON t.id = item.type
ORDER BY item.date ASC";
this is my select.php link

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'];

Current selection does not contain a unique column. Mysqli. Duplication?

I can't seem to select/retrieve the "Package Table" and merge it into 1 table that contains the other table which is "Events Table". I don't know what seems to be the problem though.
Whenever i tried to execute my query and the only thing that pops up is the
events_ table, the Package table on the other hand does not. I tried another another simple query,
SELECT * FROM event_table JOIN package ON event_id WHERE cusact_id = 8 AND event_id=80
And the query works fine.
Event Table (Structure):
http://prntscr.com/gbr6vr
Package Table (Structure):
https://prnt.sc/gbr793
Note: I have a column named package_id on events_table and package. Is that the problem? Im sorry, still new to mysql.
side note:
$c_id = $_SESSION['u_id'];
$n_id = $_GET['n_id'];
$p_id = $_GET['new_p_id'];
all of these has data, so no problem here.
Here is my query:
<?php
session_start();
include_once 'order.confirmation-header.php';
include 'includes/dbh.inc.php';
$c_id = $_SESSION['u_id'];
$n_id = $_GET['n_id'];
$p_id = $_GET['new_p_id'];
$sql = "
SELECT event_id, event_name, event_date, event_time_start,
event_time_end, cusact_id, theme, reserve_date, reserve_time
FROM event_table as e
INNER JOIN package as p
ON e.package_id = p.package_id
WHERE cusact_id = $c_id AND event_id=$n_id
";
$data = mysqli_query($conn, $sql);
if(!$data){
echo("Error description: " . mysqli_error($conn));
}
You aren't requesting any of the package columns (by merge the table I assume you mean retrieve a record set)
SELECT event_id, event_name, event_date, event_time_start,
event_time_end, cusact_id, theme, reserve_date, reserve_time, p.*
FROM event_table as e
INNER JOIN package as p
ON e.package_id = p.package_id
WHERE cusact_id = $c_id
AND event_id=$n_id
Your code is wide open to SQL injection, and I'd really consider using the PDO API with a prepared statement.

Simultaneous mysqli_stmt prepared queries

I have following code:
<ol>
<?php
$db = mysqli_connect("host","login","pass","dbase");
$stmt = $db->prepare("SELECT id,name FROM table1 WHERE faculty=?");
$stmt->bind_param("d",$fac);
$stmt->execute();
$stmt->bind_result($id,$name);
while($stmt->fetch())
{
echo "<li>$name:<ul>";
$stmt2 = $db->prepare("SELECT mac,ip FROM table2 WHERE uid=?");
$stmt2->bind_param("d",$id);
$stmt2->execute();
$stmt2->bind_result($mac,$ip);
while($stmt2->fetch())
{
echo "<li>$mac ($ip)</li>";
}
echo "</ul></li>";
}
?>
</ol>
I get the error Commands out of sync; you can't run this command now. I know that I cannot have multiple queries running at once, but I've read, that I can use $stmt->store_result(). The problem is, that it does not help in my case (I tried calling it just after $stmt->execute()). How can I get my code working? Is it possible to do it without storing the results of first query in an array?
A single query with a LEFT JOIN will work in this case:
SELECT `t1`.`id`, `t1`.`name`, `t2`.`mac`, `t2`.`ip`
FROM `table1` AS `t1`
LEFT JOIN `table2` AS `t2`
ON `t1`.`id` = `t2`.`uid`
WHERE `t2`.`uid` = ?
This query will return all four columns in one shot provided id in table 1 is uid in table 2.

PHP and SQL INSERT JOIN 2 tables with criteria error

$rentingsquery = "SELECT * FROM TBL_rentings WHERE personId='$personId'
JOIN TBL_rentings ON TBL_properties.propertyId = TBL_rentings.propertyId
JOIN TBL_people ON TBL_rentings.personId = TBL_people.personId";
$rentingsResult=mysql_query($rentingsquery) or die ("Query to get data from TBL_properties failed: ".mysql_error());
This is the error I get when I execute the code in my web page:
What I'm trying to do is select only the 'rentings' where the personId = $personId, (as the current page is a page for each individual person), and display only those 'rentings'. Also in the code which I haven't posted I'm displaying data about the property which is related to that rent, hence why I'm trying to join the renting and properties table with propertyId so that I call the correct property's details off the database.
$rentingsquery = "SELECT * FROM TBL_rentings
JOIN TBL_rentings ON TBL_properties.propertyId = TBL_rentings.propertyId
JOIN TBL_people ON TBL_rentings.personId = TBL_people.personId
WHERE personId='$personId'";
$rentingsResult=mysql_query($rentingsquery) or die ("Query to get data from TBL_properties failed: ".mysql_error());
First of all try this, the where condition has to be after the joins.
If there are other problems I will edit the answer
The next problem is that you are joining the same table, but you are joining it in an external field. A quick fix, if I am supposing correct, is that you wrongly joined with an unwanted table:
SELECT * FROM TBL_rentings
JOIN TBL_properties ON TBL_properties.propertyId = TBL_rentings.propertyId
JOIN TBL_people ON TBL_rentings.personId = TBL_people.personId
WHERE TBL_rentings.personId='$personId'

php MySQL error for retrieving data

I have a PHP code for selecting data from a database, but it produces NULL result, although the same query performed manually works well. Here's relevant part of code:
$conn = mysqli_connect($host,$user,$password);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_db_name($dbName,$conn);
$query = "SELECT Images.Path,p.NameAr,p.DescriptionAr FROM
(SELECT * FROM project where TypeID = 1) as p
JOIN Images where Images.ProjectID = p.ID";
$result = mysql_query($query,$conn);
var_dump($result);
What can be wrong about it?
Not sure about PHP related error but your query formation is not corect.
Change your query like below. Moreover, you are not fetching any column from images table then why do a join with images table?
SELECT Path,NameAr,DescriptionAr
FROM
(
SELECT p.* FROM project p
JOIN
Images i on i.ProjectID = p.ID and p.TypeID = 1
) tab
You use mysqli_connect but then you wrote mysql_* If you fix all mysql_* to mysqli_* it should work.

Categories