PHP : Can't create automatic query - php

I want to build a search engine for a webpage. I use the code below. The problem is, that I have to build the queries from different strings and if the system searches for matching in strings, quote marks are needed.
$sql = "SELECT TIT,VNEV,KNEV,NEME,MEGY,LCVAR,APOLG FROM TORZS LEFT OUTER JOIN VEGZETTSEG ON TORZS.ID = VEGZETTSEG.ID LEFT OUTER JOIN SZTAPASZTALAT ON TORZS.ID = SZTAPASZTALAT.ID LEFT OUTER JOIN SZAKTANFOLYAM ON TORZS.ID = SZAKTANFOLYAM.ID LEFT OUTER JOIN INFORM ON TORZS.ID = INFORM.ID WHERE ";
for ($i = 0;$i < count($searchcategs);$i++) {
$sql = $sql . $searchcategs[$i];
$sql = $sql . " = ";
$sql = $sql . $searchvals[$i];
$sql = $sql . " ";
}
An alternative version:
$sql = "SELECT TIT,VNEV,KNEV,NEME,MEGY,LCVAR,APOLG FROM TORZS LEFT OUTER JOIN VEGZETTSEG ON TORZS.ID = VEGZETTSEG.ID LEFT OUTER JOIN SZTAPASZTALAT ON TORZS.ID = SZTAPASZTALAT.ID LEFT OUTER JOIN SZAKTANFOLYAM ON TORZS.ID = SZAKTANFOLYAM.ID LEFT OUTER JOIN INFORM ON TORZS.ID = INFORM.ID WHERE ";
for ($i = 0;$i < count($searchcategs);$i++) {
$sql = $sql . $searchcategs[$i];
$sql = $sql . " = '";
$sql = $sql . $searchvals[$i];
$sql = $sql . "' ";
}
None of them seems to work, I got
SELECT TIT,VNEV,KNEV,NEME,MEGY,LCVAR,APOLG FROM TORZS LEFT OUTER JOIN VEGZETTSEG ON TORZS.ID = VEGZETTSEG.ID LEFT OUTER JOIN SZTAPASZTALAT ON TORZS.ID = SZTAPASZTALAT.ID LEFT OUTER JOIN SZAKTANFOLYAM ON TORZS.ID = SZAKTANFOLYAM.ID LEFT OUTER JOIN INFORM ON TORZS.ID = INFORM.ID WHERE
for the query even though the searchcateg and searchval arrays are existing and not empty.

Related

Getting information from multiple using MySQLI and be able to echo results

for the past few hours, I have been trying to find a simple method of while loop echoing information from multiple tables at once. I'd like to say I've not pulled all my hair out looking, but I have.
Here is one mysqli query to get the following fields from CUSTOMER
$tid = $_SESSION['user_id']; // "id" is 1 for example
$query = "SELECT * FROM `CUSTOMER` WHERE user_id = {$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['user_id'] . "<br><br>";
echo $row['c_fname'] . "<br>";
echo $row['c_sname'] . "<br>";
};
Here is another mysqli query to get the following fields from SALE
$query = "SELECT * FROM `SALE` WHERE user_id = {$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['s_date'] . "<br>";
echo $row['s_total'] . "<br>";
};
Could someone possibly show me how I can get both of these tables in one query so that echoing both tables information is possible at the same time instead of separately. I am not fussed how it is done, As long as it gets all from both tables for echoing purpose, that is good.
You can do it by using LEFT JOIN like this.
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
And this is your code.
$query = "SELECT * FROM `CUSTOMER` LEFT JOIN `SALE` ON `SALE`.user_id=`CUSTOMER`.user_id WHERE `SALE`.user_id={$tid}";
$results = mysqli_query($dbconnection, $query);
while ($row = mysqli_fetch_array($results)) {
echo $row['user_id'] . "<br><br>";
echo $row['c_fname'] . "<br>";
echo $row['c_sname'] . "<br>";
echo $row['s_date'] . "<br>";
echo $row['s_total'] . "<br>";
}
For more info read this,
https://www.w3schools.com/sql/sql_join_left.asp
I hope this helps.
EDITED
This is for joining 3 tables,
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
LEFT JOIN table3 ON table1.column_name = table3.column_name;
In your code.
SELECT * FROM `CUSTOMER`
LEFT JOIN `SALE` ON `CUSTOMER`.user_id = `SALE`.user_id
LEFT JOIN `PRODUCTS` ON `CUSTOMER`.user_id = `PRODUCTS`.user_id
WHERE `SALE`.user_id={$tid};
As variable.
$query = "SELECT * FROM `CUSTOMER` LEFT JOIN `SALE` ON `CUSTOMER`.user_id = `SALE`.user_id LEFT JOIN `PRODUCTS` ON `CUSTOMER`.user_id = `PRODUCTS`.user_id WHERE `SALE`.user_id={$tid}";
You can use the following code and will help u solve Ur problem
$query = "SELECT C.*,S.* FROM CUSTOMER C,SALES S
WHERE C.user_id={$tid}
and C.user_id=S.user_id;
while ($row = mysqli_fetch_array($results)) {
echo $row['C.user_id'] . "<br><br>";
echo $row['C.c_fname'] . "<br>";
echo $row['C.c_sname'] . "<br>";
echo $row['S.s_date'] . "<br>";
echo $row['S.s_total'] . "<br>";
};
You can simply join the tables to get your expected result as shown below.
$query = "SELECT c.user_id, c.c_fname, c.c_sname, s.s_date, s.s_total FROM `CUSTOMER` AS c INNER JOIN `SALE` AS s ON c.user_id = s.user_id WHERE c.user_id = {$tid}";
Joining 3 tables example
$query = "SELECT *
FROM `CUSTOMER` AS c
INNER JOIN `SALE` AS s ON c.user_id = s.user_id
INNER JOIN `PRODUCTS` AS p ON p.product_id = s.product_id
WHERE c.user_id = {$tid}";

