using fetch twice in php to get the data - php

I'm trying to get a data from db, I would to say welcome $row['name'];
then in a loop need to print the items
if I did the below code, I will get all items except the first item, but if I deleted the $row2 with the welcoming name, I will get all items why ?
is there a way to use this $row = $SQL->fetch() for both?
<?php
session_start();
include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
$SQL = $dbh->prepare("SELECT * from items, users where userid = ?");
$SQL->execute([$_SESSION["userid"]]);
$row2 = $SQL->fetch();
echo "Welcome " . $row2['name'] . "<br>";
while ($row = $SQL->fetch()) {
echo $row["itemname"] . "-" . $row["price"] . "-" . $row["itemqty"] . "<br>";
}
}else{
echo "<h1>Not Logged in. Access denied.</h1>";
}
?>

When you run fetch() you are moving forward the pointer in the result set. So your first call to fetch() gets the first row, second gets the second row, etc.
Probably the easiest approach would be to pull all results into an array and then work with that.
<?php
session_start();
include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
$SQL = $dbh->prepare("SELECT * from items, users where userid = ?");
$SQL->execute([$_SESSION["userid"]]);
$data = $SQL->fetchAll();
$row2 = $data[0];
echo "Welcome " . $row2['name'] . "<br>";
foreach ($data as $row) {
echo $row["itemname"] . "-" . $row["price"] . "-" . $row["itemqty"] . "<br>";
}
} else {
echo "<h1>Not Logged in. Access denied.</h1>";
}

Related

How do I pass this information to print it out in another document? PHP MySQL

I am having trouble echoing row data within the page I want to print it out to.
My function works, but only echoes the information because it is local (within the same function).
I'm trying to get this function to echo the database's information to another .php file (same program).
public function findByUsername($username) {
$sql = 'SELECT * FROM events WHERE username=? ';
$statement = DatabaseHelper::runQuery($this->connection, $sql, Array($username));
while ($row = $statement->fetch()) {
echo $row['username'] . "<br />";
echo $row['date'] . "<br />";
}
}
Here is the part of the other file I need to print the information from the function to:
<?php
if (isset($_SESSION["username"])) {
$eventDAO = new EventDAO($connection);
$event = $eventDAO->findByUsername($_SESSION["username"]);
foreach((array)$event as $e) {
echo $e->getUsername() . ' ' . $e->getDate() . '<br>';
}
}
?>
I'm trying to output the username/date.
Not 100% on this concept.
If you're simply trying to output username/date from one file to another, try using sessions.
public function findByUsername($username) {
$sql = 'SELECT * FROM events WHERE username=? ';
$statement = DatabaseHelper::runQuery($this->connection, $sql, Array($username));
while ($row = $statement->fetch()) {
echo $row['username'] . "<br />";
echo $row['date'] . "<br />";
$_SESSION['getuname'] = $row['username'];
$_SESSION['getdate'] = $row['date'];
}
}
You can then output the information on another php file simply by echoing it out.
echo "Username is ". $_SESSION['getuname'];

Buttons created using a PHP while loop are not updating the MySQL database

I am creating a multiuser shared to do list application using PHP and MySQL. Currently, my application is displaying the to do list items by iterating over the database table with a while loop.
All of that works correctly, so I know I am connecting to the database. Part of the while loop also generates buttons that allow a user to "claim" an item that does not have anyone working on it or to indicate that at item has been completed. However, the buttons are not updating the database table.
<?php
include 'includes/dbh.inc.php';
$sql = 'SELECT * FROM items WHERE item_is_done = 0';
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$creator = $row['item_creator'];
$owner = $row['item_owner'];
$id = $row['item_id'];
if (isset($_POST['do_item'])) {
$update = "UPDATE items SET item_owner = $currentID WHERE item_id = $id;";
mysqli_query($conn, $update);
header("Location: ../todo.php?code=doing");
exit();
} else if(isset($_POST['complete_item'])) {
$update = "UPDATE items SET item_is_done = 1 WHERE item_id = $id;";
mysqli_query($conn, $update);
header("Location: ../todo.php?code=done");
exit();
}
echo '<h4>Item ID:</h4>' . $id . '<br><br>';
echo '<h4>Item created by:</h4>' . $creator . '<br><br>';
echo '<h4>Date Added: </h4>' . $row['item_add_date'] . '<br><br>';
echo '<h4>Item Title: </h4>' . $row['item_title'] . '<br><br>';
echo '<h4>Description: </h4>' . $row['item_description'] . '<br>';
if($row['item_owner'] == 'None') {
echo '<br>';
echo '<button type="submit" name="do_item" formaction="todo.php" formmethod="POST">Do Item</button>';
echo '<br>';
} else if($row['item_owner'] != 'None') {
echo '<br>';
echo '<h4>Item is being worked on by: </h4>' . $owner . '<br><br>';
echo '<button type="submit" name="complete_item" formaction="todo.php" formmethod="POST">Complete Item</button>';
echo '<br>';
}
echo '<hr>';
}
?>
I was also got stuck on same kind of problem what I did was I tried to put the updating variables in ' ' single quotes.
If it can help you you can try this queries
$update = "UPDATE items SET item_owner='$currentID' WHERE item_id='$id'";
$update = "UPDATE items SET item_is_done='1' WHERE item_id ='$id'";

Nested while doesn't work in PHP

