Could i merge this two select query in one? - php

My aim is to show/display in the right part questions of the survey (from a table of my database) and in the left part answers from customers (from another table in my database) in the right part. So my question is : How to merge this two select query ? I did some research but with php it's kind of tricky to understand and I'm still new on php too.
Any help or advices are welcome .
Best Regards A.V.
<?php
include("bdconnect_Foredeck.php");
$link=mysqli_connect($host,$login,$pass,$dbname);
if(isset($_POST["bouton55"])){
$link = mysqli_connect($host,$login,$pass,$dbname);
$id = $_REQUEST["Zoubi"];
$ClientRef =$_REQUEST["KGB"];
$rechercheq = "SELECT Qref,Ref,Question FROM questionnaire WHERE Qref ='$id' ";
$recherche= "SELECT choix,commentaire FROM reponse WHERE RefQ ='$id' and ref_Client ='$ClientRef'";
mysqli_query($link,$recherche);
mysqli_query($link,$rechercheq);
$result1=mysqli_query($link,$rechercheq);
$result= mysqli_query($link,$recherche);
while($row = mysqli_fetch_assoc($result,$result1)){
$Ref =$row["Ref"];
$Question =$row["Question"];
$Choix =$row["choix"];
$Commentara =$row["commentaire"];
echo" <tr bgcolor=\"white\">
<td> $id </td>
<td> $Ref </td>
<td>$Question </td>
<td>$Choix </td>
<td>$Commentara </td>
</tr>";
}
}
?>

You could use a JOIN
SELECT a.Qref, a.Ref,a.Question , b.choix, b.commentaire
FROM questionnaire as a
LEFT JOIN reponse as b ON a.RefQ = b.RefQ
WHERE a.Qref ='$id'
AND b.ref_Client ='$ClientRef'
if you have duplicated rows .. then you can use distinct
SELECT DISTINCT a.Qref, a.Ref,a.Question , b.choix, b.commentaire
FROM questionnaire as a
LEFT JOIN reponse as b ON a.RefQ = b.RefQ
WHERE a.Qref ='$id'
AND b.ref_Client ='$ClientRef'
otherwise you logic don't permit a single query

Related

MAX and COUNT sql query

I need to know how to use MAX() and COUNT() query to display the "fiser" table entries that contain the primary "codp" key that comes from the "products" table, depending on a previously selected period?
Table products : codp, denp ;
Table orders: codc,codp ;
Table returns : codr, datar, codc, codp
<?php
if(isset($_POST['add'])){
$sql = "SELECT p.denp, a.datar,MAX(p.codp)
FROM ( SELECT COUNT(p.codp) FROM products p ) products p
INNER JOIN orders o ON p.codp=o.codp
INNER JOIN returns r ON o.codc=r.codc
WHERE r.datar>=STR_TO_DATE('".$_POST['d1']."','%Y-%m-%d')
AND r.datar<=STR_TO_DATE('".$_POST['d2']."','%Y-%m-%d') ";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
echo "
<table border=1 >
<tr>
<td><p> ".$row['codp']." </p></td>
<td><p> ".$row['denp']." </p></td>
<td><p> " .$row['codr']." </p></td>
<td><p> " .$row['datar']." </p></td>
<td><p> " .$row['codc']." </p></td>
</tr> </table> ";
}
} else {
echo " No results!" ;
}
}
?>
You should use group by for codp and the join the related result eg:
$sql = "SELECT p.denp, r.datar,MAX(p.cnt_codp)
FROM (
SELECT codp, COUNT(*) as cnt_codp FROM products
group by codp
) products p
INNER JOIN orders o ON p.codp=o.codp
INNER JOIN returns r ON o.codc=r.codc
WHERE r.datar>=STR_TO_DATE('".$_POST['d1']."','%Y-%m-%d')
AND r.datar<=STR_TO_DATE('".$_POST['d2']."','%Y-%m-%d')
GROUP BY p.denp, r.datar ";
and you should check for your db driver for param bindig instead of use of php var in sql (you are at risk for sql injection)
and you should also use a group by for not aggreated column or reeval the question if you need the values related to max result (the use of aggregation function without a proper group by columns for not aggreagated is depreacted in sql ai the most recent version of mysql is not allowed)

How to echo second column with only the primary key - SQL/PHP