Can I avoid this query in the While loop to speed up page loading?

My code is constructing a web page where I display multiple tables of data based on a machine ID (machine_id). The end user wants to be able to scroll through all tables on a single page versus having a single page for each individual machine.
Attached is a screenshot of what the page looks like (actually displays more than just two tables on the page). Can I modify my code so that I'm not making multiple queries in the While loop as the machine_id changes?
$db = new Database();
$result = mysqli_query($conn, "SELECT machine_id, machine_name, display_order FROM machines WHERE active_board = 'YES' ORDER BY display_order ASC");
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
$mach_id = $row["machine_id"];
$machine_name = $row["machine_name"];
$presspage = $row["machine_id"];
$machine_name = $row["machine_name"];
$daycount = '7';
$rows = $db -> select("SELECT a.machine_id, a.job_id, a.component, a.production_date, a.colors, a.hours, a.quantity, a.is_completed, a.artwork_image,
j.job_id, j.job_number, j.customer_id, j.job_name, j.total_cost, j.due_date, j.rework, j.pps, j.personalization, j.shipped, j.wave_csr,
c.customer_id, c.customer_name, c.board_color, c.text_color, u.full_name, p.component_name, d.delivery_method
FROM job_assignments a
LEFT JOIN jobs j ON a.job_id = j.job_id
LEFT JOIN customers c ON j.customer_id = c.customer_id
LEFT JOIN users u ON j.wave_csr = u.user_id
LEFT JOIN job_components p ON a.component = p.component_code
LEFT JOIN delivery_methods d ON j.method_id = d.method_id
WHERE a.machine_id = $presspage
ORDER BY j.job_number ASC");
echo "<tr>";
echo "<td>";
echo "<div id='dhtmlgoodies_dragDropContainer'>";
echo "<div id='dhtmlgoodies_mainContainer' align='center' vertical-align='middle'>";
echo "<h2>" . $machine_name . "</h2>";
for($x=0;$x<$daycount;$x++) {
$thehours = 0;
$theday = date('l M d', strtotime($date . " + {$x} day"));
$theday2 = date('Y-m-d', strtotime($date . " + {$x} day"));
$daycode = date('Md', strtotime($date . " + {$x} day"));
$totalhours = 0;
$pastdue_hours = 0;
$totalvalue = 0.00;
echo "<div style='width:180px; height:1500px; '>";
echo "<p>" . $theday . "</p>";
foreach ($rows as $row) {
$prod_date = $row["production_date"];
$shipped = $row["shipped"];
$hours = $row["hours"];
$value = $row["total_cost"];
$assignment_completed = 0;
$is_completed = $row["is_completed"];
if (($prod_date < date('Y-m-d')) AND ($shipped == 'NO') ) {
$prod_date = date('Y-m-d');
};
...
Screenshot example of web page.
You can join both the queries as
SELECT m.machine_id, m.machine_name, m.display_order, a.job_id, a.component, a.production_date, a.colors, a.hours, a.quantity, a.is_completed, a.artwork_image,
j.job_id, j.job_number, j.customer_id, j.job_name, j.total_cost, j.due_date, j.rework, j.pps, j.personalization, j.shipped, j.wave_csr,
c.customer_id, c.customer_name, c.board_color, c.text_color, u.full_name, p.component_name, d.delivery_method
FROM
machines m
LEFT JOIN job_assignments a USING (machine_id)
LEFT JOIN jobs j ON a.job_id = j.job_id
LEFT JOIN customers c ON j.customer_id = c.customer_id
LEFT JOIN users u ON j.wave_csr = u.user_id
LEFT JOIN job_components p ON a.component = p.component_code
LEFT JOIN delivery_methods d ON j.method_id = d.method_id
WHERE a.machine_id = $presspage and m.active_board = 'YES'
ORDER BY m.display_order, j.job_number;
You can first get all the machine ids from the first query into an array, then execute the second query for all machine ids in that array all at once. Below is a demonstrated example:
$db = new Database();
$result = mysqli_query($conn, "SELECT machine_id, machine_name, display_order FROM machines WHERE active_board = 'YES' ORDER BY display_order ASC");
$active_board_machine_ids = array();
while ($row = mysqli_fetch_assoc($result)) {
$active_board_machine_ids[] = $row["machine_id"];
}
$rows = $db -> select("SELECT a.machine_id, a.job_id, a.component, a.production_date, a.colors, a.hours, a.quantity, a.is_completed, a.artwork_image,
j.job_id, j.job_number, j.customer_id, j.job_name, j.total_cost, j.due_date, j.rework, j.pps, j.personalization, j.shipped, j.wave_csr,
c.customer_id, c.customer_name, c.board_color, c.text_color, u.full_name, p.component_name, d.delivery_method
FROM job_assignments a
LEFT JOIN jobs j ON a.job_id = j.job_id
LEFT JOIN customers c ON j.customer_id = c.customer_id
LEFT JOIN users u ON j.wave_csr = u.user_id
LEFT JOIN job_components p ON a.component = p.component_code
LEFT JOIN delivery_methods d ON j.method_id = d.method_id
WHERE a.machine_id IN ('".implode("','",$active_board_machine_ids)."')
ORDER BY j.job_number ASC");

inner join query don't return any things

I have a php code that use a mySQL query in it.
tables users and conversation and main_profile have true values to select after this query but query return nothing.
$sqlQuer =
"SELECT `conversation`.from,`conversation`.text, `main_profile`.nik_name, `users`.id
FROM `conversation`
INNER JOIN `users` ON(`users`.username = `conversation`.to )
INNER JOIN `main_profile` ON(`users`.id = `main_profile`.user_id)
WHERE `conversation`.to = '".$to."'
AND `conversation`.read = '0'";
$result = mysql_query( $sqlQuer) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row[0] . "#TEXT#" . $row[1]. "#TEXT#" . $row[2] . "#CON#";
$ids[] = $row['id'];
}
any Idea ?
Query was solved with this change that First INNER JOIN changed to LEFT JOIN and second changed to RIGHT JOIN.

MySQL left join not working with AS keyword

I like to use self explaining names for associative selects, and sometimes it's even mandatory to avoid duplicates, so I use the AS keyword alot. But it's giving me some trouble with left joins.
This works:
$sql = "SELECT *,
projects.id as projects_id
FROM projects";
$sql .= " LEFT JOIN".
" (SELECT
projectfiles.id as projectfiles_id,
projectfiles.fileID as projectfiles_fileID,
projectfiles.projectID as projectfiles_projectID
FROM projectfiles
) AS projectfiles".
" ON projects.id = projectfiles_projectID";
However now I end up with useless data from projects, because it also picks up the fields userID and name, which I don't need. It's also picking up the id twice.
So I tried changing it to;
$sql = "SELECT
projects.id as projects_id
FROM projects";
With the ON line becoming
" ON projects_id = projectfiles_projectID";
But that gave the error Unknown column projects_id
So I tried
" ON projects.projects_id = projectfiles_projectID";
But still the same error
I then started experimenting, and tried (as a test)
$sql = "SELECT id,name,userID FROM projects";
$sql .= " LEFT JOIN".
" (SELECT
projectfiles.id as projectfiles_id,
projectfiles.fileID as projectfiles_fileID,
projectfiles.projectID as projectfiles_projectID
FROM projectfiles
) AS projectfiles".
" ON projects.id = projectfiles_projectID";
And to my surprise, the LEFT JOIN didn't seem to pick up anything at all.
Code:
$sql = "SELECT id,name,userID FROM projects";
$sql .= " LEFT JOIN".
" (SELECT
projectfiles.id as projectfiles_id,
projectfiles.fileID as projectfiles_fileID,
projectfiles.projectID as projectfiles_projectID
FROM projectfiles
) AS projectfiles".
" ON projects.id = projectfiles_projectID";
$res = mysql_query($sql);
if(!$res) die(mysql_error());
if(mysql_num_rows($res) > 0)
{
$rownum = 0;
while($row = mysql_fetch_assoc($res))
{
print_r($row);
echo "<br/><br/>";
$rownum++;
}
}
Output:
Which is weird because there is only one row in projects but 3 in projectfiles with that projectID... what am I doing wrong?
To select only from the projectfiles table:
$sql = "SELECT projectfiles.*,
projects.id as projects_id
FROM projects";
// rest of the code is the same
Update
$sql = "SELECT projectfiles.* FROM projects";
// rest of the code is the same
Use short form of the query:
$sql = "SELECT projects.id,projects.name,projects.userID FROM projects LEFT JOIN
projectfiles ON projects.id = projectfiles.projectID";
SELECT p.*, pf.id, pf.fileId
FROM projects p LEFT JOIN projectfiles pf
on p.id = pf.projectID
You can use "as" to do as you will then. No need for a subselect.
$sql = "SELECT p.id,p.name,p.userID FROM projects p";
$sql .= " LEFT JOIN".
" projectfiles pf ".
" ON p.id = p.projectID";
$sql = "SELECT prj.id as prjId,
prj.name as prjName,
prj.userID as prjUid,
pf.id as pfId,
pf.fileID as pfFileId,
pf.projectID as pfProjecId
FROM projects as prj
LEFT JOIN projectfiles AS pf
ON prj.id = pf.projectID";

