Cheers,
I want to concat multiple rows to one column
Right now, my output is
CaseID Name Number Register date filename Actions
2 John Doe 3/2020 2020-01-20 test1.pdf delete
2 John Doe 3/2020 2020-01-20 test2.pdf delete
3 Jane Doe 5/2020 2020-01-20 test3.pdf delete
I want something like this:
CaseID Name Number Register date filename Actions
2 John Doe 3/2020 2020-01-20 test1.pdf delete
test2.pdf
3 Jane Doe 5/2020 2020-01-20 test3.pdf delete
All-day I have tried different SQL statements, but nothing works.
I'm stuck, I have no idea how to resolve it because I need to use LEFT JOIN for 2 tables:
$sql = "SELECT * FROM files as f
LEFT JOIN cases AS c on f.id_case_f = c.id_case
LEFT JOIN customers as cs on c.id_customer = cs.id_cust
WHERE case_number LIKE '%$case_number%'";
$result = $db -> query($sql);
I have tried with GROUP_CONCAT
I have used the statement below, but it doesn't work.
<?php
$db = mysqli_connect("localhost", "root", "", "testdb");
if ($db -> connect_error){
if($_REQUEST['submit']){
$case_number = $_POST['case_number'];
if(empty($case_number)){
$make = '<h4>You must type a word to search!</h4>';
}else{
$make = '<h4></h4>';
$sql = "SELECT id_case_f, GROUP_CONCAT(filename SEPARATOR ', ') FROM files
LEFT JOIN cases AS c on f.id_case_f = c.id_case
LEFT JOIN customers as cs on c.id_customer = cs.id_cust
WHERE case_number LIKE '%$case_number%'
GROUP BY id_case_f;";
$result = $db -> query($sql);
if($make = mysqli_num_rows($result) > 0)
{ echo '<table>
<tr><th>CaseID</th>
<th>Name </th>
<th>Number </th>
<th>Register date</th>
<th>filename</th>
<th>Actions</th></tr>';
while($row = mysqli_fetch_assoc($result))
{
echo "<tr><td>". $row["id_case"] ." </td><td>". $row["name"] . " </td>
<td>". $row["number"] ."</td> <td> " . $row["register_date"] ." </td>
<td> ". $row["filename"] ." </td><td><a href=#>delete</a></td></tr> ";
}
echo "</table>";
}
else
{
echo'<table "><tr><th>Try again! </th></tr></table>';
print ($make);
}
mysqli_free_result($result);
mysqli_close($db);
}
}
?>
Also, I have used a loooot of other combinations, but unfortunately, nothing worked. :(
If it is necessary I can add the entire PHP code, but this issue is regarding the select statement
Can someone help me with this?
Thank you
LE:
Errors:
Notice: Undefined index: id_case in /// on line 196
Notice: Undefined index: name
Notice: Undefined index: number
Notice: Undefined index: register_date
Notice: Undefined index: filename
SQL GROUP_CONCAT with LEFT JOIN to multiple relative rows
You can try with multiple SELECT statements.
Should work.
Also try to use WHERE EXISTS - https://www.w3schools.com/sql/sql_exists.asp
Related
I have the following Mysql query:
$sql = "select r.brand AS brand, r.name AS name, r.cost AS cost, e.price AS price, d.shipping as shipping
FROM tab.rawproduct r
INNER JOIN price e ON r.housecode=e.housecode
INNER JOIN product d ON e.productid=d.productid
WHERE r.housecode='$housecode'";
The houscode is assigned to a variable which is then passed to the sql statement:
<label>Housecode:</label><input class="boxes" type="text" name="housecode" value="<?php echo $housecode; ?>"><br />
$housecode = $_POST['housecode'];
Housecode is submitted through a form with action set to $_SERVER[PHP_SELF]
I am trying to iterate over the results with PHP with the following:
$result = $con->query($sql);
if ($result->num_rows >0) {
while($row = mysqli_fetch_array($result)) {
$brand = $row['brand'];
$housecode = $row['housecode'];
$name = $row['name'];
$cost = $row['cost'];
$salesprice = $row['price'];
$shipraw = $row['shipping'];
}
} else {
echo "0 Results";
}
$con->close();
Nothing is getting returned when a user submits a housecode and the "0 Results" is echoed.
I have looked into this problem and read Lucas Knuth's post:
If two or more columns of the result have the same field names, the
last column will take precedence. To access the other column(s) of the
same name, you must use the numeric index of the column or make an
alias for the column. For aliased columns, you cannot access the
contents with the original column name. So, you can either use an AS
in your SQL-query to set other names for the doubled rows or use the
numbered indexes to access them.
So I have used the AS keyword in the above query but I still don't get any results. I have also tried changing to mysqli_fetch_row($result) and tried to assign the $row[0], 1 ... etc instead. Again no luck.
When I run Apache error_log I get the following:
Trying to get property of non-object on line 34. On line 34 and 35 I have:
if ($result->num_rows >0) {
while($row = mysqli_fetch_array($result)) {
Any help would be much appreciated.
Cheers
I have figured out the answer for myself.
The problem was that I was selecting just one database, ie tab.rawproduct BUT tables price e and procduct d are from a totally different database.
So the sql query should have been this:
$sql = "SELECT r.brand, r.name, r.cost, e.price, d.shipping FROM
tab.rawproduct r
INNER JOIN t1.price e on r.housecode=e.housecode
INNER JOIN t1.product d on e.productid=d.productid
WHERE r.housecode = '$housecode' ";
If found the error by checking the mysqli->errno:
if(!$result = $mysqli->query($sql)) {
echo "Error: Our query failed to execute and here is why: \n";
echo "Query: " . $sql . "\n";
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
Hopefully this may help someone else facing the same problem.
Thanks for all your comments and help.
I reproduced your example and I found a bug in your select query: you're missing the r.housecode.
$sql = "select r.brand AS brand, r.name AS name, r.cost AS cost, e.price AS price, d.shipping as shipping, r.housecode AS housecode
FROM tab.rawproduct r
INNER JOIN price e ON r.housecode=e.housecode
INNER JOIN product d ON e.productid=d.productid
WHERE r.housecode='$housecode'";
Check if the cross references match in your tables, because in my examples the rows are correctly returned
table price:
housecode productid price
HT0008 4 3400
HT0008 5 5400
table product:
shipping productid
64 4
78 5
table rawproduct:
brand name cost housecode
Cani bellaaa 63824 HT0008
I have two tables and i want to echo the total call count once each user logins:
Login
Firstname | Lastname | Login ID
------------------------------
Tyler | Durden | 3
Call Count
Name | Call Count | Open | GrandTotal
------------------------------
Tyler Durden| 100 | 33 | 133
i tried:
<?php
$result = mysqli_query($mysqli, "SELECT * FROM csvdata WHERE Name=".$_SESSION['firstname']. ' ' .$_SESSION['lastname']." ");
while($res = mysqli_fetch_array( $result )) {
echo $res['Open'].' Open Calls';
echo $res['GrandTotal'].' Grand Total Calls';
}
mysqli_close($mysqli);
?>
But its not working, i think i have to join the the two tables to get it to work. What do you think?
Assuming your Call Count table is actually called csvdata, you'll want to format your SQL request string a bit by adding single quotes around the WHERE name = part.
<?php
$result = mysqli_query($mysqli, "SELECT * FROM csvdata WHERE Name='".$_SESSION['firstname']. ' ' .$_SESSION['lastname']."' ");
while($res = mysqli_fetch_array( $result )) {
echo $res['Call Count'].' Call Count';
echo $res['Open'].' Open Calls';
echo $res['GrandTotal'].' Grand Total Calls';
}
mysqli_close($mysqli);
?>
Good practice would require that you use primary keys to facilitate joins between tables and make sure two users with the same name can be differenciated.
In that case you may want to consider replacing the Name column in your Call Count table for your loginID. This way you could get your name from the Login table (as shown below). Also, as bad as it is to have duplicated data like your user's name in both tables, you do not need your GrandTotal column since you can easily get the sum of CallCount and Open to get the exact same number. In the end, your query should look more like this (assuming your tables are called Login and CallCount).
<?php
$result = mysqli_query($mysqli, "SELECT l.FirstName, l.LastName, cc.CallCount, cc.Open, (cc.CallCount + cc.Open) AS GrandTotal FROM Login AS l JOIN CallCount AS cc ON l.LoginID = cc.LoginID WHERE l.FirstName LIKE \"".$_SESSION['firstname']."\" AND l.LastName LIKE \"".$_SESSION['lastname']."\"");
// ...
?>
I'm trying to figure out the following. In the beginning I want to check if a member is in groups 11, 43 or 1.
I have the following tables with columns:
table members (member_id, name, group)
334 Ronald 43
table content (member_id, value)
334 Gold
I'm looking for a query which displays the name FROM members and value FROM content, joined with member_id and end result something like
Ronald Gold
If the user is not in the groups I have set, he/she will not be displayed.
The following is what i have managed to do
$sql = 'SELECT * FROM members m INNER JOIN content p ON m.member_id = p.member_id ';
$retval = mysql_query( $sql, $conn );
and
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo $row['member_id']. " " .$row['value'];
echo "<br>";
}
will output 334 Gold.
I just need to check the group in the beginning and replace member_id with name in the final output. Any help?
Just adjust your mysql query:
$sql = 'SELECT m.name, p.value FROM members m JOIN content p ON m.member_id = p.member_id WHERE m.group = 1 OR m.group = 11 OR m.group = 43;
then
echo $row['name']. " " .$row['value'];
Also you should be using mysqli_query() or PDO::query() since mysql_query() is deprecated. Reference
When you're echoing the results if you change echo $row['member_id'] to echo $row['name'] you will get the member's name.
Returning $row['group'] will tell you which group the member is in.
Your SQL should return following construct for each row
(member_id, name, group, value)
to filter out members not in desired groups modify your query
$sql = 'SELECT * FROM members m INNER JOIN content p ON m.member_id = p.member_id WHERE m.group IN (11,43,1) ';
Side note:
Consider using PDO or mysqli_* instead of mysql_* as mysql_* is deprecated and gone in PHP7
This one is working fine #1 but when I try to relate other tables on the second one, it gives an error
Notice: Undefined index: recipe.id in C:\xampp\htdocs\hyukies\public\samples.php on line 30
Notice: Undefined index: recipe.ingredientid in C:\xampp\htdocs\hyukies\public\samples.php on line 31
RecipeID:
IngredientID:
Notice: Undefined index: recipe.id in C:\xampp\htdocs\hyukies\public\samples.php on line 30
Notice: Undefined index: recipe.ingredientid in C:\xampp\htdocs\hyukies\public\samples.php on line 31
RecipeID:
IngredientID:
Notice: Undefined index: recipe.id in C:\xampp\htdocs\hyukies\public\samples.php on line 30
Notice: Undefined index: recipe.ingredientid in C:\xampp\htdocs\hyukies\public\samples.php on line 31
RecipeID:
IngredientID:
<?php
$sql = mysqli_query($connection, "SELECT id, location FROM location");
$userinfo = array();
while ($row_user = mysqli_fetch_assoc($sql))
$userinfo[] = $row_user;
foreach ($userinfo as $user) {
echo "ID: {$user['id']}<br />"
. "Location: {$user['location']}<br /><br />";
}
?>
This one is not working error problem please help......
<?php
$sql_2 = mysqli_query($connection, "SELECT recipe.id, recipe.ingredientid, ingredients.id, ingredients.quantity, ingredients.`name` FROM recipe INNER JOIN ingredients ON ingredients.id = recipe.ingredientid");
$userinfo_2 = array();
while ($row_user_2 = mysqli_fetch_assoc($sql_2))
$userinfo_2[] = $row_user_2;
foreach ($userinfo_2 as $user_2) {
echo "RecipeID: {$user_2['recipe.id']}<br />"
. "IngredientID: {$user_2['recipe.ingredientid']}<br /><br />";
}
?>
Remove the back ticks from 'name' in your query
$sql_2 = mysqli_query($connection, "SELECT recipe.id, recipe.ingredientid, ingredients.id, ingredients.quantity, ingredients.`name` FROM recipe INNER JOIN ingredients ON ingredients.id = recipe.ingredientid");
Should be
$sql_2 = mysqli_query($connection, "SELECT recipe.id, recipe.ingredientid, ingredients.id, ingredients.quantity, ingredients.name FROM recipe INNER JOIN ingredients ON ingredients.id = recipe.ingredientid");
Also, remove 'recipe' from $user_2['recipe.id']. It should be $user2['id'], but it won't be clear which id you are getting. To selected them independently you can use 'AS' in your query to give them a unique identifier.
SELECT recipe.id AS id1, ingedients.id AS id2
The keys in the associative array just contain the column names, not the table names. So it should be:
echo "RecipeID: {$user_2['id']}<br />"
. "IngredientID: {$user_2['ingredientid']}<br /><br />";
The table names are not included in the result set, so the columns are only named id, ingredientid etc. You really should use as for naming them, like recipe.id as recipeid. There is no warning about there being to id fields and PHP will map them together.
You don't really need both id fields anyway, since you also have the ingredientid, but most probably you will get ingredients.id in the id field also since it's latter.
So update your query to something like
SELECT recipe.id AS recipeid,
recipe.ingredientid,
ingredients.quantity,
ingredients.name
FROM recipe
INNER JOIN ingredients ON ingredients.id = recipe.ingredientid
and then use recipeid to get the recipe.id. This will always be better, since it's clear what id you are getting.
I've try a lot of ways to get this table print as good as it should but I failed.
I know it's simple thing so I hope you help me with it.
Here's my code:
<?php
include('../connect.php');
$id=$_SESSION['login_user'];
$sql = "Select CourseName , Studentname from course p natural join student t";
$rs_result = mysql_query ($sql, $connection);
echo "<center>";
echo "<table>";
echo "<tr> <th>Course Name</th> <th> Students Name</th> </tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $rs_result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['CourseName'] . '</td>';
echo "<td rowspan=''> $row[Studentname] </td> ";
echo "</tr>";
}
echo "</table>";
echo "</center>";
?>
I want to be something like this
Course | Name | Student name |
Math101 | john, Mike |
...
Also, is the JOIN query between the two tables CORRECT or not?
The two tables are:
Course ( Course name - Course id )
Student ( Student name - Course id )
Try this query
$sql ="SELECT cor.CourseName,GROUP_CONCAT(stu.StudentName) AS StudentName
FROM course AS cor
LEFT JOIN student AS stu
ON stu.CourseId = cor.CourseId";
And change the the line in below
echo "<td rowspan=''>" . $row['Studentname'] . "</td> ";
This line:
echo "<td rowspan=''> $row[Studentname] </td> ";
You are accessing the array element improperly. Studentname should have single quotes around it like such:
echo "<td rowspan=''>" . $row['Studentname'] . "</td> ";
Also, in your query, this may work better:
$sql = "SELECT c.CourseName, s.StudentName
FROM course AS c
INNER JOIN student AS s
ON s.CourseId = c.CourseId";
Please use below format
SELECT CourseName , Studentname
FROM course
INNER JOIN student
ON course.id = student.id
Thanks
The problem is with Your rowspan attribute - You need to provide it with the exact number of rows to span through. Anyway, I think it is the collspan attribute You want to use, so e.g.
echo "<td collspan='2'> {$row['Studentname']} </td> ";
which means it will span through 2 columns, thus stundet's name will be both under the Name and Student name columns.
Is this what You were expecting?
Also I highly recommend not to use mysql_ functions but learn how to use mysqli or at least PDO.
I'm under the impression that you wanted to display a comma-separated list of names of all the students that attend each course, for each separate CourseName. In this case, you could change your SQL query to something like this:
SELECT CourseName, GROUP_CONCAT(Studentname SEPARATOR ', ') as names
FROM Course p NATURAL JOIN Student t
GROUP BY CourseName;
Hello please take a look of this answer. Dynamic rowspan while fetching records from database
I think it might be helpfull.