sql works on phpmyadmin but not on php script - php

I have 2 table names courses and institution.
Here is my query:
CREATE TEMPORARY TABLE
IF NOT EXISTS temp AS (SELECT course_name, ins_name
FROM courses
where course_name='ACCA') ;
select institution.ins_name, address, contact, website,
email from institution join temp on institution.ins_name = temp.ins_name
And here is my php script:
<?php
session_start();
include('db_connect.php');
$sql="CREATE TEMPORARY TABLE
IF NOT EXISTS temp AS (SELECT course_name, ins_name
FROM courses
where course_name='ACCA') ;
select institution.ins_name, address, contact, website, email from institution join temp on institution.ins_name = temp.ins_name";
$result= mysqli_query($conn, $sql) or die("MySQL error: " . mysqli_error($conn));
while ($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['ins_name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['contact'] . "</td>";
echo "<td>" . $row['website'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>"
?>
I can't figure out what the problem is. The error i get is:
MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select institution.ins_name, address, contact, website, email from institution j' at line 6
What am i doing wrong?

From Multiple Statements:
MySQL optionally allows having multiple statements in one statement
string. Sending multiple statements at once reduces client-server
round trips but requires special handling.
Multiple statements or multi queries must be executed with
mysqli_multi_query(). The individual statements of the statement
string are separated by semicolon. Then, all result sets returned by
the executed statements must be fetched.
Alternatively, just fire two queries.

Every query must be executed separately. create and select are two different queries so first you need to call mysqli_query for create and then mysqli_query for select

You need alias on each column :
select institution.ins_name, institution.address, institution.contact, institution.website, institution.email from institution join temp on institution.ins_name = temp.ins_name";

Related

using JOIN in mysqli only return result from one table

I'm currently trying to print the result of joining 2 tables using mysqli. but everytime i try to do it, it only return the result from one table while the table that it's joining doesn't return any result
below is the code that show the data into a table
foreach($db->showdata() as $x) {
if($x['role_id'] == 1 || $x['role_id'] == 2) continue;
$id = $x['user_id'];
echo "<tr>";
echo "<td>" . $x['user_id'] . "</td>";
echo "<td>" . $x['first_name'] ." ". $x['last_name']. "</td>";
echo "<td>" . $x['nilai_tugas'] . "</td>";
echo "<td>" . $x['nilai_uts'] . "</td>";
echo "<td>" . $x['nilai_uas'] . "</td>";
echo "</tr>";
}
while this one is the showdata() function it called
function showdata(){
$data = mysqli_query($this->db, "SELECT * FROM user LEFT OUTER JOIN grade ON(user.user_id = grade.user_id) IS NOT NULL;");
while($d = mysqli_fetch_array($data)){
$hasil[] = $d;
}
return $hasil;
}
The structure of the table is
User: user_id, first_name, last_name and other column that's irrelevant for this part
Grade: user_id, nilai_tugas, nilai_uts, nilai_uas
when I run the code it return
Notice: Undefined index: nilai_tugas
Notice: Undefined index: nilai_uts
Notice: Undefined index: nilai_uas
which is from the grade table, but the data from the user table do go through and show up in the page.
The page result
When I run the query in mysql it does return all the data I requested but it doesn't seem to return the data when in the function.
Thank you in advance.
Edit: I tried to move the select query into the same page and it work, it just don't work when I use return from function(which is mandatory).
Can you try be more explicit in selecting your columns?
mysqli_query($this->db, "SELECT user.columnname, grade.columnname FROM user LEFT OUTER JOIN grade ON(user.user_id = grade.user_id) IS NOT NULL;");
And are you sure the column in users is called user_id? Because the result set has the columnname studentID.
I don't fully know what happened, so I tried reinstalling xampp and it finally start working, the problem might be located in mysql config file(not the first time this happen to me).

PHP running Union All SQL Statement

im trying to combine two tables together, but whenever i run the program, this happens.
As you can see i've echoed out the sql statement. Here are my codes.
$queryc1 = "select sum(repeater),sum(membersigned) from sales UNION ALL select count(*) from approach;"; //DO INNERJOIN PRACTISE
$resultc1 = mysqli_query($dbconn,$queryc1);
echo "<table>
<tr>
<th>Repeater</th>
<th>Members</th>
<th>Approach</th>
</tr>";
while($row = mysqli_fetch_array($resultc1)) {
echo "<tr>";
echo "<td>" . $row['sum(repeater)'] . "</td>";
echo "<td>" . $row['sum(membersigned)'] . "</td>";
echo "<td>" . $row['count(*)'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo $queryc1;
I'd like to show count(*) as in the photo, as a third column to the genrated table.
You don't need UNION select here, instead you can use subquery:
select sum(repeater) as repeater_sum,
sum(membersigned) as membersigned_sum,
(select count(*) from approach) as approach_count
from sales;
and in PHP you use $row['repeater_sum'].. etc
When you union two or more queries together each query should have the same columns of data with same data type for example :
SELECT SUM(repeater),SUM(membersigned) FROM sales
UNION
SELECT Text1,Text2 FROM approach
Replace your query with this format

Very strange SQL error where data is not being pulled correctly

I have two pages that are very similar, but do slightly different things. However, both place data into a table called playerRegSeason.
Here is the SQL code I use on one page:
$sql2="INSERT INTO playerRegSeason
(playerID, year, teamID, gp, minutes, pts, oreb, dreb, reb,
asts, stl, blk, turnover, pf, fga, fgm, fta, ftm, tpa, tpm)
SELECT playerID, $year, '$teamID', $gp, $minutes, $pts, $oreb,
$dreb, $reb, $asts, $stl, $blk, $turnover, $pf, $fga, $fgm,
$fta, $ftm, $tpa, $tpm FROM players WHERE firstname='".$firstname."'
AND lastname='".$lastname."' AND firstseason='".$firstseason."'";
And here's the code for the other page:
$sql2="INSERT INTO playerRegSeason
(playerID, year, teamID, gp, minutes, pts, oreb, dreb, reb,
asts, stl, blk, turnover, pf, fga, fgm, fta, ftm, tpa, tpm)
VALUES ($playerID, $year, '$teamID', $gp, $minutes, $pts, $oreb,
$dreb, $reb, $asts, $stl, $blk, $turnover, $pf, $fga, $fgm,
$fta, $ftm, $tpa, $tpm)";
On both pages, when I look at the database, the data has been added and is in the proper format.
Now, is my problem. I have another page that displays the contents of the table. Here is the code that is not working:
$quer1 = "SELECT * FROM players p
INNER JOIN playerRegSeason pr ON p.playerID = pr.playerID
INNER JOIN teams t ON pr.teamID = t.teamID
WHERE p.firstname='$firstname' AND p.lastname='$lastname'";
$result1 = mysqli_query($con, $quer1);
while($row = mysqli_fetch_array($result1)) {
echo "<tr>";
echo "<td>" . $row['year'] . "</td>";
echo "<td>" . $row['location']." ". $row['name'] . "</td>";
echo "<td>" . $row['leag'] . "</td>";
echo "<td>" . $row['gp'] . "</td>";
echo "<td>" . $row['minutes'] . "</td>";
echo "<td>" . $row['pts'] . "</td>";
echo "<td>" . $row['oreb'] . "</td>";
echo "<td>" . $row['dreb'] . "</td>";
echo "<td>" . $row['reb'] . "</td>";
echo "<td>" . $row['asts'] . "</td>";
echo "<td>" . $row['stl'] . "</td>";
echo "<td>" . $row['blk'] . "</td>";
echo "<td>" . $row['turnover'] . "</td>";
echo "<td>" . $row['pf'] . "</td>";
echo "<td>" . $row['fga'] . "</td>";
echo "<td>" . $row['fgm'] . "</td>";
echo "<td>" . $row['fta'] . "</td>";
echo "<td>" . $row['ftm'] . "</td>";
echo "</tr>";
echo "</table>";
}
The weird thing is that any data entered from the first sql will not show up, but any data that was entered through the second sql statement will. Even though both entries are listed right next to each other in the db with the same playerID primary key.
You are doing two inner joins, you already confirmed one of them when you said that both entries have the same player ID, but do they also both have the same teamID?
If the first entry doesn't have a teamID that exists in the teams table, it won't be coming in through your query.
A quick way to check this is to change the 'INNER JOIN' on the teams table with an LEFT JOIN, if this gets you more records then your data has some teamID values that don't exist in the teams table.
In the second set of sql inserts you're always going to do an insert (assuming no errors with variables, etc.)
In the first set of sql, you're doing a select statement to perform the insert, specifically look at your where clause - if that clause eliminates all returned results, then no records will be inserted. If you run the statement:
SELECT *
-- input your expected values in place of the variables
FROM players WHERE firstname= ''
AND lastname='' AND firstseason='';
you'll likely see that nothing is being returned from this query, therefore nothing would be inserted in the first query.
Based on your comment it sounds like the issue (since it wasn't due to the first sql statement) would likely be due to the inner joins:
try your query as such:
SELECT * FROM players p
--INNER JOIN playerRegSeason pr ON p.playerID = pr.playerID
--INNER JOIN teams t ON pr.teamID = t.teamID
WHERE p.firstname='$firstname' AND p.lastname='$lastname
See if you're getting your expected value. If you are, uncomment the inner join on playerRegSeason, if still getting your expected row, uncomment the join on teams. The likely cause is that at least one of the tables you're joining on does not contain the record you're expecting, and therefore is not being returned by the query. (or as David suggested, change your inner joins to left joins for testing purposes)

Show multiple table rows in a table

I have 2 tables called 0_vrs_american and 0_vrs_europe, and I need to display the rows of these tables in a single html table. So I wrote this code:
<?php
$con=mysqli_connect("localhost","aaa","bbb","my_mk7vrlist");
$result = mysqli_query($con,"SELECT 0_vrs_american.*, 0_vrs_europe.* FROM 0_vrs_american, 0_vrs_europe ORDER BY `vrs` DESC LIMIT 0 , 200");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $x . "</td>";
echo "<td>" . $row['playername'] . "</td>";
echo "<td>" . $row['contactable'] . "</td>";
echo "<td>" . $row['vrs'] . "</td>";
echo "</tr>";
$x = $x+1;
}
mysqli_close($con);
?>
I am pretty new with MySQL and so I googled about this topic and I found a syntax like the one you can see above. By the way I have no results in my page because the table is empty.
So: I must display in a HTML table the content of both sql tables, and the rows must be sorted according with the vrs (number that goes from 50000 to 99000). How could I solve my problem?
An alternative to the above is to select all the rows from those two tables as an inner select, and then order by vrs in the returned result set.
SELECT *
FROM
(
SELECT * FROM 0_vrs_american
UNION
SELECT * FROM 0_vrs_europe
) AS a
ORDER BY vrs
at first U need to define $x before the loop
then use the query like this
$result = mysqli_query($con,"SELECT 0_vrs_american.*, 0_vrs_europe.* FROM 0_vrs_american, 0_vrs_europe ORDER BY `vrs` DESC LIMIT 0 , 200") or die (__LINE__." ".mysqli_error($con));
so you will see the error and the line of the query
i just add or die (__LINE__." ".mysqli_error($con))
Separate the 2 queries and their results
merge both results into an array
sort the array as needed
output the array (generate table rows)

Trying to order a 3 table JOIN by date desc, How to sort correctly?

Have 3 different mysql tables, my script queries the DB using JOINS to output the most recent results from each of the 3 tables. All works like it is supposed to but the way mysql databases allow for JOINS, the ORDER BY will order the results as you list the tables, resulting in the finished output not being ordered by date correctly, since the results are from 3 different MYSQL tables.
The results instead are ordered by date correctly only next to the other results form the same table. See the script and results below: (I am limit 1 for the output for simplicity)
$username = $_SESSION['username'];
$result = $mysqli->query("
SELECT
accounts.account_name,
cases.case_subject,
tasks.task_title,
accounts.accounts_date_last_edited,
cases.cases_date_last_edited,
tasks.tasks_date_last_edited
FROM
accounts,
cases,
tasks
WHERE
accounts.username = cases.username
AND cases.username = tasks.username
ORDER BY
accounts.accounts_date_last_edited DESC,
cases.cases_date_last_edited DESC,
tasks.tasks_date_last_edited DESC
LIMIT 1
");
if (!$result) { echo "Error Result5: " . $mysqli->error; } else {
echo "<table>";
echo "<tr><th>Item</th><th>Date</th></tr>";
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['account_name'] . "</td><br>";
echo "<td>" . $row['accounts_date_last_edited'] . "</td><br>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['case_subject'] . "</td><br>";
echo "<td>" . $row['cases_date_last_edited'] . "</td><br>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['task_title'] . "</td><br>";
echo "<td>" . $row['tasks_date_last_edited'] . "</td><br>";
echo "</tr>";
}
echo "</table>";
The Results are below: they will list 1 item from each table listed above. Again I am trying to sort by the date_last_edited regardless of which table the values are from.
Item Date
Shorley Homes 2013-11-02 04:02:34
Techical Testing Case Open 2013-11-03 07:17:36
Icons 2013-11-03 07:28:02
If I read correctly (and I'm not sure of that) your
...sort by the date_last_edited regardless of which table the values are from...
then you might want to use UNION instead of JOIN
SELECT account_name item, accounts_date_last_edited date
FROM accounts
UNION ALL
SELECT case_subject, cases_date_last_edited
FROM cases
UNION ALL
SELECT task_title, tasks_date_last_edited
FROM tasks
ORDER BY date DESC
Here is SQLFiddle demo

Categories