I'm trying to create a fixture list for a football competition currently, and i have been stuck with trying to display something like "team1name V team2name".The tables that i am trying to pull the data from are:
Team
teamID
teamname
Fixtures
hometeam
awayteam
The sql query I have written up is:
$sql = "SELECT homeTeam, awayTeam, roundID, teamID, teamName, logo, groundName, abbreviatedName, matchDate, matchTime, venue
FROM fixtures
INNER JOIN team ON fixtures.homeTeam = team.teamID
INNER JOIN ground ON ground.groundID = team.groundID";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error());
and the PHP code which i have been using to display this data is:
<?php
while ($row = mysqli_fetch_array($results))
{
?>
<tr>
<td><?php echo $row ["teamName"]?></td>
<td> V </td>
<td><?php echo $row ["teamName"]></td>
</tr>
<?php
}
mysqli_close($conn);
?>
I understand i am calling teamname twice and hence why i am getting the same name displayed, but i am unsure as to how to get my code to differentiate the two IDs and names. Any help would be greatly appreciated
This is just a SQL problem. You need to join team twice, once for home team and once for away team.
SELECT homeTeamID, awayTeamID, homeTeam.teamID homeTeamID,
awayTeam.teamID awayTeamID, homeTeam.teamName homeTeamName,
awayTeam.teamName awayTeamName
FROM fixtures
INNER JOIN team homeTeam ON fixtures.homeTeam = homeTeam.teamID
INNER JOIN team awayTeam ON fixtures.awayTeam = awayTeam.teamID
INNER JOIN ground ON ground.groundID = team.groundID
By naming the selects, you can use the separately in your PHP code.
<?php echo $row['homeTeamName']; ?> v <?php echo $row['awayTeamName']; ?>

MySQL what kind of query i need to use

i'm making a panel where i can manage my users, i want to show username, email, and i want to show how much orders the placed. In my database i have 2 tabels 1 users, 1 orders. I'm saving the username from the user in the order table so i know wich user has bought it.
But, i want to write a panel with a overview from my users in a foreach loop. I have the loop for username, email how i can add the amount of order to it.
<?php
$model = $connection->createCommand('SELECT * FROM user');
$adminAccounts = $model->queryAll();
foreach($adminAccounts as $results){
$accounts['id'] = $account_id;
$accounts['username'] = $results['username'];
$accounts['email'] = $results['email'];
$accounts['rest'] = $results;
echo "
<tr>
<td>
<p>" . $newValidation->safeEcho($accounts['username']) ." </p>
</td>
<td>
<p>" . $newValidation->safeEcho($accounts['email'])." </p>
</td>
</tr>
";
}
Lets say my table look likes this
<username> <email>
Now i want it to look like this
<username> <email> <total orders>
I was thinking i should use a inner join but how i can do that ?
Greetz
I think you can change your query to:
SELECT user.*, t.cnt FROM user JOIN (SELECT gebruikersnaam, COUNT(*) AS cnt FROM orders GROUP BY gebruikersnaam) t ON user.username = t.gebruikersnaam
With this query you can get users orders but you will skip users without orders, so to get them you can do LEFT JOIN:
SELECT user.*, t.cnt FROM user LEFT JOIN (SELECT gebruikersnaam, COUNT(*) AS cnt FROM orders GROUP BY gebruikersnaam) t ON user.username = t.gebruikersnaam
I suggested that the field for users in table orders is username. And in your question you point that the table is users but in your query table is user. I am using user. If you change your current query with this one you can add in your code:
foreach($adminAccounts as $results){
$accounts['id'] = $account_id;
$accounts['username'] = $results['username'];
$accounts['email'] = $results['email'];
$accounts['total_orders'] = ($results['cnt'] == NULL) ? 0 : $results['cnt']; // orders per user
$accounts['rest'] = $results;
echo "
<tr>
<td>
<p>" . $newValidation->safeEcho($accounts['username']) ." </p>
</td>
<td>
<p>" . $newValidation->safeEcho($accounts['email'])." </p>
</td>
<td>
<p>" . $newValidation->safeEcho($accounts['total_orders'])." </p>
</td>
</tr>
";
}

how to select data from 2 table of databace in mysql....?