I have problem with my code.
I use nested while in my code and the nested while doesn't work, only the outer while is work
I don't know where is the bug of my code.
This is the piece of my code :
$database = new mysqli('127.0.0.1', 'user', 'user', 'mini_email');
$query = 'SELECT * FROM mails';
$query2 = 'SELECT * FROM users';
$result_set = $database->query($query);
$result2 = $database->query($query2);
while ($row2 = $result2->fetch_assoc()) {
if ($row2['username'] == $_SESSION['user']) {
$id_email = $row2['id'];
}
}
if (isset($_SESSION['is_logged_in'])) {
echo('<center><font size="10">Mailing List</font></center><br><br>');
echo('<center><table border="3" bgcolor="#f0cdfa">');
echo('<tr>');
echo ('<td>No</td>');
echo ('<td>ID</td>');
echo ('<td>From</td>');
echo('<td>Subject</td>');
echo ('<td>Message</td>');
echo ('<td>Action</td>');
echo ('</tr>');
$i = 1;
while ($row = $result_set->fetch_assoc()) {
if ($row['to_user_id'] == $id_email) {
echo('<tr>');
echo ('<td>' . $i . '</td>');
echo ('<td>' . $row['id'] . '</td>');
while($row2 = $result2->fetch_assoc()){
if($row2['id']== $row['from_user_id']){
echo ('<td>' . $row2['username'] . '</td>');
}
}
echo ('<td>' . $row['subject'] . '</td>');
echo ('<td>' . $row['message'] . '</td>');
echo ('<td>View</td>');
echo ('</tr>');
$i++;
}
}
Your initial
while ($row2 = $result2->fetch_assoc()) {
is looping through all the records to the end of the set,
so looping a second time won't retrieve any further records because you're already at the end of the resultset
Resultset pointers aren't automatically reset when you initiate a new loop, but you can reset them manually using
$result2->data_seek(0);
before each subsequent loop
But iterating the point made in the comments by #Sirko you'd be better using a JOIN to make a single query
If I may help, I think you shouldn't even perform the queries when your if statement with the session returns false.
In the first lines or your script you should define a function with all this code, and write it like this :
function YourFunction()
{
if (isset($_SESSION['is_logged_in'])) {
return false;
}
// Database connection and queries
// your business
}
This will be more clean.
Next, your query doesn't seem to be correct. You get all the mails of your website, and then in a loop you check if the mail user id is the user id you have in session. Imagine the lack of performance if you have 35 000 mails in your database.
Improve your query with a WHERE statement : http://www.w3schools.com/sql/sql_where.asp
then, are you sure that $_SESSION['user'] contains an id ? I think your second if statement never returns true because of that.

PDO row count confusion

I am making a login page that checks for matching values in a database if the SELECT query returns a matching row with username and password then it will return a row count of 1. The way I have it coded right now when I echo the variable that stores the row count it will echo 26 for some reason and I'm not to sure why.
Would someone explain if I am doing something wrong or if this is normal behavior and where that value is coming from?
function checkLogin($conn,$myusername,$mypassword,$row,$row1){
try {
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
if($results->fetchColumn() > 0) {
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
$rowCount = count($row);
echo $rowCount;
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
echo $count;
}
else {
print "NO ROWS";
}
}
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
Your code, $rowCount = count($row);, is counting the columns in the current row - not the number of rows returned by the query.
On the same note, you are echoing a second count related variable, $count, but you neither declare-it nor increment it in your code. It looks like this one is the one that's supposed to be counting the number of rows you loop through. If this is true, you should set it as $count = 0; before the loop and use $count++; within it:
$count = 0;
foreach ($conn->query($sql) as $row) {
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
$count++;
}
echo $count;
Also, you're currently using PDO's rowCount prior to selecting a user, and you're using it properly. You could just store that result into a variable and use it to tell how many rows you are receiving:
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
$numRows = $results->fetchColumn();
if($numRows > 0) {
... rest of your code ....
function checkLogin($conn,$myusername,$mypassword,$row,$row1)
{
try
{
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql))
{
$count = $results->fetchColumn();
echo "$count\n";
if($count > 0)
{
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
}
else
{
print "NO ROWS";
}
}
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}

Repeating a query

I want to search a table by inputing a random number for the ID, and for it to be successful, it has to match the specified tag. So far I have:
$query = "SELECT * FROM web_db WHERE P_Id = " . $random;
$result = mysql_query($query);
if($result) {
while($row = mysql_fetch_array($result)){
$name = $row[$id];
echo 'ID:' . $name . '<br>';
$name = $row[$url];
echo 'URL: ' . $name . '<br>';
$name = $row[$tag];
echo 'Tag:' . $name . '<p>';
}
}
This brings up one entry, any tag. How can I have it repeat until Tag matches a specified value?
You don't. SELECT statement returns everything that matches the followed conditions. So, if you want to query for a specific tag entry disregarding the P_Id, do this :
$query = "SELECT * FROM web_db WHERE tag = '".$tag."' ORDER BY RAND() LIMIT 1";
RAND() in this case will order the list randomly, while the query returns the first result that matches the tag used.
$result = mysql_query($query);
if(count($result) > 0) {
while($row = mysql_fetch_array($result)) {
echo 'ID:' . $row['id'] . '<br>';
echo 'URL: ' . $row['url'] . '<br>';
echo 'Tag:' . $row['tag'] . '<p>';
}
} else {
echo 'no entries found';
}
if("sometag" === $name) break;
that exits the while loop. after you exit, you should check again to see if the tag was found or not

Categories