Why data from my database is not displaying? - php

Hey guys I'm pretty new at PHP, I'm not too sure what Ive done wrong and I've been working at this for a few hours and cant seem to see whats wrong with it (there's no error which makes things more fun) what it actually does, it runs fine but it does not display the data from my database and only shows up with the column headers and that's it.
I would appreciate any advice at this point. What my code does is that it grabs some information 'staffID' from a form and uses that to display data that associates with it (like a search function) I'm using a 'join' function just for practice with the database I'm using.
As I said I'm completely new to this so this so I could be completely wrong with my code
<?php $staffidstr = $_GET["staffID"];
$conn = mysql_connect("xxxxxxx", "xxxxxx", "xxxxxxx");
mysql_select_db("xxxxxxxx", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "SELECT orderID, orderDate, shippingDate, staffName
FROM purchase, staff
WHERE purchase.staffID = staff.staffID
AND staff.staffID = '%$staffidstr%'
ORDER BY staff.staffName";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
?>
<?php echo "$staffidstr"; ?>
<table border="1" summary="Purchase Details">
<tr>
<th>Order ID</th>
<th>Order Date</th>
<th>Shipping Date </th>
<th>Staff Name</th>
</tr>
<?php
while ($row = mysql_fetch_array($rs)) { ?>
<tr>
<td><?php echo $row["orderID"]?></td>
<td><?php echo $row["orderDate"]?></td>
<td><?php echo $row["shippingDate"]?></td>
<td><?php echo $row["staffName"]?></td>
</tr>
<?php }
mysql_close($conn); ?>

I'm pretty sure it's following part of the WHERE clause
staff.staffID = '%$staffidstr%'
That should be most likely
staff.staffID = '$staffidstr'
The % character has no special meaning using the = operator, so your query will return not a single row.

Related

How to delete the entire row in the database from html table instead of deleting entire table in the database

I have added delete button to the html table on each row and when clicked on delete button the entire row should be deleted but instead whole table in the database is being deleted.
here is my code for admin.php
<div class="container mt-3 ml-3">
<table class="table">
<thead>
<tr>
<th>S.No</th>
<th>Name</th>
<th>Email</th>
<th>Rating</th>
<th>Review</th>
<th>Image</th>
<th>Suggestion</th>
<th>NPS</th>
<th>Delete</th>
</tr>
</thead>
<tbody class="table-warning">
<?php
include 'database_conn.php'; // makes db connection
$sql = "SELECT feedbackID, name, email, rating, review, image, suggestion, nps
FROM feedback
ORDER BY feedbackID Desc";
$queryResult = $dbConn->query($sql);
// Check for and handle query failure
if($queryResult === false) {
echo "<p>Query failed: ".$dbConn->error."</p>\n";
exit;
}
// Otherwise fetch all the rows returned by the query one by one
else {
if ($queryResult->num_rows > 0) {
while ($rowObj = $queryResult->fetch_object()) {
echo "<tr>
<td>{$rowObj->feedbackID}</td>
<td>{$rowObj->name}</td>
<td>{$rowObj->email}</td>
<td>{$rowObj->rating}</td>
<td>{$rowObj->review}</td>
<td>{$rowObj->image}</td>
<td>{$rowObj->suggestion}</td>
<td>{$rowObj->nps}</td>
<td><a id='delete' href=delete.php?id={$rowObj->feedbackID}>Delete</a></td>
";
}
}
}
?>
</tr>
</tbody>
</table>
</div>
And here my code for delete.php. I think there is something wrong in the sql query I made.
<?php
include 'database_conn.php'; // makes db connection
$sql = "DELETE FROM feedback WHERE feedbackID=feedbackID";
if ($dbConn->query($sql) === TRUE) {
echo "Record deleted successfully. Please go to Customer Feedback Page by clicking"; echo "<a href='http://unn-w18031735.newnumyspace.co.uk/feedback/admin.php'> here</a>";
} else {
echo "Error deleting record: " . $dbConn->error;
}
$dbConn->close();
?>
This is wrong:
DELETE FROM feedback WHERE feedbackID=feedbackID
it is always true as it will be equal to itself.
What you want to use is parameters here. $_GET['id'] is where the id is.
If you use PDO, something like
$stmt = $dbConn->prepare("DELETE FROM feedback WHERE feedbackID=:feedback_id");
$stmt->execute(['feedback_id' => $_GET['id']]);
For mysqli,
$stmt = $mysqli->prepare("DELETE FROM feedback WHERE feedbackID=?");
$stmt->bind_param("i",$_GET['id']);
$stmt->execute();
this solution in delete.php has worked.
$feedbackID = $_GET["id"];
$sql = ("DELETE FROM feedback WHERE feedbackID= '$feedbackID'");

Table with database values and user input

So I've been wrestling with this issue on and off for quite a while now, and just like driving around lost in a strange city, I am finally breaking down for direction! I am developing table with values from a database, but also need a column that will process user input. I have been able to display the table but my input is not updating the necessary database element. Code below:
<?php
include("pogsatbetbuddy.inc.php");
$cxn=mysqli_connect($host,$username,$password,$db_name)
or die("Did Not Connect");
$query="SELECT * FROM $tbl2_name ORDER BY $tbl2_name.$col_name ASC";
$result=mysqli_query($cxn,$query)
or die("Query Not Working");
echo"<table border='1'
<form name='payments' action='' method='POST'>
<tr>
<td class='update' colspan='5'>
<button data-theme='b' id='submit' type='submit'>Update</button>
</td>
</tr>
<tr>
<th class='profile'>Last Name</th>
<th class='profile'>First Name</th>
<th class='profile'>Saturday Payment Owing</th>
<th class='profile'>Enter Payment</th>
<th class='profile'>Saturday Balance</th>
</tr>";
while ($row=mysqli_fetch_assoc($result))
{
extract ($row);
echo"<tr>
<td class='profile'>$lastname</td>
<td class='profile'>$firstname</td>
<td class='profile'>$owingsat</td>
<td class='profile'><input type='number' name='paidsat' value=''/></td>
<td class='profile'>$owingsat-$paidsat</td>
</tr>";
}
echo "</form>";
echo "</table>";
This displays the table in the way I want. Having worked through the results of the following code, it seems that I am returning a null value, so I am thinking I have an issue with either the form action or the submit Update button, but can not find the solution after much experimentation and searching. Balance of code below:
if(isset($_POST['paidsat']))
{
$paidsat = $_POST['paidsat'];
if(($paidsat) != null)
{
$stmt = $cxn->prepare("UPDATE $tbl2_name SET paidsat = ? WHERE firstname=? and lastname=?");
$stmt->bind_param('sss', $paidsat, $firstname, $lastname);
$status = $stmt->execute();
if($status === true) //To check if the execute was successful
{
echo("<p class='click'>You have successfully added the payment for $firstname $lastname\n<br /></p>");
}
}
else echo"Not Successful";
}
else echo "<p class='click'>Make your changes as required</p>";
mysqli_close($cxn);
Everything comes to a crashing halt at the second if statement.....or should I say, although things look pretty, they don't function! Thanks in advance, appreciate any help!
Be sure you have a proper value for $tbl2_name checking
var_dump($tbl2_name)
in your code before the update
and for debug try using a string concatenation like
"UPDATE " . $tbl2_name . " SET paidsat = ? WHERE firstname=? and lastname=?";
and try use
if( $paidsat != NULL )
and last check if you have proper value for update
paidsat = ? WHERE firstname=? and lastname=?
Try
var_dump( $paidsat);
var_dump( $firstname);
var_dump( $lastname);
and build a proper select for test if you value math the rows you think and
test this select in you db console

How to print out a table from mySQL database inside a html/php page

i am trying to print out this table from phpmyadmin to my html/php page as a normal table. this is my coding for the page
Any help would be appreciated
Thanks
Looks like You were Using PDO , and all of a sudden you jump into old data fetching technique using mysql_*
My advice is to stick with PDO structure . SO you have to some little things
on line 6 use
$stmt->rowCount();
to get user row
then use
$data = $stmt->fetchAll();
to get database rows , You'll get an object .
Now You just need to loop through object for example
foreach ( $data as $rows ){
echo $rows->users;
}
Try this code:
<?php
$db = new mysqli("localhost", "root", "", "hangman");
?>
<table border="1">
<tr>
<td>User</td>
<td>Score</td>
</tr>
<tr>
<?php
$sql = "SELECT * FROM usernames";
$result = $db-query($sql);
while($row = mysqli_fetch_assoc($result)) {
?>
<td><?php echo $row['users']; ?></td>
<td><?php echo $row['Scores']; ?></td>
<?php
}
?>
</tr>
</table>
give me a comment if any errors.

PHP echoing MySQL data into HTML table

So I'm trying to make a HTML table that gets data from a MySQL database and outputs it to the user. I'm doing so with PHP, which I'm extremely new to, so please excuse my messy code!
The code that I'm using is: braces for storm of "your code is awful!"
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = mysql_connect("localhost", "notarealuser", 'notmypassword');
for ($i = 1; $i <= 20; $i++) {
$items = ($mysqli->query("SELECT id FROM `items` WHERE id = $i"));
echo ("<tr>");
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['id'];
}</td>");
$items = ($mysqli->query("SELECT name FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['name'];
}</td>");
$items = ($mysqli->query("SELECT descrip FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['descrip'];
}</td>");
$items = ($mysqli->query("SELECT reward FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['reward'];
}</td>");
$items = ($mysqli->query("SELECT img FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['img'];
}</td>");
echo ("</tr>");
}
?>
</tbody>
</table>
However, this code is not working - it simply causes the page to output an immediate 500 Internal Server Error. IIS logs show it as a 500:0 - generic ISE. Any ideas?
You are mixing mysql and mysqli, not closing php code block and you are not selecting a database. Plus you don't have to run a query for each field
Try this:
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = new mysqli("host","user", "password", "database");
$execItems = $con->query("SELECT id, name, descrip, reward, img FROM `items` WHERE id BETWEEN 1 AND 20 ");
while($infoItems = $execItems->fetch_array()){
echo "
<tr>
<td>".$infoItems['id']."</td>
<td>".$infoItems['name']."</td>
<td>".$infoItems['descrip']."</td>
<td>".$infoItems['reward']."</td>
<td>".$infoItems['img']."</td>
</tr>
";
}
?>
</tbody>
</table>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = mysqli_connect("hostname","username",'password');
$sql= "SELECT * FROM `items` WHERE id <20 ";
$items = (mysqli_query($sql));
while ( $db_field = mysqli_fetch_assoc($items) ) {?>
<tr><td><?php echo $db_field['id'];?></td></tr>
<tr><td><?php echo $db_field['name'];?></td></tr>
<tr><td><?php echo $db_field['descrip'];?></td></tr>
<tr><td><?php echo $db_field['reward'];?></td></tr>
<tr><td><?php echo $db_field['img'];?></td></tr>
<?php}
</tbody>
</table>
Try these, not tested
Where is the question?
There's many problems with this code.
First, you are confused between PHP and HTML.
Code between is PHP. It's executed on the server, you can have loops and variables and assignments there. And if you want some HTML there you use "echo".
Code outside is HTML - it's sent to the browser as is.
Second - what you seem to be doing is querying each field separately. This is not how you work with SQL.
Here's more or less what you need to do:
//Query all rows from 1 to 20:
$items = $mysqli->query("SELECT id,name,descrip,reward,img FROM `items` WHERE id between 1 and 20");
//Go through rows
while ( $row = mysqli_fetch_assoc($items) )
{
echo "<tr><td>{$db_field['id']}</td>";
//echo the rest of the fields the same way
});
I'm going to go ahead and assume that the code isn't working and that's because there's several basic errors. I'd strongly suggest doing some hard reading around the topic of PHP, especially since you're using databases, which, if accessed with insecure code can pose major security risks.
Firstly, you've set-up your connection using the procedural mysql_connect function but then just a few lines down you've switched to object-orientation by trying to call the method mysqli::query on a non object as it was never instantiated during your connection.
http://php.net/manual/en/mysqli.construct.php
Secondly, PHP echo() doesn't require the parentheses. PHP sometimes describes it as a function but it's a language construct and the parentheses will cause problems if you try to parse multiple parameters.
http://php.net/manual/en/function.echo.php
Thirdly, you can't simply switch from HTML and PHP and vice-versa with informing the server/browser. If you wish to do this, you need to either concatenate...
echo "<td>".while($db_filed = mysqli_fetch_assoc($item)) {
print $db_field['id'];
}."</td>;
Or preferably (in my opinion it looks cleaner)
<td>
<?php
while($db_filed = mysqli_fetch_assoc($item)) {
print $db_field['id'];
}
?>
</td>
However, those examples are based on your code which is outputting each ID into the same cell which I don't think is your goal so you should be inserting the cells into the loop as well so that each ID belongs to its own cell. Furthermore, I'd recommend using echo over print (it's faster).
Something else that may not be a problem now but could evolve into one is that you've used a constant for you FOR loop. If you need to ever pull more than 20 rows from your table then you will have to manually increase this figure and if you're table has less than 20 rows you will receive an error because the loop will be trying to access table rows that don't exist.
I'm no PHP expert so some of my terminology might be incorrect but hopefully what knowledge I do have will be of use. Again, I'd strongly recommend getting a good knowledge of the language before using it.

Use a Drop Down Menu to Query A Database and Return the Results Without Leaving The Page

I have a page with some PHP that looks like this:
<table>
<thead>
<tr>
<th class="wheniwant">Date</th>
<th class="wheniwant">Income Amount</th>
<th class="wheniwant">Expense Amount</th>
</tr>
</thead>
<?php
//DB CONNECTION
$varDatePaid = ""; $varIncomePaid =""; $varExpensePaid = "";
$sql = mysql_query(
"
SELECT DATE_FORMAT(`date_paid`, '%Y-%m') `date_paid`,
SUM(CASE WHEN `categoryType` = 'Income' THEN `amount_paid` END) `IncomeAmount`,
SUM(CASE WHEN `categoryType` = 'Expense' THEN `amount_paid` END) `ExpenseAmount`
FROM `accounting`
GROUP BY DATE_FORMAT(`date_paid`, '%Y-%m')
"
);
while($row = mysql_fetch_array($sql))
{
$varDatePaid = $row['date_paid'];
$varIncomePaid = $row['IncomeAmount'];
$varExpensePaid = $row['ExpenseAmount'];
?>
<tr>
<td><?php echo $varDatePaid; ?></td>
<td><?php echo $varIncomePaid; ?></td>
<td><?php echo $varExpensePaid; ?></td>
</tr>
<?php
}
?>
</table>
This returns a table like:
I want to then add something:
$sql_query = "SELECT id, DATE_FORMAT(`date_paid`, '%Y') AS year FROM accounting GROUP BY year ORDER BY year DESC";
$result = mysql_query($sql_query) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
echo '<option value='. $row['year'] . '>'. $row['year'] . '</option>';
To create some sort of filter to limit the result to a particular year. How do I do this without leaving the page?
Ok so you are going to want to read up on AJAX over here. It's not very difficult and for the most part you can copy the code right off of that site. Alternatively depending on how much data you have and if you don't really want to learn something new, you could load the entire data set on page load and then use JS to just pick out the parts you want once they fill out the form. I would suggest the AJAX route.
Someone else mentioned something about external PHP scripts which I guess is possible but I'm not sure how that would work. I would assume that you have to use JS on your first page to make a cookie that says what you want, then you open a new tab or window where you perform your query and store the value as a cookie or session variable, then use JS to close that window when the query is done, and then use JS again to put the results of the query back onto the page. I suppose that would work but it seems like not the most efficient way to go about this.

Categories