I have 2 table of date , student_info and student_payment in my databace...
in student_info i have:
id, student_id,student_mail,student_pass,student_name,...
and in student_payment have:
id,student_id,student_payment_id,student_payment_date,...
so my problem is here, i wanna select student_name where student_id form student_info but i have problem and mysql give my an error:
$db->connect();
$sql = "SELECT * FROM `student_payment`";
$rows = $db->fetch_all_array($sql);
$student_id = $rows['student_id'];
$sql2 = "SELECT * FROM `student_info` WHERE student_id=$student_id";
$rows2 = $db->fetch_all_array($sql2);
$db->close();
foreach($rows as $record ){
// i wanna to use student_name in first line
echo "\n<tr>
<td>$record[student_id]</td>
<td dir=\"ltr\">$record[student_payment]</td>
<td dir=\"ltr\">$record[student_payment_id]</td>
<td dir=\"ltr\">$record[student_payment_bank]</td>
<td dir=\"ltr\">$record[student_payment_type]</td>
<td dir=\"ltr\">$record[student_payment_date]</td>
<td dir=\"ltr\"></td>
</tr>\n";
}
but i dont know how to connect student_id and student_name and use in foreach because i have 2 rows of data.
(i'm a beginner in PHP / MySql)
Instead of querying database twice, you can instead join the tables to get the rows you want. Try to execute the query below in PhpMyAdmin or directly on MySQL Browser.
SELECT a.*, b.*
FROM student_info a
INNER JOIN student_payment b
ON a.student_ID = b.student_ID
-- WHERE ...if you have extra conditions...
ORDER BY b.student_payment_date DESC
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
It is possible to fix it with INNER JOIN, you can join 2 tables and use both values from 1 query.
http://www.w3schools.com/sql/sql_join_inner.asp
Or you can use the OOP way, not sure if that is what you need.
Make 2 objects from the 2 query's and put them in a foreach.
try this
$sql2 = " SELECT * FROM `student_info` WHERE student_id= '$student_id' ";
try this
$sql2 = "SELECT * FROM `student_info` WHERE student_id IN ($student_id)";
foreach($rows as $record ){
// i wanna to use student_name in first line
echo "\n<tr>
<td>$record[student_id]</td>
<td dir=\"ltr\">".$record['student_payment']."</td>
<td dir=\"ltr\">".$record['student_payment_id']."</td>
<td dir=\"ltr\">".$record['student_payment_bank']."</td>
<td dir=\"ltr\">".$record['student_payment_type']."</td>
<td dir=\"ltr\">".$record['student_payment_date']."</td>
<td dir=\"ltr\"></td>
</tr>\n";
}
Use Mahmoud Gamal code
But always select the needed columns only not all because
In future number of columns in table may increase which may decrease the performance of your application.
Also it may contain some important information not to be leaked.
It seems like you want a report of all payments made. The student name is to be displayed with the payment information. The results will probably have more than one payment per student.
This result is ordered by student name, and then payment date (most recent first)
SELECT s.student_name, sp.*
FROM student_payment sp
INNER JOIN student_info s ON s.student_ID=sp.student_ID
ORDER BY s.student_name ASC, sp.student_payment_date DESC
try to join the table and use single query instead of two -
$sql = "SELECT * FROM student_info, student_payment
WHERE student_info.student_id=student_payment.student_id"

While loop Repeats infinitely

I have a while loop that populates a dropdown box with values from a mysql table. There are only two matching records and it is repeating them over and over. How do i only display each record once?:
$query = "SELECT * FROM members, sportevents, dates, results, event, userlogin ".
"INNER JOIN members AS m ON userlogin.id = m.id " .
"WHERE userlogin.username = '$un' " .
"AND sportevents.id = members.id " .
"AND sportevents.event_id = event.id " .
"AND sportevents.date_id = dates.id " .
"AND sportevents.result_id = results.id";
echo "<form method='POST' action='display.php'>";
echo "Please Select Your Event<br />";
echo "<select name='event'>";
echo "<option>Select Your Event</option>";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results)) {
echo "<option>";
echo $row['eventname'];
echo "</option>";
}
echo "</select>";
echo "<input type='submit' value='Go'>";
echo "</form>";
Have you tried running that query manually in the mysql monitor? Nothing in your code would produce an infinite loop, so most likely your query is not doing joins as you expect and is doing a cross-product type thing and creating "duplicate" records.
In particular, your query looks very suspect - you're using the lazy "from multiple tables" approach, instead of explicitly specifying join types, and you're using the members table twice (FROM members ... and INNER JOIN members). You don't specify a relationship between the original members table and the joined/aliased m one, so most likely you're doing a members * members cross-product fetch.
give that you seem to be fetching only an event name for your dropdown list, you can try eliminating the unused tables - ditch dates and results. This will simplify things considerable, then (guessing) you can reduce the query to:
SELECT event.id, event.eventname
FROM event
INNER JOIN sportevents ON event.id = sportevents.event_id
INNER JOIN members ON sportevents.id = members.id
INNER JOIN userlogins ON members.id = userlogins.id
WHERE userlogins.username = '$un'
I don't know if the members/userlogins join is necessary - it seems to just feed sportevents.id through to members, but without knowing your DB's schema, I've tried to recreate your original query as best as possible.
You could always try changing the SELECT statement to a SELECT DISTINCT statement. That'll prevent duplicates of the selected fields.
Either that or reading all the results before displaying them, then de-duping them with something like array_unique().
Checkout My Example. It will be helped for you to understand. Because this code 100% working for me. Study it and get a solution.
And You Should Use DISTINCT keyword and GROUP BY Keyword. That's the Main Thing to prevent repeating values.
<?php
$gtid = $_GET['idvc'];
if(isset($_GET['idvc']))
{
$sql = mysql_query("SELECT DISTINCT gallery_types.gt_id, gallery_types_category.gtc_id, gallery_types_category.gt_category, gallery_types_category.gtc_image FROM gallery_types, gallery_types_category WHERE $_GET[idvc]=gtid GROUP BY gt_category");
mysql_select_db($database,$con);
while($row = mysql_fetch_array($sql))
{?>
<table>
<tr>
<td width="100px"><?php echo $row['gt_id'] ?></td>
<td width="100px"><?php echo $row['gtc_id'] ?></td>
<td width="300px"><?php echo $row['gt_category'] ?></td>
<td width="150px">
<a href='view_all_images.php?idvai=<?php echo $row[gtc_id] ?>' target='_blank'>
<img width='50' height='50' src='<?php echo $row[gtc_image] ?>' />
</a>
</td>
</tr>
</table>
<?php
}
}
?>
Better Understand, Follow Following Method,
$sql = mysql_query("SELECT DISTINCT table1.t1id, table2.t2id, table2.t2name FROM table1, table2 WHERE t1id=t2id GROUP BY t2name");

Categories