I am having an issue with MySQL data not being displayed via PHP
Below is the code which the data should be outputted into:
THIS IS individual_item_page.php
<?php
if (isset($_GET['suburb']))
{
$_SESSION["dog_park"] = $_GET['suburb'];
}
elseif (isset($_GET['keyword']))
{
$_SESSION["dog_park"] = $_GET['keyword'];
}
else
{
$_SESSION["dog_park"] = $_GET['rating'] ;
}
?>
<h1><?php echo $_SESSION["dog_park"]; ?></h1>
<table border="1" cellspacing="5" cellpadding="5" width="100%">
<thead>
<tr>
<th>Park Name</th>
<th>Street</th>
<th>Suburb</th>
<th>Dog Park Area (m2)</th>
</tr>
</thead>
<tbody>
<?php
$result = $conn->prepare("SELECT * FROM dog_parks.items where suburb = ?");
$result->execute(array($_SESSION['dog_park']));
for($i=0; $row = $result->fetch(); $i++){
?>
<tr>
<td><label><?php echo $row['Park_Name']; ?></label></td>
<td><label><?php echo $row['Street']; ?></label></td>
<td><label><?php echo $row['Suburb']; ?></label></td>
<td><label><?php echo $row['Dog_Park_Area_(m2)']; ?></label></td>
</tr>
<?php } ?>
</tbody>
</table>
Below is the output page after the code has been executed:
(No data)
A basic overview of how the page is meant to work is,
I have 3 search types via
keyword
suburb
rating
If I want to search for a dog park by suburb I would select a suburb from the drop down box. (Code at bottom of page)
A table would then display the dog parks in that suburb/area which I would then click on one of those parks displayed (Hyperlinked),
which will take me to the page I am having issues with, 'individual_item_page.php'
Below is the code for the suburb search page which then has a hyperlink to the 'individual_item_page.php' where the issue is..
THIS IS SUBURB SEARCH PAGE
<table class="center"> <!-- Creating a table with the class of 'center' -->
<!-- DROP DOWN BOX -->
<?php
$SUBURB = $_POST['suburb'];
$stmt = $conn->prepare("SELECT dog_park_name from items where suburb='$SUBURB'");
$stmt->execute();
for($i=0; $row = $stmt->fetch(); ){
$_SESSION["dog_park".$i] = $row[0];
?>
<!-- DISPLAY RESULTS -->
<tr> <!-- Adding the first table row -->
<th>Dog Park</th> <!-- Adding the second table header -->
</tr>
<tr> <!-- Adding the second table row -->
<td><a href="individual_item_page.php?suburb='<?php echo $row[$i] ?>' " ><?php echo $row[$i] ?></a></td> <!-- Add the second cell on the second row -->
</tr>
<?php }
?>
</table>
This issue has baffled me for many hours now, any help would be appreciated.
On individual_item_page.php, you have a couple of things going on:
You test for the presence of the first 2 GET variables you may be setting $_SESSION["dog_park"] to, but you fail to test for the third GET variable, $_GET['rating'].
Your SQL statement on that page is searching for a suburb, assuming that $_SESSION["dog_park"] was set to a suburb, despite the fact it may be set to $_GET['keyword'] or $_GET['rating']. Also, I'm not sure why you are binding $_SESSION['dog park'] as an array parameter in your $result->execute() statement.
On the suburb search page you are searching the table items but on the individual search page you are searching dog_parks.items. Was this intentional?
Important Note: On your suburb search page, you use a prepared statement but manually add a user entered variable instead of binding it, which defeats the protection supplied by binding parameters, which is to prevent user-entered data from being directly added to SQL statements.
Related
I have a MySql database which has users and each user gets a grade see below:
ID NAME GRADE
1 Sean 10
2 Sarah 15
3 Seo 12
4 Ste 32
Basically, I want to be able to dynamically print out whats stored in the database and add a text input box which enables me to enter in grades which are stored for each individual person. I then want this grade to be stored in the database for the user. Is this possible?
I have code which prints out the users but doesn't include a text box
<table style="width:50%" style = "background-color: transparent;">
<tr>
<th>ID</th>
<th>NAME</th>
<th>GRADE</th>
</tr>
<?php
$sql = "SELECT id, name, grade FROM students";
$result = $conn -> query ($sql);
if($result -> num_rows >0){
//output data of each row
while($row = $result -> fetch_assoc()){
?>
<tr>
<td> <?php echo $row["id"] ?> </td>
<td> <?php echo $row["name"] ?> </td>
<td> <?php echo $row["grade"] ?> </td>
</tr>
?>
</table>
Research a bit on HTML forms here
HTML Forms
You can either use post or get methods for the form to send the values to PHP.
After you have set up your form you can simply use the variables $_GET[formvariable] if you are using get or
$_POST[formvariable] if you are using post.
You can then use mysql to update values in the database when the form is submitted.
Im sorry if this has been answered before but I am new to PHP and MySQL and I can't figure this out.
Pretty much every time I alter my code to include an array I get a fatal error. What I am trying to do is display all the data in 3 columns from my table.
I have my site set up where you log in and I store that user's name as a "code" in a session. I have a table that has multiple user form entries that are differentiated by the user's code because in my form, I grab the code as a hidden field and add it to the entry in the table.
So far I have been able to isolate those entries by the users code, in one column I have the sum of all of the user's numerical data and I am able to echo this as a total.
I want the other 3 columns to display all the values in their columns and for each value have a line break in between them. And I am trying to print or echo these results in specific parts on a confirmation page.
I have seen examples with PDO using fetch_all and other examples of storing arrays but I can't seem to figure it out with my existing code.
Here is my existing code:
<?php
$user = *****;
$pass = *****;
$dbh = new PDO('mysql:host=localhost;dbname=*****', $user, $pass);
$stmt = $dbh->prepare("SELECT sum(price),part_number,location,price FROM products WHERE code = :usercode");
$stmt->bindParam(':usercode', $_SESSION['MM_Username']);
if ($stmt->execute()) {
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>
And here is where I want to display the results:
<table style="margin:0 auto;" cellspacing="7" width="100%">
<tbody>
<tr>
<td><?php echo $user['part_number']; ?></td><!--all column values-->
<td><?php echo $user['location']; ?></td><!--all column values-->
<td><?php echo $user['price']; ?></td><!--all column values-->
<td><?php echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
</tbody>
</table>
Try like this:
<table style="margin:0 auto;" cellspacing="7" width="100%">
<tbody>
if ($stmt->execute()) {
while($user = $stmt->fetch( PDO::FETCH_ASSOC )){
<tr>
<td><? echo $user['part_number']; ?></td><!--all column values-->
<td><? echo $user['location']; ?></td><!--all column values-->
<td><? echo $user['price']; ?></td><!--all column values-->
<td><? echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
}
}
</tbody>
</table>
There are a few things in your question that jumped out at me.
It looks like you're attempting to display both raw data (each row) and aggregate data (the sum of prices). It can be simpler to fetch the information separately instead of in the same request.
You had mentioned fetch_all in PDO, but the method is fetchAll.
Instead of working with PDO within the HTML (like iterating through while calling fetch), write code so that you're simply iterating over an array.
Based on your description of the problem, it sounds like you want to separate the total price from the raw data, so you can reduce your table down to three columns and use the table footer to show the total price.
Based on those, I have the following solution that
Separates the calls to get data into descriptive functions
Use money_format to better display prices
Removes any database-specific manipulation from the view itself.
<?php
function getTotalPriceForUser(PDO $database_handler, $user_code)
{
// If no rows are returned, COALESCE is used so that we can specify a default
// value. In this particular case, if there aren't any products that would
// match, we'd still get a result with a value of 0.
$sql = 'SELECT COALESCE(SUM(price), 0) FROM products WHERE code = ?';
$stmt = $database_handler->prepare($sql);
$stmt->execute(array($user_code));
// This fetches the first row of the result; the result is given as an array with numerical keys.
$result = $stmt->fetch(PDO::FETCH_NUM);
// [0] refers to the first column
return $result[0];
}
function getProductsForUser(PDO $database_handler, $user_code)
{
$sql = 'SELECT part_number, location, price FROM products WHERE code = ?';
$stmt = $database_handler->prepare($sql);
$stmt->execute(array($user_code));
// fetchAll returns all rows, with each row being an associative array (where part_number, location and price are the keys)
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// Set up the database information
$user = '*****';
$pass = '*****';
$dbh = new PDO('mysql:host=localhost;dbname=*****', $user, $pass);
// money_format to use the below money formatting; this makes sure there's a dollar sign to represent USD, for example
setlocale(LC_MONETARY, 'en_US.UTF-8');
// Store $_SESSION['MM_Username'] in a local variable
$user_code = $_SESSION['MM_Username'];
// Get the list of products associated with this user code
$products = getProductsForUser($dbh, $user_code);
// Get the total cost of the products
$total_cost = getTotalPriceForUser($dbh, $user_code);
?>
<table style="margin:0 auto;" cellspacing="7" width="100%">
<thead>
<tr>
<th>Part Number</th>
<th>Location</th>
<th>Cost</th>
</tr>
</thead>
<tfoot>
<tr>
<td style="text-align: right" colspan="2">Total:</td>
<td style="text-align: right; border-top: 1px solid #999"><?= money_format('%.2n', $total_cost) ?></td>
</tr>
</tfoot>
<tbody>
<?php foreach($products as $product): ?>
<tr>
<td><?= $product['part_number'] ?></td>
<td><?= $product['location'] ?></td>
<td style="text-align: right"><?= money_format('%.2n', $product['price']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Change to this
<? echo
to
<?php echo
Try this:
...
$keys = array_keys($user);
foreach ($keys as $k) :
?>
<td><?= $user[$k]?></td>
<?php endforeach?>
<table>
<tbody>
if ($stmt->execute()) {
while($user = $stmt->fetch( PDO::FETCH_ASSOC )){
<tr>
<td><?php echo $user['part_number']; ?></td><!--all column values-->
<td><?php echo $user['location']; ?></td><!--all column values-->
<td><?php echo $user['price']; ?></td><!--all column values-->
<td><?php echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
}
}
</tbody>
</table>
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I am trying to select data from mySQL database,
I execute the following code:
<?php $_SESSION["dog_park"] = $_GET['keyword'] ?>
<div class="review"> <!-- Creating a div with the class 'review -->
<!-- but POST varibale in here for dog park name -->
<h1><?php echo $_SESSION["dog_park"]; ?></h1>
<table border="1" cellspacing="5" cellpadding="5" width="100%">
<thead>
<tr>
<th>Park Name</th>
<th>Street</th>
<th>Suburb</th>
<th>Dog Park Area (m2)</th>
</tr>
</thead>
<tbody>
<?php
$result = $conn->prepare("SELECT * FROM dog_parks.items where suburb = '$_SESSION[dog_park]'");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<tr>
<td><label><?php echo $row['Park_Name']; ?></label></td>
<td><label><?php echo $row['Street']; ?></label></td>
<td><label><?php echo $row['Suburb']; ?></label></td>
<td><label><?php echo $row['Dog_Park_Area_(m2)']; ?></label></td>
</tr>
<?php } ?>
</tbody>
</table>
When that script executes it displays the following error:
It has something to do with the session variable, if i enter a static value for the mySQL query it will display table data correctly, but fail when the $_SESSION variable is present.
That string contains quotes, that breaks your SQL string encapsulation. Use the prepared statements as they are meant to be, parameterized, and the issue will be gone.
$result = $conn->prepare("SELECT * FROM dog_parks.items where suburb = ?");
$result->execute(array($_SESSION[dog_park]));
You can read more:
http://php.net/manual/en/pdo.prepared-statements.php
How can I prevent SQL injection in PHP?
As is your query was running as:
SELECT * FROM dog_parks.items where suburb = ''Tramway''
(roughly, if you'd included text of error message, not image I could supply real query)
Which is invalid because '' is what you are comparing. The Tramway'' it doesn't know what to do with. This coincidentally is how SQL injections occur.
This is my first posting in SO, my apologize if I opened an existing question. As I couldn't find the result in Google. Sorry to said but I'm still fresh in PHP PDO and in learning stage.
Back to my question, currently I'm building a customer visit logs from my wife but I'm stuck with the result. I have two table which one stores the customer information and another table store the visit details. I uploaded the test table at here: SQL Fiddle
And below is my current coding and I'm using PHP PDO while
<?php
require_once 'dbconnect.php';
$p_id = $_GET['name'];
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = "SELECT customer.fname, customer.lname, customer.gender, services.treatment, services.date
FROM customer LEFT JOIN services
ON customer.id = services.customer_id
WHERE customer.slug LIKE :id";
$q = $conn->prepare($sql);
$q->execute(array('id' => $p_id));
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="container">
<h1>Customer Record</h1>
Name: <br />
Gender: <br />
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Customer Name</th>
<th>Customer Gender</th>
<th>Treatment</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php while ($r = $q->fetch()): ?>
<tr>
<td><?php echo htmlspecialchars($r['fname']), ' ', htmlspecialchars($r['lname'])?></td>
<td><?php echo htmlspecialchars($r['gender']); ?></td>
<td><?php echo htmlspecialchars($r['treatment']); ?></td>
<td><?php echo htmlspecialchars($r['date']); ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
Seach Again
</body>
</div>
</html>
And I achieve as what SQL Fiddle result, but what I wanted is, the name and gender is not keep repeating.
I attached together with the screenshot:
Screenshot
What I want is as per the screenshot image, Name: John Doe and Gender: Male, should be on top and not keep on repeating while the table below show all the visit details. I tried to modified the code but it seems it don't really work out.
Please advise me as I'm really out of idea how to achieve what I want.
Thank you so much.
Since you do a LEFT JOIN in your SQL query, you know ahead of time that all of the fname, lname and gender values returned by $q->fetch() are going to be for the same customer.slug, right? So you can count on that.
My suggestion would be to instead use the fetchAll() function to get an array of all records for customer.slug, and then render that in your view. For example (haven't tested this) you could add the following after $q->setFetchMode(PDO::FETCH_ASSOC); ...
$cs = $q->fetchAll(); // customer services join
Then, in your <html> view, you could do something like the following:
<h1>Customer Record</h1>
Name: <?php echo htmlspecialchars($cs[0]['fname'].' '.$cs[0]['lname']); ?> <br />
Gender: <?php echo htmlspecialchars($cs[0]['gender']); ?> <br />
<table>
<thead>
<tr>
<th>Treatment</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php foreach($cs as $r): ?>
<tr>
<td><?php echo htmlspecialchars($r['treatment']); ?></td>
<td><?php echo htmlspecialchars($r['date']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
Of course, it might also be a good idea to check to see that any records were returned by your query and display a "not found" message if not. After all, $cs[0] might be empty, giving you a PHP error.
I will have to mention first that I have searched for a Google and stackoverflow and anywhere else, as well as tried to use scripts given in forums and write my own ones, but nothing worked for me. I am completely stuck.
So, all I try to do is to write a script that will delete checked rows from MySQL table. Here is my HTML written inside of a PHP file:
<tr class="noP">
<td class="check"><input class="checkbox" name="checkbox[]" type="checkbox" value="'.$row["PID"].'"/></td>
<td class="id">'.$row['PID'].'</th>
<td>'.$row["name"].'</th>
<td>'.$row["surname"].'</th>
<td>'.$row["pcode"].'</th>
<td class="address">'.$row["address"].'</th>
<td class="email">'.$row["email"].'</th>
<td>'.$row["phone"].'</th>
<td class="education">'.$row["education"].'</th>
<td class="remarks">'.$row["remarks"].'</th>
</tr>
for here $row = mysql_fetch_assoc($qParts);, so this array is just a collector of field values from MySQL DB.
Basically, all I try to do is just a table with all the participants listed with ability to delete selected ones.
I would highly appreciate any help provided. Thank you!
This should help you:
foreach($_REQUEST['checkbox'] as $val)
$delIds = intval($val);
$delSql = implode($delIds, ",");
mysql_query("DELETE FROM table WHERE PID IN ($delSql)");
So, that takes your input array from $_GET/$_POST, sanitises it (a little), then implodes it to get a list of IDs (e.g. 5, 7, 9, 13). It then feeds that into an SQL statement, matching on those IDs using the IN operator.
Note that you should do this using prepared statements or similar. It's been a while though, so I can't write them off-hand, but this should give you the gist of it.
To do this using PDO, have a look here. It's a bit more complex, since you need to dynamically create the placeholders, but it should then work the same.
Reference - frequently asked questions about PDO
I think I can help you out. I had the same issue during my semester project. The problem can be solved using HTML and PHP alone.
I am assuming that PID is the primary key in your table. The trick here is to put the entire table in a form so that it looks like this:
<form action="/*NAME OF THIS PAGE HERE*/.php" method="POST">
<?php
if(isset($_POST['delete'])) //THE NAME OF THE BUTTON IS delete.
{
foreach ($_POST["checkbox"] as $id){
$de1 = "DELETE FROM //table-name WHERE PID='$id'";
if(mysqli_query($conn, $de1))
echo "<b>Deletion Successful. </b>";
else
echo "ERROR: Could not execute";
}
}
if(isset($_POST['delete'])){
echo"<b>Please make a selection to complete this operation.</b>";
}
?>
</br>
<!-- below you will see that I had placed an image as the delete button and stated its styles -->
<button type="submit" name="delete" value="delete" style="float:right;border:none; background:none;">
<img style="width:55px; height:55px;margin-left:10px; margin-bottom:6px; float:left;" src="images/del.png">
</button>
<table>
<thead>
<tr>
<th>#</th>
<th>PID</th>
<th>NAME</th>
<th>SURNAME</th>
<!--REST OF THE TABLE HEADINGS HERE -->
</tr>
<?php $fqn="SELECT * FROM //table-name here;
$fqn_run=mysqli_query($conn,$fqn);
while($row=mysqli_fetch_array($fqn_run)):?>
</thead>
<tbody>
<tr class="noP">
<td class="check"><input class="checkbox" name="checkbox[]" type="checkbox" value="<?php echo $row["PID"];?>"></td>
<td><?php echo $row['PID'];?></td>
<td><?php echo $row["name"];?></td>
<td><?php echo $row["surname"];?></td>
<!-- REST OF THE ROWS HERE -->
</tr><?php endwhile;?>
</tbody>
</table>
</div>
</div>
</form>
Hope this helps you.