Display data in desired form ,using php - php

I'm trying to get this output
Province
1.city 1 33poits
2.city 2 33poits
3.city 3 33poits
and what my current output is
Province
1.city 1 33points
Province
2.city 2 33points
Province
3.city 3 33points
please help just a newbie here, below is my php code
<?php
$sql = "SELECT * FROM ccty WHERE ID=".$ID;
$results = $mysqli->query($sql);
if ($results->num_rows > 0) {
while ($row = $results->fetch_object()) {
?>
<table>
<tr><?= $row->PID; ?>
<td><?= $row->SPID; ?><?= $row->points; ?></td>
</tr>
<?php
}
} else {
echo "No record available!";
}
?>

For one, your table-structure is invalid.
To only print the PID once per group, store the previous PID in a variable and check against it - only print it if its different from before.
You should also be using a prepared statement instead of a direct query.
<?php
$sql = "SELECT PID, SPID, points FROM ccty WHERE ID=? ORDER BY PID";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $ID);
$stmt->execute();
$stmt->bind_result($PID, $SPID, $points);
if ($stmt->num_rows) {
echo '<table>';
$previousPID = null;
while ($stmt->fetch()) {
if ($PID != $previousPID) {
echo '<tr><td>'.$PID.'</td></tr>';
$previousPID = $PID;
}
?>
<tr>
<td><?= $SPID." ".$points; ?></td>
</tr>
<?php
}
echo '</table>';
} else {
echo "No records available!";
}

Related

Checking if value is stored in the database with isset()

I want to display a page, if user doesn't pay for content (via Stripe) and therefore have to check in DB if he paid or not. If he paid, I store string "ok" into status and if he doesn't it's just blank.
Now I'm not sure why the following code doesn't work:
<?php
if(!isset($_SESSION["username"])) {
?>
Login to watch Satellite data.
<?php
$query = 'SELECT status
FROM users
WHERE username="'.$_SESSION["username"].'"';
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$status = $row["status"];
if ($status !== "ok") {
$status_notpaid = true;
}
}
} elseif(isset($_SESSION["username"]) && isset($status_notpaid)) {
include("notpaid.php");
} else {
?>
<?php
$query = 'SELECT id
FROM users
WHERE username="'.$_SESSION["username"].'"';
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
?>
Hello <strong><?php echo $_SESSION["username"];?></strong> |
<?php
while ($row = $result->fetch_assoc()) {
echo $row["id"]; }
?>
I'm not sure why elseif(isset($_SESSION["username"]) && isset($status_notpaid)) { include("notpaid.php"); } doesn't work.
I am assuming the login script sets $_SESSION["username"] if login is successful.
It would make more sense to put the id of the users table, as I assume that is the primary key. You can keep username in session as well if you like and that would save you running some of this code at all.
<?php
if(!isset($_SESSION["userid"])) {
# user not logged in direct to login, and nothing else
echo 'Login to watch Satellite data.';
}
if (isset($_SESSION["userid"])) {
# then we are logged in
# So now we check if they paid
$query = 'SELECT status
FROM users
WHERE id=?';
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $_SESSION["userid"])
$stmt->execute();
$result = $stmt->get_result();
# we had better only be getting one row as a resut of that query
# so a loop is totally unnecessary
$row = $result->fetch_assoc();
$status = $row["status"];
if ($status !== "ok") {
include("notpaid.php");
}
}
?>
Hello <strong><?php echo $_SESSION["username"];?></strong> | $_SESSION['userid']

between two users messages conversation in php mysqli

