Deleting database row via PHP - php

I've looked through the "recommendations" based on the title I placed this as and the topics either weren't answered or didn't relate to my situation (from what I could see).
I've got a PHP HTML page that calls information from a database and inputs it into a table. I've got a a tag ready for a delete function but I just can't seem to get it right. I was hoping someone here would be able to help me out.
These are all the relevant pages.
connection.php
<?php
try{
$handler = new PDO('mysql:host=127.0.0.1;dbname=data', 'root', 'root');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
?>
location1.php
<?php
include('connection.php');
$query = $handler->query('SELECT * FROM subsordered WHERE location ="location1"');
$delete = $handler->query('DELETE * FROM subsordered WHERE id = :id');
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<h1 align="center">Location 1</h1>
<table align="center" border="1" height="10%" width="80%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Desc</th>
<th>Location</th>
<th></th>
</tr>
<?php while($row = $query->fetch()){ '<tr>
<td align="center">';echo $row[''],'</td>
<td align="center">';echo $row['id'],'</td>
<td align="center">';echo $row['name'],'</td>
<td align="center">';echo $row['desc'],'</td>
<td align="center">';echo $row['location'],'</td>
<td align="center">Delete</td>
</tr>';} ?>
</table>
When I try to keep the mysql delete call in the first php section in location1 it breaks the page, I'm pretty sure it has something to do with the fact that I am assigning 2 calls to 1 function but I other than making a brand new page jsut for a single delete call I don't know what else to do

Try:
<?php
include('connection.php');
$query = $handler->query('SELECT * FROM subsordered WHERE location ="location1"');
if (isset($_GET["id"])) {
$delete = $handler->exec('DELETE FROM subsordered WHERE id = \'' . $_GET["id"] . '\'');
}
?>
This should work. Anyway, i would consider changing the code in order to prevent SQL injection (Check this)

I'm not so familiar with PDO but from what I see this line has a problem:
$delete = $handler->query('DELETE * FROM subsordered WHERE id = :id');
It should be this I think:
$delete = $handler->query('DELETE FROM subsordered WHERE id = :id');
Have a look at the example here: http://www.mustbebuilt.co.uk/php/insert-update-and-delete-with-pdo/

Related

PHP website search

I'm having trouble getting my php search project working properly, having followed a guide, I don't fully understand the guide/code. My search bar will allow me to search for jobs in the database, but currently it shows all jobs and filters the one you search.
Is it possible to display these jobs as links, where it will take you to another page and display the currently selected job.
Here is my current code:
<?php
require 'config.php';
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `job` WHERE CONCAT(`location`, `description`, `budget`, `duedate`,`title`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `job`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$conn = mysqli_connect("localhost", "root", "", "bid4myjob");
$filter_Result = mysqli_query($conn, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black;
}
</style>
</head>
<body>
<form action="php_html_table_data_filter.php" method="post">
<input type="text" name="valueToSearch" placeholder="Value To Search"><br><br>
<input type="submit" name="submit" value="Search"><br><br>
<table>
<tr>
<th>Title</th>
<th>Location</th>
<th>Description</th>
<th>Budget</th>
<th>Due date</th>
</tr>
<!-- populate table from mysql database -->
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['title'];?></td>
<td><?php echo $row['location'];?></td>
<td><?php echo $row['description'];?></td>
<td><?php echo $row['budget'];?></td>
<td><?php echo $row['duedate'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
Your problem is this line:
if(isset($_POST['search']))
There's no variable called "search" which will be submitted by your form, so its value will never be set, and this if block will never be entered. I suspect you've confused the "name" attribute which determines the variable's name in the POST array, with its value ("Search", in the case of your button). Try
if(isset($_POST['submit']))
instead.
See also my comments above about your security problems and aim to fix those a.s.a.p.

PHP PDO Table and seperate buttons

noob here. I am trying to create a table where I can put in separate buttons that link to my next .php page and to certain information from the next page tables. I have tried for hours and hours to get a style of table pdo that will allow me to add my own separate buttons with link to my next .php page.
But without adding one input href that creates a button for all of the rows.
Unless there is a way to add it to the single href section. But I have no idea. The links work but just point to the next page as a whole instead of choosing a table.
There are 3 tables on the next .php page, taken from mysql databases. Here is my index.php page. It is just basic for now until I can get the php code to work. I take it there is something to do with superglobals or sessions?? Thanks in advance.
<html>
<head>
<title>Blah</title>
<H1>Blah</H1>
<H2>Blah</H2>
<body>
<?php
include 'mystyles.css';
?>
<?php
$user = '123';
$pass = '456';
$db = new PDO( 'mysql:Myhost;dbname=123', $user, $pass );
$sql = "SELECT * FROM Production";
$query = $db->prepare( $sql );
$query->execute();
$results = $query->fetchAll( PDO::FETCH_ASSOC );
?>
<table class="table">
<tr>
<th>Title</th>
<th>Ticket Cost</th>
<th></th>
<?php
foreach( $results as $row ){
echo "<tr><td>";
echo $row['Title'];
echo "</td><td>";
echo $row['BasicTicketPrice'];
echo ('<td><a href="perf.php"><input type="submit" name="submit"
value="Register" class="register" /></a></td>');
echo "</tr>";
}
?>
</table>
</body>
</html>
One way is You need to pass the value to next page via GET ie in the URL
For eg:
....
This will result like ......
Once user clicks the link value will be passed to next page via GET, u can u use that value for computation
Sample
<html>
<head>
<title>Blah</title>
<H1>Blah</H1>
<H2>Blah</H2>
<body>
<?php
include 'mystyles.css';
?>
<?php
$user = '123';
$pass = '456';
$db = new PDO( 'mysql:Myhost;dbname=123', $user, $pass );
$sql = "SELECT * FROM Production";
$query = $db->prepare( $sql );
$query->execute();
$results = $query->fetchAll( PDO::FETCH_ASSOC );
?>
<table class="table">
<tr>
<th>Title</th>
<th>Ticket Cost</th>
<th></th>
<?php
foreach( $results as $row ){
echo "<tr><td>";
echo $row['Title'];
echo "</td><td>";
echo $row['BasicTicketPrice'];
echo ('<td><a href="perf.php?id=".$row['TicketId'].""><input type="submit" name="submit"
value="Register" class="register" /></a></td>');
echo "</tr>";
}
?>
</table>
</body>
</html>

PHP not displaying anything in MAMP

Im very new to PHP and was trying to get record information to display on a php page using the MAMP server environment.
The attributes are productID, productName, productDescription and productPrice.
I've been able to get really basic PHP to run fine but every time I open this php file, nothing displays, I was wandering if it might be to do with the location I placed the php file. It is currently in htdocs. would appreciate any help.
Thanks
<?php
//connection to db
mysql_connect('localhost', 'root', 'root');
//choosing db
mysql_select_db(primrose);
$sql= "SELECT * FROM products";
$records mysql_query(sql);
?>
<html>
<head>
<title>Product Data</title>
</head>
<body>
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<?php
//loops over each record and for each a new record is set into the variable products
while(products=mysql_fetch_assoc($records)){
echo "<tr>";
echo "<td>".$products['productName']."</td>";
echo "<td>".$products['productDescription']."</td>";
echo "</tr>";
} //end while
?>
</table>
</body>
</html>
This is because (I think) this line is bad:
mysql_select_db(primrose);
Add quotes around the name of db:
mysql_select_db("primrose");
Also this line:
$records mysql_query(sql);
change to
$records = mysql_query($sql);
and this:
while(products=mysql_fetch_assoc($records)){
to
while($products=mysql_fetch_assoc($records)){
NOTE 1:
Do not use mysql functions since, they are deprecatid. Use mysqli or PDO instead.
NOTE 2:
Let's turn on your error reporting with these two rows in the top of your PHP file:
error_reporting(E_ALL);
ini_set('display_errors', 1);
You have a lot of syntax errors. Let's use an IDE to identify them.
So your final code like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//connection to db
mysql_connect('localhost', 'root', 'root');
//choosing db
mysql_select_db("primrose");
$sql= "SELECT * FROM products";
$records = mysql_query($sql);
?>
<html>
<head>
<title>Product Data</title>
</head>
<body>
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<?php
//loops over each record and for each a new record is set into the variable products
while($products=mysql_fetch_assoc($records)){
echo "<tr>";
echo "<td>".$products['productName']."</td>";
echo "<td>".$products['productDescription']."</td>";
echo "</tr>";
} //end while
?>
</table>
</body>
</html>
Try setting error_reporting(E_ALL); to on just after to open'ed PHP.
If not, make sure that error reporting is turned on in your php.ini
http://php.net/manual/en/errorfunc.configuration.php

PHP PDO while doesn't achieve my desire end result

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.

HTML table with sql data in php (table row depend by sql columns)

Hello i got this sample data in sql
$data = array(
array('id' => '1','name' => 'name1','surname' => 'surname1'),
array('id' => '2','name' => 'name2','surname' => 'surname2'),
array('id' => '3','name' => 'name3','surname' => 'surname3'),
array('id' => '4','name' => 'name4','surname' => 'surname4')
);
I want to dispplay in in html table but my code didnt work :
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$select_data = "SELECT * FROM dane ORDER BY `id` DESC";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th align="left" valign="middle">id</th>
<th align="center" valign="middle">name</th>
<th align="center" valign="middle">surname</th>
</tr>
</thead>
<?php
$result = mysql_query($select_data);
while ($data = mysql_fetch_row($result)) {
}
?>
<tbody>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
</tbody>
</table>
</body>
</html>
But i wann't also that the numer of rows in html table depends by number of columns in sql table. For example in this case i want to display only three rows (three columns in sql table). When i add the column's to sql table i want to rows in html output table increses dynamicly.
Could someone help me with this code ?
Change your code to this:
<tbody>
<?php
$result = mysql_query($select_data);
while ($data = mysql_fetch_row($result)) {
?>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
<?php
}
?>
</tbody>
You are closing your while loop before displaying the results
You close your while-loop not correct:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$select_data = "SELECT * FROM dane ORDER BY `id` DESC";
$result = mysql_query($select_data);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th align="left" valign="middle">id</th>
<th align="center" valign="middle">name</th>
<th align="center" valign="middle">surname</th>
</tr>
</thead>
<tbody>
<?php while ($data = mysql_fetch_row($result)):?>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
<?php endwhile;?>
</tbody>
</table>
</body>
</html>
Using the the "while(cond):" and "endwhile;" command you can see better where something starts and where it ends than using the encapsulation with braces.
Please consider to switch your Database Wrapper from mysql_ to PDO or mysqli, since mysql is not anymore actively supported.
You could also use instead:
<?php echo $data['id']?>
rather the shortform:
<?=$data['id']?>
Which is also avaiable w/o php short open after 5.3 (I think it was 5.3)
If I understand your question correctly, you would like to have the number of returned rows match the number of columns in your table dane. The following code should do just that and I'm using mysqli which I strongly recommend. The mysql_query extension is deprecated as of PHP 5.5.0.
<?php
$db = new mysqli('localhost', 'root', '', 'test'); // server, user, pass, database
$table_name = 'dane'; // table
// Let's make sure we could establish a connection
if($db->connect_errno > 0){
die('Unable to connect to the database ' . $db->connect_error);
}
// Build our select to return column names only
$select_cols = "SELECT column_name FROM information_schema.columns WHERE table_name='$table_name'";
if(!$result = $db->query($select_cols)){
die('There was an error running the query.');
}
while($row = $result->fetch_assoc()){
$cols[] = $row['column_name']; // Store the columns to an array. It will be further used.
}
// Implode the column names to a comma delimited string to use in the next select. It's also a good practice not to use asterisk in your select statements
$table_headers = implode(',', $cols);
// Query for records with a limit to number columns in the $table_name
$select_data = "SELECT $table_headers FROM $table_name ORDER BY `id` DESC LIMIT 0 , $result->num_rows";
if(!$result = $db->query($select_data)){
die('There was an error running the query ' . $db->error);
}
while($row = $result->fetch_assoc()){
$data[] = $row; // Store the data into an array to be used in the html table
}
$db->close(); // Close our connection
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<?php foreach ($cols as $k) : // Loop through columns ?>
<th align="center" valign="middle"><?php echo $k; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach ($data as $k) : // Loop through each $data array() ?>
<tr>
<?php foreach ($k as $v) : // Let's display the records ?>
<td align="center" valign="middle"><?php echo $v; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
I also took the liberty to dynamically display the column names as table headers which should eliminate the need to manually add them later when your columns increase. If you would like to manually create them simply replace the top php portion with this one:
<?php
$db = new mysqli('localhost', 'root', '', 'test'); // server, user, pass, database
$table_name = 'dane'; // table
// Let's make sure we could establish a connection
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
// Build our select to return column names only
$select_cols = "SELECT column_name FROM information_schema.columns WHERE table_name='$table_name'";
if(!$num_cols = $db->query($select_cols)){
die('There was an error running the query.');
}
$select_data = "SELECT * FROM $table_name ORDER BY `id` DESC LIMIT 0 , $num_cols->num_rows";
if(!$result = $db->query($select_data)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$data[] = $row; // Store the data into array to be used in the html table
}
$db->close(); // Close our connection
// print_r('<pre>');
// print_r($data);
// print_r('</pre>');
?>
and adjust the html code between <thead></thead>. This entire sample was put together pretty quickly so it could definitely be improved and adjusted to whatever needs. Please inspect it for any typos as well.

Categories