Building mysqli queries?

say if I have the query select users.user_id, users.fname, users.lname, bios.bio, groups.groupid from users LEFT JOIN bios on users.user_id = bios.userid then I want to add another table on a condition then add a where statement at the end. The problem is because when I bind the param it said 'number of variables doesn't match the number of variables in the prepare statement'. How would I solve this? Cheers. Example:
$info = "select users.user_id, users.fname, users.lname, bios.bio, groups.groupid from users LEFT JOIN bios on users.user_id = bios.userid";
$content = $members->prepare($info);
if ($_GET['where'] == 'requests') $info .= "LEFT JOIN requests on users.user_id = requests.receiver";
else if ($_GET['where'] == 'referrals') $info .= "LEFT JOIN referrals on users.user_id = referrals.receiver";
$info .= "where users.user_id = ?";
$content->bind_param('s', $_SESSION['token'][1]);
$content->execute();
You're changing the SQL string after preparing it. Don't do that. Do it like this instead:
$info = "select users.user_id, users.fname, users.lname, bios.bio, groups.groupid from users LEFT JOIN bios on users.user_id = bios.userid";
if ($_GET['where'] == 'requests') $info .= " LEFT JOIN requests on users.user_id = requests.receiver";
else if ($_GET['where'] == 'referrals') $info .= " LEFT JOIN referrals on users.user_id = requests.receiver";
$info .= " where users.user_id = ?";
$content = $members->prepare($info);
$content->bind_param('s', $_SESSION['token'][1]);
$content->execute();
Edit: Also, make sure your SQL fragments are separated with spaces where necessary; the .= operator doesn't automatically add a space for you.

Categories