In my database I have a one-to-many table relationship where one parent can have many kids. The primary key is the parents email. I query to get the kids
$results1 = mysqli_query($con,"
SELECT directory.email
, dirKids.kname
, dirKids.kbirthday
FROM directory
JOIN dirKids
ON '$row[email]' = dirKids.parent
");
Then I loop through and echo the value to my html page
while($row1 = mysqli_fetch_array($results1)) {
if (!empty($row1["kname"])) {
echo "<tr><td>". $row1["kname"] ."</td><td>".
$row1["kbirthday"]."</td></tr>";
}
}
The problem I am having is that only one parent has kids in my database, but it will print the kids name and birthday 10 times because there are 10 people in my database. How can I get it to only print the child's name and birthday once?
My full code is listed below:
<?php
$con = mysqli_connect("localhost", "username", "password", "db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$results = mysqli_query($con,"SELECT directory.id, directory.fname, directory.lname, directory.address, directory.bdname, directory.birthday, directory.cell, directory.email, directory.sFName, directory.sBirthday, directory.sCell, directory.sEmail FROM directory ORDER BY lname") or die ("couldn't fetch query");
echo "<div class='accordion' id='accordion'>";
// output data of each row
while($row = mysqli_fetch_array($results)) {
$results1 = mysqli_query($con,"SELECT directory.email, dirKids.kname, dirKids.kbirthday FROM directory JOIN dirKids ON '$row[email]' = dirKids.parent");
echo "</table></div>";
if ($row['sFName'] == "" || $row['sFName'] == "undefined") {
echo "<div class='card'><div class='card-header'
id='headingOne'><h5 class='mb-0'><button class='btn btn-link'
type='button' data-toggle='collapse' data-target='#collapse".
$row["id"] ."' aria-expanded='true' aria-controls='collapse".
$row["id"] . "'><h5>".$row["fname"] ."<span id='lnameText'>".
$row["lname"] ."</span></h5></button></h5></div><div
id='collapse". $row["id"] . "' class='collapse'
aria-labelledby='headingOne' data-parent='#accordion'><div
class='card-body'><table id='myUL' class='table'><tr></tr><tr>
<td><h5>Address</h5></td><td>". $row["address"] ."</td></tr>
<tr><td><h5>Birthday</h5></td><td>".$row["birthday"]."</td>
</tr><tr><td><h5>Cell</h5></td><td>". $row["cell"]."</td></tr>
<tr><td><h5>Email</h5></td><td>". $row["email"] ."</td></tr>
</table></div>";
echo "<div class='col-md-6'><h3>Children</h3><table class='table'><tr><th><h5>Name</h5></th><th><h5>Birthday</h5></th>";
while($row1 = mysqli_fetch_array($results1)) {
if (!empty($row1["kname"])) {
echo "<tr><td>". $row1["kname"] ."</td><td>". $row1["kbirthday"]."</td></tr>";
}
}
echo "</table></div></div>";
?>
Since the data needed for the second while loop comes exclusively from the kids table, just build your SELECT statement for that, forget the join and the WHERE statement looks for only the parents email.
The below code goes inside the primary while loop and replaces the
$results1 = mysqli_query($con,"SELECT directory.email, dirKids.kname, dirKids.kbirthday FROM directory JOIN dirKids ON '$row[email]' = dirKids.parent");
with
//Build the select statement
$sql = "SELECT kname, kbirthday FROM dirKids WHERE parent = '" .$row[email] . "'";
//now run the query
$results1 = mysqli_query($con,$sql);
//uncomment the below to see the results
//var_dump(mysqli_fetch_array($results1));
Your query should look like this;
$select = mysqli_query($db, "SELECT * FROM parents_database WHERE parent_name = '$parent_name'");
while ($row = mysqli_fetch_array($select, MYSQLI_ASSOC)) {
// echo kids here..
}
Not sure what do you need. Since you posted 2 different queries.
But 1st one has wrong approach, hope you need to fix that one.
I think you've meant something like:
SELECT directory.email
, dirKids.kname
, dirKids.kbirthday
FROM directory
JOIN dirKids
ON directory.email = dirKids.parent
WHERE directory.email = '$row[email]'
Related
So what i want is the following. I have 3 tables: first i will explain in english what i want for final result:
let me explain all in english:
table 1 is REGISTERED_MEMBERS
table 2 is OPEN CLASSES
table 3 i want who appplied and to which class they applied and show that in a table when date is selected from a dropdown list!
This is how it should show at the end:
table = razpisani_tecaji with (ID_TECAJA, DATE, STATUS, ST_ODPRTIH_MEST)
table = registrirani_clani wtih (ID_TECAJNIKA,IME,PRIIMEK, EMAIL)
table = prijave_na_tecaj with (ID_TECAJNIKA, ID_TECAJA, PLACILO)
now in HTML i have a dropdown list populated with dates (this works ok) from table 1.
<form>
<select name="dates" onchange="showUser(this.value)">
<option value="" selected="selected">Izberi datum za pregled</option>;
<?php
$con = mysqli_connect('localhost','root','','viverius_education');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = mysqli_query($con, "SELECT ID_TECAJA, DATUM FROM razpisani_tecaji");
while ($row = $sql->fetch_assoc()){
echo "<option value='" . $row['ID_TECAJA'] . "'>" . $row['DATUM'] . "</option>";
}
?>
Here a ID is saved to a variable q which is then send to php via JS. This all works. Now what i would like is for user to select a date and get a results from 3. table only to show IME from linked to ID_TECAJNIKA and PLACILO linked to ID_TECAJNIKA.
THis is what i have in PHP so far:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','viverius_education');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT razpisani_tecaji.ID_TECAJA, registrirani_clani._ID_TECAJNIKA FROM prijave_na_tecaj
LEFT JOIN razpisani_tecaji ON prijave_na_tecaj.ID_TECAJA = razpisani_tecaji.ID_TECAJA
LEFT JOIN registrirani_clani ON prijave_na_tecaj.ID_TECAJNIKA = registrirani_clani.ID_TECAJNIKA";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Ime</th>
<th>Placilo</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['ID_TECAJNIKA'] . "</td>";
echo "<td>" . $row['PLACILO'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
$sql="select registrirani_clani., prijave_na_tecaj.,razpisani_tecaji.*
from registrirani_clani
left join prijave_na_tecaj on registrirani_clani.ID_TECAJNIKA = prijave_na_tecaj.ID_TECAJNIKA
left join razpisani_tecaji ON razpisani_tecaji.ID_TECAJA = prijave_na_tecaj.ID_TECAJA
where razpisani_tecaji.ID_TECAJA = '".$q."'";
My problem is this:
<?php
// Connect to database server
mysql_connect("localhost", "root", "abcabc") or die (mysql_error ());
// Select database
mysql_select_db('iite') or die(mysql_error());
// Get data from the database depending on the value of the id in the URL
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
echo'<h1>'. $row['title'].'</h1>';
echo'<h1>'. $row['price'].'</h1>';
}
// Close the database connection
mysql_close();
?>
I want to show related posts, for this I need to insert this:
$sql = "SELECT * FROM table1 where title like '%keyword%' limit 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["price"]. " " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
so how can I insert the related post part near
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
and how to echo?
Thanks
You can use OR or AND for combining different where conditions(according to requirement) in query :
Ex;
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5";
$strSQL = mysql_query(SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5) or die(mysql_error());
$row_strSQL = mysql_fetch_assoc($strSQL );
$totalRows_strSQL = mysql_num_rows($strSQL );
if ($result->totalRows_strSQL > 0) {
// output data of each row
while($row_strSQL= $result->fetch_assoc()) {
echo "id: " . $row_strSQL["id"]. " - Name: " . $row_strSQL["price"]. " " . $row_strSQL["title"]. "<br>";
}
} else {
echo "0 results";
}
You don't need two seperate queries for that at all. Just use the OR operator in ur where clause like Where id=" . $_GET['id']." or title like '%keyword%'
I need to print a row from a database, i know how to print columns, but having a hard time printing rows. Can someone tell me how to?
<?php
$query = "SELECT * FROM categorias ";
$result = mysqli_query($conn, $query) or die (mysql_error());
while ($categoria = mysqli_fetch_array($result)) {
echo "<p>" . $categoria ['descricao'] . "</p>";
}
?>
This is how im printing columns
The answer is don't use SELECT * in PHP, it's extremely prone to errors. If you explicitly list the columns in your select statement you can concatenate them into a table in PHP.
Hope this helps.
Use print_r to debug selected data.
Also look for Mysql Fetch Row
Always Use Google
<?php
$query = "SELECT * FROM categorias ";
$result = mysqli_query($conn, $query) or die (mysql_error());
if(mysqli_num_rows($result)>0)
{
while ($categoria = mysqli_fetch_array($result)) {
echo "<p>" . $categoria['descricao'] . "</p>";
}
}
?>
<table><tr><?php
while ($categoria = mysqli_fetch_array($result)) {
echo "<td>" . $categoria ['descricao'] . "</td>";} ?></tr></table>
I use a table, where while the array is true places the values cell by cell in a row, because the loop is working inside the <tr> </tr> creating a new <td> for every record.
I have had a long road to get to this last question. Everything is my code is working now, but I can't get this last little issue. Right now I have:
$sql = "SELECT phonenumber,email, dataplan AS currentplan, SUM(datamb) AS
value_sum FROM maindata GROUP BY phonenumber, dataplan";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$val = $row["value_sum"];
$plan = $row["currentplan"];
$remain = $plan - $val;
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
It only subtracts the first value as opposed to the values for all. displayed like this:
while ($row = mysql_fetch_assoc($result)){
echo "<tr>";
echo "<td>".$row['phonenumber'] . "</td> ";
echo "<td>".$row['currentplan'] . "</td> ";
echo "<td>".ROUND ($row["value_sum"],2) . "MB</td> ";
echo "<td>".$remain . " MB</td> ";
echo "<td>".$row['email'] . "</td></tr>";
}
So my goal is to subtract all value_sums from all dataplans, but what I have now, gives me the first value for all columns. Thank you!
mysql_fetch_assoc() will always get one row. You can use it in loop, or better use PDO, eg. like this:
$sql = "SELECT phonenumber,email, dataplan AS currentplan, SUM(datamb) AS
value_sum FROM maindata GROUP BY phonenumber, dataplan";
$results = $pdo->query($sql);
You can read about creating PDO connections here http://www.php.net/manual/en/book.pdo.php
I am currently creating a database for an upload system - I am using a select box to limit the number of categories added to the database.
<select name="category">
<?php
$conn = mysqli_connect("localhost", "blah", "blah") or die ("No connection");
mysqli_select_db($conn, "UPLOAD") or die("db will not open");
$query = "SELECT category FROM details GROUP BY category";
$result = mysqli_query($conn, $query) or die("Invalid query");
while($row = mysqli_fetch_array($result)) {
echo "<option value=\"" . $row[0] . "\">" . $row[0] . "</option>";
}
mysqli_close($conn);
?>
</select>
<select name="reaction">
<?php
$conn = mysqli_connect("localhost", "blah", "blah") or die ("No connection");
mysqli_select_db($conn, "UPLOAD") or die("db will not open");
$query = "SELECT reaction FROM details GROUP BY reaction";
$result = mysqli_query($conn, $query) or die("Invalid query");
while($row = mysqli_fetch_array($result)) {
echo "<option value=\"" . $row[0] . "\">" . $row[0] . "</option>";
}
mysqli_close($conn);
?>
While the two queries are the same - Only the Category (The top query) is stopping form repeating multiple data from my db. When I look into my database - This is what I am finding (Which I have a hunch may be the problem).
INSERT INTO `details` (`name`, `category`, `reaction`, `photo`, `date_added`) VALUES
('Mase Laughing', 'Funny', 'Laugh\n', 'mase-laugh.gif', '2013-05-01 07:16:26'),
('Movie Wink', 'Cheeky', 'Wink\n', 'movie-wink.gif', '2013-05-02 12:33:12'),
('Tarzan Giggle', 'Funny', 'Wink\r\n', 'tarzan-laugh.gif', '2013-05-02 01:33:00');
Beside the reactions I am getting these strange \r\n letters -
Anyone have any Ideas?
Thanks in advance.
These are "Carriage Return" (\r) and "Newline" (\n) characters. These are commands telling your computer to go the end of the line and to a new line.
To stop your page from showing duplicate categories, change this:
$query = "SELECT category FROM details GROUP BY category";
into this:
$query = "SELECT distinct category FROM details GROUP BY category";
It will not prevent your database from storing duplicate categories (which you do no want, otherwise you would only be able to save 1 (one) line of details per categorie, but it will prevent your dropdown (select) from showing the duplicates. So, with the details you showed, it will give you a dropdown with the values 'Funny' and 'Cheecky', both of them showing only once.
Add "distinct" to your other SQL statement too to have the reactions de-duplicated too:
$query = "SELECT DISTINCT reaction FROM details GROUP BY reaction";
Here I am updating original question by reducing redundant code
<?php
$conn = mysqli_connect("localhost", "root", "") or die ("No connection");
mysqli_select_db($conn, "test") or die("db will not open");
?>
<select name="category">
<?php
$query = "SELECT category FROM details GROUP BY category";
$result = mysqli_query($conn, $query) or die("Invalid query");
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row[0] . "'>" . $row[0] . "</option>";
}
?>
</select>
<select name="reaction">
<?php
$query = "SELECT reaction FROM details GROUP BY reaction";
$result = mysqli_query($conn, $query) or die("Invalid query");
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row[0] . "'>" . $row[0] . "</option>";
}
mysqli_close($conn);
?>
</select>