How to echo out mysqli aliased columns? - php

Having issues echoing out the sql columns because I want to output the two
aliased columns that come out of an sql statement whereby I'm doing calculations on certain rows.
I have tried the below code and also by modifying it by replacing the 0 and 1 with the aliased column names, AmountOwed, KindsOfProducts which didnt work.
PHP CODE - where the issue is...
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "AmountOwed: " . $row[0]. " - KindsOfProducts: " . $row[1]
."<br>";
}
} else {
echo "0 results";
}
$con->close();
The Messy SQL statement I'm trying to echo
#$username=$_POST['username'];
$sql= "SELECT SUM(`price` * `quantity`) AS AmountOwed,
COUNT(*) AS KindsOfProducts FROM tablename
WHERE `orderdate` BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
and uname = '$username'";

The original method I found on Stack was to echo row[0] etc, replace the 0 with the column alias.
Only reason why this didnt work initially was it had a small typo in there, here's the correct code.
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "TEXT: " . $row[COLUMNALIAS]. " - MORETEXT: " . $row[COLUMNALIAS]
."<br>";
}
} else {
echo "0 results";
}
$con->close();

Related

How to sort MySQL entries by date in PHP? [duplicate]

This question already has answers here:
Sort by date (newest)
(2 answers)
Closed 3 years ago.
I want entries in MySQL to be ordered by Date (fDate in my case) on my website. Here is the table structure:
The entries are read with this code:
$sql = "SELECT * FROM homework";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<br> Fach: " . $row["subject"] . "<br> Bis zum: " . $row["fDate"]. "<br>" . $row["hDesc"]. "<br>";
}
} else {
echo "0 results";
}
And this results in my Website looking like this:
Now I would like the output of every row ordered by date, so that the row with the date closest to the current one is displayed as the first.
I'm new to MySQL and PHP, so how can this be done?
$sql = "SELECT * FROM homework ORDER BY fDate DESC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<br> Fach: " . $row["subject"] . "<br> Bis zum: " . $row["fDate"]. "<br>" . $row["hDesc"]. "<br>";
}
} else {
echo "0 results";
}
Change the SQL statment to
SELECT * FROM homework ORDER BY fDate DESC (OR ASC)

mysql get the value of a column in a database as a percentage

I have a table in a database and am currently pulling data using the SELECT statement Where the information from the column Opinion equals either Negative or Positive.
what i want to also do is output the positive data as an overall percentage but Unsure if that would be possible i had a look at multiple overflow questions but couldn't see anything. Any help would be appreciated.
$sql = "select Opinion from survey where Opinion = 'Positive'";
$result = mysqli_query($con, $sql);
if (!$result) {
die(mysqli_error($con));
}
echo "<div style='overflow: auto;'>";
echo "<table width=40% border=1 align=center >
<tr>
<th>Opinion</th>
<th>Date</th>
</tr>";
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr align=center>';
echo "<td>" . $row['Opinion'] . "</td>";
}
} else {
echo "0 results";
}
?>
The query will calculate how many percentage of 'Positive' opinions compared to total rows of the 'survey' table:
select (SUM(IF(Opinion = 'Positive',1,0))/count(*))*100 as percentage_positive
from survey
The query below can determine the percentage of each different opinions at once:
select
Opinion,
count(*) as total,
(count(*) / (select count(*) from survey))*100 as percentage
from survey
group by opinion
Something like this as SQL query?
SELECT COUNT(Opinion) / (SELECT COUNT(Opinion) FROM survey) * 100
FROM survey
WHERE Opinion = 'Negative'
After help from Kevin HR i have fixed my issue with the code below.
$sql = "select Opinion,count(*) as total,(count(*) / (select count(*) from survey))*100 as percentage from survey group by opinion";
$result = mysqli_query($con, $sql);
echo "<div style='overflow: auto;'>";
echo "<table width=40% border=1 align=center >
<tr>
<th>Opinion</th>
<th>Percentage</th>
</tr>";
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr align=center>';
echo "<td>" . $row['Opinion'] . "</td>";
echo "<td>" . $row['percentage'] . "</td>";
}
}
else {
echo "0 results";
}
Working code for getting the value of number of rows from a database
$sql = "SELECT * FROM `survey` WHERE Opinion='Positive'";
$connStatus = $con->query($sql);
$numberOfRows = mysqli_num_rows($connStatus);
echo "There are a total number of $numberOfRows Positive rows in the database";
echo "<br>";
echo "<br>";

How do I Subtract Values of Multiple Queries

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

PHP echo date and number from query

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 ']';
}
}

Not able to delete the database(mySQL) record in PHP, where did i go wrong?

I am trying to delete the records from the users table in mysql,
the code goes like this.
if(isset($_GET['id'])) {
//create query to delete the record
$query = "DELETE FROM users WHERE id =" . int($_GET['id']) or die(mysql_error());
//execute query
if($mysqli->query($query)) {
//print number of affected rows
echo $mysqli->affected_rows. " row(s) affected";
}
else {
//print error message
echo "Error in query : $query " . $mysqli->error;
}
}
else {
echo "Could not Execute the Delete query";
}
at the same time i am iterating the records from the users table in the database and it goes like this.
//query to get records
$query = "SELECT * FROM users";
//execute query
if($result = $mysqli->query($query)) {
// see if any rows were returned
if($result->num_rows > 0) {
// if yes then print one after another
echo "<table cellpadding=10 border=1>";
while($row = $result->fetch_array()) {
echo "<tr>";
echo "<td>" .$row[0] . "</td>";
echo "<td>" .$row[1] . "</td>";
echo "<td>" .$row[2] . "</td>";
echo "<td>Delete</td>";
echo "</tr>";
}
echo "</table>";
}
$result->close();
}
the problem is, i am able to get the records from the database and display it in the browser but when i try to delete the record the first condition does not pass i.e if(isset($_GET['id'])) instead it goes to else condition and print the message "Could not Execute the Delete query " , i guess it is not able to fetch the $_GET['id'] so only it refuses to enter the if condition,
P.S :i would appreciate if someone explains me in simple words, i am a newbie to programming, thanks..
You are missing an =:
echo "<td>Delete</td>";
HERE -------------------^
"DELETE FROM users WHERE id =" . int($_GET['id']) or die(mysql_error());
Shouldn't it be intval instead? There's no function int in PHP. There's also (less preferably) the cast to int, like this: (int) $_GET['id']).

Categories