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.
Related
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'];
ok guys I need a bit of help with this, remaking this to format ir properly.
I have this code:
(this is accessing a table called "students" in database.)
<?php
require_once('connection.php');
$id = $_SESSION['SESS_MEMBER_ID'];
$result3 = mysql_query("SET NAMES UTF8;");
$result3 = mysql_query("SELECT * FROM students where mem_id='$id'");
while($row3 = mysql_fetch_array($result3))
{
$fname = $row3['fname'];
$country = $row3['country'];
$class = $row3['class'];
$headteacher = $row3['headteacher'];
$attendance = $row3['attendance'];
$homework = $row3['homework'];
$messagestudent = $row3['messagestudent'];
}
?>
<?php
if($class=='K1')
echo "teacher 1";
else if($class=='K2')
echo "teacher 2";
else if($class=='K3')
echo "teacher 3";
?>
In another table, i have the teacher names and what i need to do and i cannot find the right way to do it, is to call the teacher's name from the table "teachers" after the query confirms the K1, K2 or K3 data on the "students" table column "class".
Basically what i need is to change the contents of the echo part, switching it from static data needed to be within the code, to a data contained on another table, for example. both tables have a column called "class", so if class column for a student says "K1" i want this to then go check the "teacher" table's column "class" and pick the one that matches "K1" and display it in the result echo, I'm sure it is possible, but not with my current skill level.
The table structure for students is:
mem_id, username, password, fname, country, class, attendance, homework, messagestudent
The table structure for teacher is:
mem_id, class, name, comment
Hope you guys shed some light on me!
Thanks in advance.
PS. I know the query is using the deprecated mysql_, but when I tried to change it to mysqli_ following a guide, it never worked.
If I understood, you can get the desired data through this query (without JOIN or if statement):
SELECT students.*,teachers.name FROM students,teachers WHERE students.id='$id' AND students.class = teachers.class
It returns the teacher name according the student class, at the same row.
You can use left join for this. Try using following query:
SELECT * FROM students as st
LEFT JOIN teachers AS ts
on st.class=ts.class
WHERE st.mem_id = '$id'
You don't need to use if-else statement for this. And it will also work with mysqli.
According to your script, it should work like:
<?php
require_once('connection.php');
$id = $_SESSION['SESS_MEMBER_ID'];
$result3 = mysql_query("SET NAMES UTF8;");
$result3 = mysql_query("SELECT st.*, ts.name AS teacher_name FROM students as st LEFT JOIN teachers AS ts on st.class=ts.class WHERE st.mem_id = ".$id);
while($row3 = mysql_fetch_array($result3))
{
$fname = $row3['fname'];
$country = $row3['country'];
$class = $row3['class'];
$headteacher = $row3['headteacher'];
$attendance = $row3['attendance'];
$homework = $row3['homework'];
$messagestudent = $row3['messagestudent'];
$teachername = $row3['teacher_name'];
}
echo $class. ' - '. $teachername;
?>
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
I'm currently trying to delete a row from a mysql table using php. I have two very basic tables. 'worksheet' and 'worksheet_labour'. Worksheet contains a field called job_ID and it has a field called WS_ID. Worksheet_Labour has a field called WS_ID and various other fields. I'm trying to delete all of the information within worksheet_labour for a particular job_ID that can be found in worksheet. This is what I've attempted so far but haven't had any luck so far. Any help would be greatly appreciated. Thanks
if(isset($_GET["delete"]))
{
$SQL = "DELETE FROM worksheet_labour INNER JOIN worksheet ON worksheet_labour.WS_ID = worksheet.WS_ID WHERE job_ID = '1234'";
$resultset2 = mysql_query($SQL);
}
Give this a try:
$SQL = "DELETE wl FROM worksheet_labour wl INNER JOIN worksheet w ON wl.WS_ID = w.WS_ID WHERE wl.job_ID = '1234'";
I am getting a bunch of undefinded index warnings when i print out my data from a SQL query, when i remove the INNER JOINS most of the warnings disappear. I am not sure what is causing that error.
My code is here:
<?php
$id = $_GET['id'];
$sql = "SELECT * FROM updates INNER JOIN clients ON updates.c_id = clients.c_id INNER JOIN pages ON updates.page = pages.p_id INNER JOIN projects ON updates.p_id = projects.p_id WHERE u_id='$id' LIMIT 1";
echo $sql;
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
// put update_id in hidden form and pass it to the next page
$u_id = $row['u_id'];
?>
<h4>Viewing update for <i><? echo $row['fname'] ." ". $row['lname'] ?></i> for their <i><? echo $row['p_title']; ?> project</i></h4>
<h4><b>Posted on: </b> <? echo $row['date_submitted'] = date("F j, Y, g:i a"); ?></h4>
Any idea on what I can do? The reason I have the INNER JOIN for CLIENTS is because "fname" and "lname" are stored there
clients.c_id = updates.c_id
Where I have: "p_url" "p_title" those are stored in the table PROJECTS which is also:
clients.c_id = projects.c_id
Edit with new problem
My code is here:
$sql = "SELECT
updates.u_id AS u_id,
updates.date_submitted AS date_submitted,
updates.deadline AS deadline,
updates.description AS description,
updates.priority AS priority,
pages.page_name AS page_name,
clients.fname AS fname,
clients.lname AS lname,
projects.p_url AS p_url,
projects.p_title AS p_title,
FROM updates INNER JOIN clients ON updates.c_id = clients.c_id INNER JOIN pages ON updates.page = pages.p_id INNER JOIN projects ON updates.p_id = projects.p_id WHERE u_id='$id' LIMIT 1";
The error is:
Not unique table/alias: 'clients'
Edited answer:
Ah, I incorrectly assumed it had to do with SQL indexes. It appears it's actually a PHP error, related to you trying to print out array elements that don't exist.
For all of your prints that include elements of $row ($row['deadline'], etc), you need to make sure that there are actually columns named that being returned by your query. If there's not a column named "deadline", that attempt to print it is going to generate the warning.
Edit again: since this got bumped up, I guess I'll go into a little more detail.
First of all, as bobince points out, you have SQL injection possible. The first line should be:
$id = intval($_GET['id']);
if $id will always be an integer, and mysql_real_escape_string() if it could be a string.
Second, SELECT * is generally bad form, especially in a case with joins. I don't know exactly which tables particular fields come from, but your query should look more like this, where you select only the fields you're actually going to use:
$sql = "SELECT clients.fname, clients.lname, projects.p_url, projects.p_title, updates.date_submitted ".
"FROM updates ".
"INNER JOIN clients ON updates.c_id = clients.c_id ".
"INNER JOIN pages ON updates.page = pages.p_id ".
"INNER JOIN projects ON updates.p_id = projects.p_id ".
"WHERE updates.u_id='$id' ".
"LIMIT 1";
Next, $u_id gets set to exactly the same value as $id already had, so it's kind of a pointless variable.
Finally, on the last line, you have:
<? echo $row['date_submitted'] = date("F j, Y, g:i a"); ?>
I'm not sure what you're expecting this to do, but it's going to assign date("F j, Y, g:i a"); to $row['date_submitted'] and then end up printing out "true" or "1" or something, that's probably not what you were going for.
Newest problem: You both try to select from clients, and join clients, you can't do both, at least without giving one of them an alias.
I don't think this has anything to do with the SQL (but I could be wrong). You might take a look at this thread for a start.
SELECT * FROM updates INNER JOIN clients
When you ‘SELECT *’ you get each column from both tables. Because columns can have the same names, the column names generated automatically by ‘*’ are prefixed with the table name. So your associative array will contain indexes like:
updates.u_id
clients.c_id
...
So when you try to access the array using an unprefixed column name such as 'page_name', it fails because that index isn't there.
You can use the full column name ('pages.page_name'), or you can explicitly give your own column names by saying:
SELECT updates.u_id AS u_id, pages.page_name AS page_name, ...
FROM updates JOIN client ...
u_id='$id'
Whoops, SQL injection hole. Congratulations, you are this week's 1000th winner of the obligatory xkcd link.
mysql_real_escape_string() is your friend. (Even better: mysqli parameterised queries.)
<? echo $row['deadline']; ?>
Whoops, HTML injection hole. htmlspecialchars() is your friend.