$st = $this->db->prepare("SELECT * FROM users WHERE id=? ORDER BY id ASC");
$st->execute(array($id));
if($st->rowCount() >= 1){
foreach ($st as $row) {
echo $row["exp"]."+";
}
}
So what I've tried is to echo $row["exp"]."+"; to simply add in a loop, but it just print it out. How can I fix?
Try like this
$st = $this->db->prepare("SELECT * FROM users WHERE id=? ORDER BY id ASC");
$st->execute(array($id));
$sum=0;
if($st->rowCount() >= 1){
foreach ($st as $row) {
$sum += $row["exp"];
}
echo $sum
}
you can also get sum of exp by single query SELECT SUM(exp) as exp FROM users WHERE id=? ORDER BY id ASC
Here, this should give you all the answers you need: http://www.homeandlearn.co.uk/php/php.html
In particular, look at section 6, Addition in PHP
Related
I am creating a time attendance PHP script. I started from storing data in the database MySQL and use different tables for the Punch-in/Punch-out, Breaks, Lunch/Dinner breaks.
Each one of the casualties mentioned before have a table which is structured with an:
ID, start, end, flag
I have already tried to do this with the following code of foreach but unsuccessfully!
foreach ($total as $key => $row) {
$start[$key] = $row['start'];
}
$final = array_multisort($start, SORT_DESC, $total);
echo $final;
Here is the code that I have made with 2 SELECT MySQL queries
$result = mysqli_query($db, "SELECT * FROM time WHERE username =
'$user_check' ORDER BY start DESC");
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
} $db->next_result();
$result = mysqli_query($db, "SELECT * FROM break WHERE username =
'$user_check' ORDER BY start DESC");
$data2 = array();
while ($row = mysqli_fetch_assoc($result)) {
$data2[] = $row;
}
$total = array_merge ($data, $data2);
I would like to have 1 array of this 2 queries sorted DESC by start as I will use this array to populate a table in DESC order.
Use UNION ALL in your query, instead of merge arrays. Let the database do the work for you:
SELECT * FROM
(SELECT * FROM time WHERE username = '$user_check'
UNION ALL
SELECT * FROM break WHERE username = '$user_check'
) ORDER BY start DESC
PS: Your code is vulnerable to SQL Injection. You should use prepared statement instead.
I've been combing through previous questions and trying many solutions but cannot figure this out. I'm trying to convert this query to a Prepared Statement:
$query = mysqli_query($this->con, "SELECT * FROM notifications WHERE user_to='$userLoggedIn' ORDER BY id DESC");
Here is what I have:
$query = $this->con->stmt_init();
$query->prepare('SELECT * FROM notifications WHERE user_to=? ORDER BY id DESC');
$query->bind_param('s', $userLoggedIn);
$query->execute();
$query->store_result();
$qty = $query->num_rows;
$query_result = $query->get_result();
Below this code I have variables being used like this:
if($qty == 0) {
echo "<li class='no-more-posts' style='height: 0px; text-transform: uppercase;'>- You have no notifications! -</li>";
return;
}
$num_iterations = 0; //Number of messages checked
$count = 1; //Number of messages posted
while($row = $query_result->fetch_assoc()) {
if($num_iterations++ < $start)
continue;
if($count > $limit)
break;
else
$count++;
$user_from = $row['user_from'];
etc.etc.
What I am getting is blank result in my dropdown. If I change the while statement back to the original while($row = mysqli_fetch_array($query)) { (which I know is wrong and from old statement) my result is always returning the li No More Posts to Show. This tells me that $qty = $query->num_rows; is returning 0. Based on documentation my understanding is that once I buffered the result set with store_result() I could call $qty = $query->num_rows; right after. What am I missing here?
I'm certain this isn't the most efficient way to do things, but it's all I have on it; decided to break the statement up.
First I did a statement for the count:
$query_count = $this->con->stmt_init();
$query_count->prepare('SELECT COUNT(*) FROM notifications WHERE user_to=?');
$query_count->bind_param('s', $userLoggedIn);
$query_count->execute();
$query_count_result = $query_count->get_result();
$rows_count = $query_count_result->fetch_array();
$qty = array_shift($rows_count);
Then I did a statement for the data:
$query = $this->con->stmt_init();
$query->prepare('SELECT * FROM notifications WHERE user_to=? ORDER BY id DESC');
$query->bind_param('s', $userLoggedIn);
$query->execute();
$query_result = $query->get_result();
It solved my problem & everything works as expected. I know there is a better way to do this, so if someone has that suggestion great. In the meantime this will have to do.
I am trying to create a PDO database results page with a previous and next for the previous 10 or next 10 records. I just can't figure out what should go in the 4 ????? areas below. I have tried several different approaches with all sorts of incorrect results. Any ideas on the missing pieces to make this work?
$results = $dbh->prepare("select
stories.SID,
stories.story_name,
stories.category,
stories.genre
FROM stories
WHERE stories.category = :cat OR stories.genre = :gen LIMIT 10");
$results->bindParam(':cat', $scategory, PDO::PARAM_STR);
$results->bindParam(':gen', $sgenre, PDO::PARAM_STR);
$results->execute();
$row = $results->fetchAll(PDO::FETCH_ASSOC);
}
if ($row) {
echo '<table>';
echo '<tr>';
foreach ($row as $all) {
echo '<tr>';
echo "<td>$all[story_name]
</td>";
echo "<td>$all[category]</td>";
echo "<td>$all[genre]</td>";
}
echo '</table>';
}
//get all results from PDO SQL query and pass to previous & next links
$id = $row;
$stmt_a = $pdo->prepare("
(SELECT * FROM stories WHERE ???? ORDER BY id DESC LIMIT 1)
UNION (SELECT * FROM stories WHERE id = (SELECT MAX(id) FROM stories)) LIMIT
1 prev_id");
$stmt_b = $pdo->prepare("
(SELECT * FROM stories WHERE ????? ORDER BY id ASC LIMIT 1)
UNION (SELECT * FROM stories WHERE id = (SELECT MIN(id) FROM stories)) LIMIT
1 next_id");
// $vars = array(':id' => $id);
$prev = $stmt_a->execute();
$next = $stmt_b->execute();
if ($prev) {
while($row = $stmt_a->fetchObject()) {
echo 'Previous';
}
} else {
echo 'no previous';
}
if ($next) {
while($row = $stmt_b->fetchObject()) {
echo 'Next';
}
} else {
echo 'no next';
}
Here is a blog that discusses many aspects of what you are doing:
http://mysql.rjweb.org/doc.php/pagination
It also shows how to do "pagination" in a scalable way.
Below is my code
$stmt = $db->prepare("SELECT * FROM inbox ORDER BY `date` DESC ");
$stmt->execute(array());
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$uniques = count(array_unique($row, SORT_REGULAR));
for ($i=0; $i < $uniques; $i++) {
$inbox_id = $row[$i]["inbox_id"];
$stmt = $db->prepare("SELECT * FROM messages WHERE inbox_id=? AND seen=? ORDER BY `date` DESC");
$stmt->execute(array($inbox_id, 0));
$row_msg = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
return $row_msg;
But this is nor returning all data.It is only returning values got from first iteration only.
you can use:
$row_msg[$i] = $stmt->fetchAll(PDO::FETCH_ASSOC);
Your PDO statement is prepared every round inside the loop, that is not necessary and i hope the inbox_id column is a primary key in the inbox table:
$stmt1 = $db->query("SELECT `inbox_id` FROM inbox ORDER BY `date` DESC ");
$stmt2 = $db->prepare("SELECT * FROM messages WHERE inbox_id=? AND seen=0 ORDER BY `date` DESC");
while($id = $stmt1->fetchColumn(0)) {
$stmt2->execute(array($id));
$row_msg[$id] = $stmt2->fetchAll(PDO::FETCH_ASSOC);
}
return $row_msg;
If you do not want a multidimensional array you can just add the row to the result array by using array_merge() (PHP Manual: array_merge) inside the loop (instead of the line with $row_msg[$id]):
$row_msg = array_merge($row_msg, $stmt2->fetchAll(PDO::FETCH_ASSOC));
I have a table and i want to echo the 2 last rows of my tabel, I used the below code but just the last one showed, what is the problem.
$result1 =(mysql_fetch_array(mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")));
Print $result1['time'];
mysql_fetch_array = 1 fetch.
do it again for fetching 2nd result.
Also, use mysqli eh.
You're doing mysql_fetch_array only one time, so it gets the first element. If you want to get all the elements, then do it again, or use a loop.
Something like:
$query = "SELECT * FROM $table ORDER BY id DESC LIMIT 2";
while($row = mysql_fetch_array(mysql_query($query) )
{
echo $row['time'].'<br>';
}
For 2 Or more rows you need to loop it
$sql = mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")
while($row=mysql_fetch_array($sql))
{
echo $row['time']."<br>";
}
$query = mysqli_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2");
while ($result = mysqli_fetch_array($query)) {
echo $result['time'];
}
Gives out every return of your database (2 in this case). You should use mysqli_-functions.
Maybe you should try like this, since mysql_fetch_array returns only one row
while ($row = mysql_fetch_array($yourQuery)) {
echo $row["yourAlias"];
}
Further details here : http://fr2.php.net/manual/en/function.mysql-fetch-array.php
My solution:
$limit = 2;
$sql = "SELECT * FROM $table ORDER BY id DESC LIMIT $limit";
$result = mysql_query($sql);
$array = array(); $i = 0;
while($row = mysqli_fetch_array($result))
{
$array[$i] = $row;
$i++;
}
var_dump($array[0]);
var_dump($array[1]);