I am creating simple private message conversation script. my script showing incoming users conversation. but messages which i sent to another user not showing.
any one can help me i have lot of tried.
my database
id from_id from_name to_id to_name msg
1 2 master 3 john hi how are you?
2 3 john 2 master fine
3 2 master 3 john hi
Here is my code conversation
<?php
if (isset($_GET['to_id'])) {
$from_id = $_GET['to_id'];
}
if (isset($_GET['to_name'])) {
$from_name = $_GET['to_name'];
}
if (isset($_SESSION['userid'])) {
$to_id = $_SESSION['userid'];
}
require_once"config.php";
if ($stmt = $con->prepare("SELECT * from inbox where from_id=? and from_name=? and to_id=? ")){
$stmt->bind_param('sss', $from_id,$from_name,$to_id);
$stmt->execute();
}
$result = $stmt->get_result();
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
?>
<div class="msg">
<?php echo $row['from_name'];?>
<?php echo $row['msg'];?>
<?php
}
}
?>
</div>
output image here
check this code
<?php
if (isset($_GET['to_id'])) {
$from_id1 = $_GET['to_id'];
}
if (isset($_GET['to_name'])) {
$from_name1 = $_GET['to_name'];
}
if (isset($_SESSION['userid'])) {
$to_id1 = $_SESSION['userid'];
}
require_once"config.php";
if ($stmt = $con->prepare("SELECT * from inbox where (from_id='2' and to_id='3' and from_name ='jhon') || (from_id='3' and to_id='2')")){
$stmt->bind_param('sss', $from_id,$from_name,$to_id);
$stmt->execute();
}
$result = $stmt->get_result();
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
?>
<div class="msg">
<?php echo $row['from_name'];?>
<?php echo $row['msg'];?>
<?php
}
}
?>
</div>

Execute query update with form from a query

I am trying to create a button on my user list page to delete that row, or make that user an admin.
Here is the info for the user query and html:
<?php
$query = "SELECT * FROM users";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
$rows = $stmt->fetchAll();
?>
<?php foreach($rows as $row) : ?>
<?php
if($row['usertype'] == 2) {
$usertype = "<span style='color:#F7FE2E;'>Donator</span>";
} elseif($row['usertype'] == 3) {
$usertype = "<span style='color:red;'>Admin</span>";
} elseif($row['usertype'] == 4) {
$usertype = "<span style='color:orange;'>Owner</span>";
} else {
$usertype = "<span style='color:#585858;'>Normal</span>";
}
?>
<tr>
<!--<td><?php echo $row['id']; ?></td>-->
<td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8');?></td>
<!--<td><?php echo htmlentities($row['email'], ENT_QUOTES, 'UTF-8');?></td>-->
<td><?php echo htmlentities($row['steamid'], ENT_QUOTES, 'UTF-8');?></td>
<td><?php echo $usertype?></td>
<td><form action="" method="post">
<input type="submit" name="admin" value="Promote" />
</form></td>
</tr>
<?php endforeach; ?>
And the code where I prepare and execute my update query:
if(!empty($_POST['admin']))
{
$query = "UPDATE `users` SET `usertype` = '3' WHERE `id` = " . $row['id'];
// $query_params = array(':id' => $row['id']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
}
Unfortunately I when I run this current setup, it updates the very last row. To further ask what I am looking for, is I have a list of users:
where "admin_b" is a button that forced $_POST['admin']
Billy admin_b
Bob admin_b
Jill admin_b
Jack admin_b
UPDATE:
So in my form I have an input with <input type="hidden" name="id" value="<?php $row['id']; ?>" /> and added this to my SQL $query = "UPDATE users SET usertype = '3' WHERE id = :id"; $query_params = array(':id' => $_POST['id']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex)
{
die("An Error has occured. Please contact the server administrator for assistance.");
}
send an id with $_POST request, now you are always update user with id = $row['id']
WHERE `id` = " . $row['id'];
row[id]edit?=edit.php= ...
and let's say you have list all the members and beside them is an href, the code above will execute, it will display let's say Billy?edit.php=1, wherein 1 is his primary key, then for the next, when you scroll the cursor to the next href of the next user, Jim, it will display, Jim?edit.php=2, in your edit.php,
if(isset($_POST['edit])){
code goes here to make the user an admin..
You can also make an href for the delete, similar to this edit..
This is just an idea/hint that I can give to you, but your problem can be solved in many different ways, it just depends on your approach on how you could do it :D goodluck.

A Better Way for No Results Returned?

I have a very simple search page running a query for one table in a DB. I have the query and fetch working. But if it doesn't find any matches to the term the user put in then I need it to say "No Rows Returned".
Here is my PHP CODE:
<?php
include('./includes/dbConnection.php');
$result = null;
if (isset($_GET['submit'])) {
// connect to database
$conn = dbConnect('localhost', 'db_admin', 'kfor.com', 'receiving');
// query the database
$stmt = $conn->stmt_init();
$searchTerm = "SELECT * FROM inventory WHERE pallet = {$_GET['pallet_id']}";
$result = $conn->query($searchTerm);
}
?>
Here is the PHP displaying the results and errors:
<?php
if ($result != null) {
if (!empty($result)) {
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row['pallet']; ?></td>
<td><?php echo $row['serial']; ?></td>
</tr>
<?php
}
}
} else {
echo "No Results";
}
?>
Is there a better way to display "No Results Returned"? Right now it's just displaying that error upon refresh because $result does equal null.
Thanks for any help!
Remove $result = null;, it's not needed. You can check num_rows returned your query.
<?php
include('./includes/dbConnection.php');
if (isset($_GET['submit'])) {
// connect to database
$conn = dbConnect('localhost', 'db_admin', 'kfor.com', 'receiving');
$_GET['pallet_id'] = addslashes($_GET['pallet_id']);
// query the database
$stmt = $conn->stmt_init();
$searchTerm = "SELECT * FROM inventory WHERE pallet = {$_GET['pallet_id']}";
$result = $conn->query($searchTerm);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row['pallet']; ?></td>
<td><?php echo $row['serial']; ?></td>
</tr>
<?php
}
} else {
echo "No Results Returned";
}
}
?>

