Hi I have trying to learn php by writing little web app for showing me sales data. I have got a query which i now works as i have tested it but i want it to echo the datematched and the number of rows/results found with that date. This is what I have so far
<?php
$con=mysqli_connect("host","user","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM matched WHERE datematched IN (
SELECT datematched FROM matched GROUP BY datematched HAVING count(*) > 1");
while($row = mysqli_fetch_array($result))
{
echo "['";
echo "" . $date['datematched'] . "', ";
echo "" . $num_rows . "],";
}
mysqli_close($con);
?>
I know i am doing something wrong here. ryan
EDIT:
<?php
$con=mysqli_connect("host","user","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM matched WHERE datematched IN (
SELECT datematched FROM matched GROUP BY datematched HAVING count(*) > 1");
echo "['";
echo " 16/08/2013 ', ";
echo "12345}],";
mysqli_close($con);
?>
Okay i have just checked my echo and they work i put in some data so all i need is to find a way of getting the information of the datematched that has been found and then the number of rows that has been found with that. Thanks Ryan
first of all you need to make an adjustment to your query, so that it has the number of rows your expecting.
$result = mysqli_query($con,"SELECT datematched, COUNT(*) as num_rows "
. "FROM matched GROUP BY datematched HAVING num_rows > 0");
then you can display the data as follows
while($row = mysqli_fetch_array($result))
{
echo $row['datematched'] . ",";
echo $row['num_rows'];
}
if your sql query is perfect then you should write like this wayt
while($row = mysqli_fetch_array($result))
{
echo "['";
echo "" . $row['datematched'] . "', ";
echo "" . $row['num_rows'] . "', ";
}
please set your column as you got in your mysql query.
<?php
$query=mysqli_query($con,"SELECT datematched FROM matched GROUP BY datematched");
$num=mysqli_num_rows($query);
if($num>1)
{
$result = mysqli_query($con,"SELECT * FROM matched");
$num_rows=mysqli_num_rows($result);
while($row = mysqli_fetch_array($result))
{
echo '['; echo $row['datematched']; echo $num_rows; echo ']';
}
}
Related
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]'
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'm having issues placing a PHP variable in MySQL string,
<?php
$con=mysqli_connect("***","***","***","***");
function getItem($itemNo)
{
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM products WHERE product_id = '$itemNo'");
echo $itemNo;
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo $row['product_id'] . " " . $row['product_name'];
echo "<br>";
}
}
getItem(1001);
mysqli_close($con);
?>
The page shows my echo of the $itemNo, but thats all. If I just do select * from products, it gives my entire table like it should, so I know the database is working,
so I've narrowed it down to the placement of the variable.
EDIT:
product_id column is an int and also the primary key.
You can try a prepared statement to make using variables in your queries easier.
$stmt = $con->prepare("SELECT * FROM products WHERE product_id=?");
$stmt->bind_param($itemNo);
$stmt->execute();
$stmt->close();
$result = mysqli_query($con,"SELECT * FROM products WHERE product_id = " .$itemNo );
<?php
$con = mysql_connect("localhost","root","root");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("mydb",$con);
//Count all Total of Acc Class with same value Example Restaurant, Hotel
$query = "select acc_class,count(*) as total from mytable group by acc_class";
$result = mysql_query($query);
$values = mysql_fetch_assoc($result);
$num_total = $values['total'];
while($record = mysql_fetch_array($result)){
echo '<br>';
echo "<label>" . $record['acc_class'] . "</label>";
echo "<label>" . $num_total . "</label>";
}
mysql_close($con);
?>
Guys please help me. I want to produce something like this. But I don,t know how.
Account Class Total
------------- -----------
Hotel 5
Restaurant 2
Club 3
Church 1
I want to have a page in which it will show total numbers of each account class. Please help.
Thanks!
//you just need to put the name of the column in quert like COUNT(column_name)
$con = mysql_connect("localhost","root","root");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("mydb",$con);
//data base connection ends here
//you write a query to fire if you want by order the put "ORDER BY HERE"
$query = "select acc_class,count(acc_class) as total from mytable group by acc_class";
//here you fire a query to mysql
$result = mysql_query($query);
//now put the selected roe in loop and again and again loop ask for more data to mysql
while($record = mysql_fetch_array($result)){
**//here you select all the group in the table**
echo '<br>';
echo "<label>" . $record['acc_class'] . "</label>";
echo "<label>" . $record['total'] . "</label>";
}
//close connection to database
mysql_close($con);
Please dump $values:
var_dump($values);
I guess, the problem is it's either the data itself or the data-fetch (array, assoc).
Please format your SQL for better readability:
SELECT acc_class, COUNT(*) AS total FROM mytable GROUP BY acc_class;
The Count statement is correct: https://dev.mysql.com/doc/refman/5.7/en/counting-rows.html
Solution:
$query = "SELECT acc_class, COUNT(*) AS total FROM mytable GROUP BY acc_class";
$result = mysql_query($query);
echo '<table border="1">';
while($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td>' . $row['acc_class'] . '</td>';
echo '<td>' . $row['total'] . '</td>';
echo '</tr>';
}
echo '</table>';
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