Foreach invalid argument

I am creating a search function that will allow a user to search for a house in my database by postcode initially. The function can be seen below, when the function is executed and finds a true statement I get no errors however when I execute the search and I get a no fields been returned I am left with this error:
No Records Found
Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/undergradpad/search.php on line 26
I want it to display No Records Found however I don't know how I should correct the above error.
search.php:
<table width="500" border="1" cellpadding="5">
<tr>
<th width="16" scope="row">id</th>
<td width="95">bedrooms</td>
<td width="140">description</td>
<td width="104">roadname</td>
<td width="71">postcode</td>
</tr>
<?php
require("classes/class.House.inc");
$obj = new House();
$obj->search($_POST['term']);
foreach($obj->data as $val){
extract($val);
?>
<tr>
<td scope="row"><?php echo $id; ?></td>
<td><?php echo $bedrooms; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $roadname; ?></td>
<td><?php echo $postcode; ?></td>
</tr>
<?php
}
?>
</table>
classes/class.House.inc:
<?php
include("connect/class.Database.inc");
class House extends Database {
public function read(){
$query = "SELECT * FROM houses";
$result = $this->mysqli->query($query);
$num_result = $result->num_rows;
if($num_result > 0){
while($rows =$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
}
}
public function search ($term){
$query = "SELECT * FROM houses WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
$result = $this->mysqli->query($query);
$num_result = $result->num_rows;
if($num_result > 0){
while($rows =$result->fetch_assoc()){
$this->data[]=$rows;
//print_r($rows);
}
return $this->data;
} else{
echo 'No Records Found';
}
}
}
?>
in this variable ($obj->data) you just get null data.
First check if not empty and than use foreach and don't have error if yout method don't return null data
just check if (!empty($obj->data)
{
foreach code
}
$obj is a House object. It has no $data property, even if you use it. The search method sets this property, but only if records are found. If no records are found, the method echoes a value.
I would change it like this: Instead of echoing an error, make the method return false:
public function search ($term){
$query = "SELECT * FROM houses WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
$result = $this->mysqli->query($query);
$data = false;
$num_result = $result->num_rows;
while($row =$result->fetch_assoc()){
$data[]=$row;
}
return $data;
}
Now, the function return an array of false if there is no data. You can now use it like this:
$obj = new House();
if ($data = $obj->search($_POST['term']))
{
foreach($obj->data as $val){
extract($val);
}
}
The changes I made:
- No longer set data as a property, since you also return it. You can still do that, if you like, but I think it's confusing to do both.
- Return false if there's no data.
- Change the variable rows to row, since it only contains one row.
if(is_array($obj->data)){
foreach code
}
else{
no record
}

Categories