I am trying to perform this query in PHP however it keeps returning false. I have tried the query in phpMyAdmin and it works fine so if anyone can spot what is wrong that would be great. Also how can I get some better error messages for problems like this so I can try and solve the problem?
$stmt = $conn->prepare("SELECT * FROM artist WHERE artID != ?;");
if(!$stmt)
{
echo "Error creating SQL statement";
return 1;
}
I have already used $stmt = $conn->prepare(query); for a different query in the same block of PHP code which runs fine so I don't know if that is anything to do with it.
Thanks in advance :)
EDIT: I was asked where I bind the '?' used in the query. $stmt->bind_param('i', $albumArtID); I didn't include it in the question originally because the echo in the if statement runs so I presumed it was encountering an error before the bind_param.
EDIT 2: As requested here is the code used to make the connection:
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'psyjb6';
$conn = new mysqli('localhost', 'root', '', 'psyjb6');
if ($conn->connect_errno)
echo"<p>failed to connect to database</p>";
?>
EDIT 3: Here is the entire main section of code from that page, hopefully we can figure this out:
<form name="editAlbum" method="get" onsubmit="return validateForm(this)">
<div class="row">
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'connection.php';
if(isset($_GET["album"]))
{
/* If album was passed in the URL then get current values
for that album */
$stmt = $conn->prepare("SELECT cd.artID, artName, cdTitle, cdPrice, cdGenre, cdTracks FROM cd INNER JOIN artist ON (cd.artID = artist.artID AND cdID = ?);");
if(!$stmt)
{
echo "Error creating SQL statement";
exit;
}
$albumID = htmlspecialchars($_GET["album"]);
$stmt->bind_param('i', $albumID);
$stmt->execute();
$stmt->bind_result($albumArtID, $albumArtName, $albumTitle,
$albumPrice, $albumGenre, $numTracks);
$stmt->fetch();
/* Create input fields */
// Album Title
echo "<div class=\"row horizontal-center\">" .
"<input type=\"text\" value=\"" . htmlspecialchars($albumTitle) . "\" name=\"albumTitle\"/>" .
"</div>";
// Artist Name
echo "<div class=\"row horizontal-center\">" .
"<h6>By Artist:</h6>" .
"</div>";
echo "<div class=\"row horizontal-center\">" .
"<select name=\"artID\">";
/* Create option for current artist so it will be first in list */
echo "<option value=\"$albumArtID\">$albumArtName</option>\n";
/* Generate list of artists except artist currently associated with the album */
$stmt = $conn->prepare("SELECT * FROM artist WHERE artID != ?");
if($stmt === false)
{
echo $conn->error;
echo "hi";
exit;
}
$stmt->bind_param('i', $albumArtID);
$stmt->execute();
$stmt->bind_result($artID, $artName);
/* Check if no artists were found */
if(!$stmt->fetch())
echo "<p>No artists were found!</p>";
else
{
/* Create options for artists that were found */
do
{
echo "<option value=\"$artID\">$artName</option>\n";
}while($stmt->fetch());
}
echo "</select>" .
"</div>";
// Album Price
echo "<div class=\"row horizontal-center\">" .
"<input type=\"number\" step=\"0.01\" value=\"" . htmlspecialchars($albumPrice) . "\" name=\"albumPrice\"/>" .
"</div>";
// Album Genre
echo "<div class=\"row horizontal-center\">" .
"<input type=\"text\" value=\"" . htmlspecialchars($albumGenre) . "\" name=\"albumGenre\"/>" .
"</div>";
// Number of Tracks
echo "<div class=\"row horizontal-center\">" .
"<input type=\"number\" value=\"" . htmlspecialchars($numTracks) . "\" name=\"numTracks\"\n/>" .
"</div>";
// Delete checkbox
echo "<div class=\"row\">" .
"<div class=\"col-2\">" .
"<h6>Delete:</h6>" .
"</div>" .
"<div class=\"col-1\">" .
"<input type=\"checkbox\" name=\"delete\" value=\"Delete\"/>" .
"</div>" .
"</div>";
/* Create hidden field to submit the album ID with the form */
echo "<input type=\"hidden\" value=\"" . htmlspecialchars($albumID) . "\" name=\"albumID\"\n/>";
}
else
{
/* Send browser back to artists page if they somehow accessed
the edit page without going through the "Edit" link next
to an artist in the table. This would be the artName variable
would not be sent via the URL.*/
header("Location: artists.php");
}
?>
</div>
<div class="row">
<div class="col-2">
<h6>Delete:</h6>
</div>
<div class="col-1">
<input type="checkbox" name="delete" value="Delete"/>
</div>
</div>
<div class="row">
<input type="submit" name="submit" value="Update"/>
</div>
<!-- PHP to edit album data -->
<?php
include 'connection.php';
if(isset($_GET["delete"]))
{
$albumID = $_GET["albumID"];
/* Create DELETE query */
$stmt = $conn->prepare("DELETE FROM cd WHERE cdID = ?;");
if(!$stmt)
{
echo "Error creating SQL statement";
exit;
}
$stmt->bind_param('i', $albumID);
$stmt->execute();
}
else if(isset($_GET["albumTitle"]) && isset($_GET["albumGenre"])
&& isset($_GET["albumPrice"]) && isset($_GET["numTracks"]))
{
$albumTitle = htmlspecialchars($_GET["albumTitle"]);
$artID = htmlspecialchars($_GET["artID"]);
$albumGenre = htmlspecialchars($_GET["albumGenre"]);
$albumPrice = htmlspecialchars($_GET["albumPrice"]);
$numTracks = htmlspecialchars($_GET["numTracks"]);
/* Create INSERT query */
$stmt = $conn->prepare("UPDATE cd SET (cdTitle = ?, artID = ?,
cdGenre = ?, cdPrice = ?, cdTracks = ?) WHERE cdID = ?;");
if(!$stmt)
{
echo "Error creating SQL statement";
exit;
}
$stmt->bind_param('sisdi', $albumTitle, $artID, $albumGenre,
$albumPrice, $numTracks);
$stmt->execute();
}
?>
</form>
If you are using parameterized queries, then you have to pass the value for the parameter when you execute the prepared query.
You also have to execute the prepared query. The prepare just passes the query to the database for compilation and optimisation, it does not actually execute the query.
Also if you get an error in these database access statement, there are functions/methods you should use to show the the actuall error message which are a lot more useful than outputting something you make up yourself like echo "Error creating SQL statement";
Also the ; is not necessary.
$stmt = $conn->prepare("SELECT * FROM artist WHERE artID != ?");
if ( $stmt === false ){
echo $conn->error;
exit;
}
$stmt->bindParam('i', $some_variable)
$result = $stmt->execute();
if ( $result === false ) {
echo $stmt->error;
exit;
}
Close first connection using mysqli_close($conn); after first query is finished then open a new connection with include 'connection.php'; before the second query. Credit to #Chay22
Related
I have this PHP code below that prints the result of a MySQL query in a HTML table. Furthermore, in the table, I create a link of the result that will be used in another query. Lets take a look at the code:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root", "DB1");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM fileDB";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>filename</th>";
echo "<th>filepath</th>";
echo "<th>size</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><a href='http://mysecreturl.com/test.php?path=" . $row['filepath'] . "'>" . $row['filename'] . "<a/></td>";
echo "<td>" . $row['filepath'] . "</td>";
echo "<td>" . $row['size'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
This code works as intended, but now comes the problem: I want to implement the following: Once you click on the link, another query should be executed, this one to be specific: SELECT * FROM fileDB WHERE filepath = 'the one sent from the link'. I thought to use something like $_GET["filepath"] from the link to set the filepath in the second query. I have two main problems with this:
I don't know any PHP so I have no idea how clicking a link could run another query and generate a new table with results.
This is important to point out, filepath is a string of a Windows path, therefore it contains backslashes like this: C:\something\something etc. When I query this manually in phpMyAdmin I escape the backslashes by writing C:\\something\\something but when getting my result in the table from the code above, the string filepath will have one pair of backslash of course (as it is saved in the database). How could I then perform my second query if the backslashes apparently need to be escaped?
Any help is very appreciated!
I thought you want to download a file. well this is much simpler:
if (isset($_GET["path"])) {
$stmt = mysqli_prepare($link, "SELECT * FROM fileDB WHERE filepath = ?");
mysqli_stmt_bind_param($stmt, "s", $_GET["path"]);
}else{
$stmt = mysqli_prepare($link, "SELECT * FROM fileDB");
}
mysqli_stmt_execute($stmt);
if ($result = mysqli_stmt_get_result($stmt)) {
if(mysqli_num_rows($result) > 0){
...
oh and one more thing you should escape query component in your URL
echo "<td><a href='http://mysecreturl.com/test.php?path=" . urlencode($row['filepath']) . "'>" . $row['filename'] . "<a/></td>";
Now this could be done using get method like <a href="yourpage.php?path='your_filepath'"> then in your php use this <?php if(isset($_GET['filepath'])){//Run your php query here}?>
You can do something like this:
echo '<tr>
<td><form method="get" action="test.php">
<button type="submit" name="path" value="'.$row['filepath'].'">
'.$row['filename'].'</button>
</form></td>
<td>'.$row['filepath'].'</td>
<td>'.$row['size'].'</td>
</tr>';
Untested, but should in theory work. Why you have the link in the filename-table-cell, instead of in the table-cell with the actual path in it, god knows, but you can test it and see if it works.
I would, however, just make this into a $_POST, unless it's important to show the URI in the address bar.
To answer the first question, you can add variables to a link, e.g. if you want to pass a first name and last name in a link you would do this
<?php
$fname = "John"; // First name
$lname = "Doe"; // Last Name
echo "<a href='next_table.php?fname=$fname&lname=$lname'>Next Table</a>";
?>
Then to retrieve the first name and last name on another page you would use this:
<?php
$fname = $_GET["fname"];
$lname = $_GET["lname"];
?>
Let me know if this helps.
Just an if statement to check whether the filepath is set or not and str_replace function to escape backlashes.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root", "DB1");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
// Check If filpath is set or not
if(!isset($_GET['filepath']))
{
$sql = "SELECT * FROM fileDB";
}
else
{
$filepath=$_GET['filepath'];
//replace backlashes with double backlashes using str_replace
$filepath=str_replace('\\','\\\/',$filepath);
$sql = "SELECT * FROM fileDB WHERE filepath='$filepath'";
}
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>filename</th>";
echo "<th>filepath</th>";
echo "<th>size</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><a href='http://mysecreturl.com/test.php?path=" . $row['filepath'] . "'>" . $row['filename'] . "<a/></td>";
echo "<td>" . $row['filepath'] . "</td>";
echo "<td>" . $row['size'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Change the code:
// Attempt select query execution
$sql = "SELECT * FROM fileDB";
if($result = mysqli_query($link, $sql)){
To:
// Attempt select query execution
if(isset($_REQUEST['file']) && $_REQUEST['file'] !='') {
$sql = "SELECT * FROM fileDB WHERE `file` = '".$_REQUEST['file']."';";
} else {
$sql = "SELECT * FROM fileDB";
}
if($result = mysqli_query($link, $sql)){
This should convey the basic idea, but take to heart about using parameterized queries.
This question already has answers here:
How to add a delete button to a PHP form that will delete a row from a MySQL table
(5 answers)
Closed 1 year ago.
I am new to php coding.
I am adding each row delete button, but it should not working.
This is my html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
$sql = "SELECT * FROM venu ";
$result = mysql_query($sql) or die(mysql_error());
?>
<table border="2" style= " margin: 0 auto;" id="myTable">
<thead>
<tr>
<th>name</th>
<th>id</th>
<th>rollnumber</th>
<th>address</th>
<th>phonenumber</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['rollnumber'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phonenumber'] . "</td>";
echo "<td><form action='delete.php' method='POST'><input type='hidden' value='".$row["address"]."'/><input type='submit' name='submit-btn' value='delete' /></form></td></tr>";
echo "</tr>";
}
?>
</tbody>
</table>
</body>
</html>
This is my delete code:
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "emp",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
error_reporting(0);
session_start();
$name = $_POST['name'];
$id = $_POST['id'];
$rollnumber = $_POST['rollnumber'];
$address = $_POST['address'];
$phonenumber = $_POST['phonenumber'];
if($name!='' and $id!='')
{
$sql = mysql_query("DELETE FROM 'venu' WHERE name='balaji'AND id='93'AND rollnumber='93'AND address='bangalore'AND phonenumber='1234567890'");
echo "<br/><br/><span>deleted successfully...!!</span>";
}
else{
echo "<p>ERROR</p>";
}
mysql_close($connection);
?>
I am trying to delete each row using a button, but it is not working.
In your html view page some change echo "<td><a href='delete.php?did=".$row['id']."'>Delete</a></td>"; like bellow:
<?php
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['rollnumber'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['phonenumber'] . "</td>";
echo "<td><a href='delete.php?did=".$row['id']."'>Delete</a></td>";
echo "</tr>";
}
?>
PHP delete code :
<?php
if(isset($_GET['did'])) {
$delete_id = mysql_real_escape_string($_GET['did']);
$sql = mysql_query("DELETE FROM venu WHERE id = '".$delete_id."'");
if($sql) {
echo "<br/><br/><span>deleted successfully...!!</span>";
} else {
echo "ERROR";
}
}
?>
Note : Please avoid mysql_* because mysql_* has beed removed from
PHP 7. Please use mysqli or PDO.
More details about of PDO connection http://php.net/manual/en/pdo.connections.php
And more details about of mysqli http://php.net/manual/en/mysqli.query.php
First you need to change your button like
echo "<td>Delete</td>";
this will send the ID of the row which you want to delete to the delete.php
Secondly you need to change a bit your delete.php currently is wide open for SQL injections. Try using MySQLi or PDO instead
if(isset($_GET['id'])) {
$id = $_GET['id'];
$stmt = $mysqli->prepare("DELETE FROM venu WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
}
Of course if you need to add more parameters in delete query you should pass them also with the button..
EDIT: Simple example for update record
You can put second button on the table like
echo "<td>Update</td>";
Then when you click on it you will have the ID of the record which you want to update. Then in update.php
if(isset($_GET['id'])) {
$id = $_GET['id'];
$stmt = $mysqli->prepare("UPDATE venu SET name = ?, rollnumber = ?, address = ? WHERE id = ?");
$stmt->bind_param('sisi', $name, $rollnumber, $address, $id);
$stmt->execute();
$stmt->close();
}
Here ( in update.php ) you can have form which you can fill with new data and pass to variables $name, $rollnumber, $address then post it to update part.
Something to start with: PHP MySqli Basic usage (select, insert & update)
change up your query to use the dynamic value entered by the user, right now it is hard coded in there.
session_start();
require_once 'conn.php';
class myClass extends dbconn {
public function myClassFunction(){
try {
$id = $_GET['id'];
if(isset($_GET['id'])) {
$sql = "DELETE FROM tablename WHERE id = ?";
$stmt = $this->connect()->query($sql);
$stmt->bind_param('i', $id);
header("location: ../filepath/index.php");
}
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
}
This line is wrong, you need to set the WHERE clause to the data you get from the hidden input value
$sql = mysql_query("DELETE FROM 'venu' WHERE name='balaji'AND id='93'AND rollnumber='93'AND address='bangalore'AND phonenumber='1234567890'");
Should be:
$sql = mysql_query("DELETE FROM 'venu' WHERE address='"._POST['address']."'");
And in the little form you are using, change:
<input type='hidden' value='".$row["address"]."'/>
to:
<input type='hidden' name='address' value='".$row["address"]."'/>
i retrieve from the database a list with the ids and titles of some data and have for each an edit and delete link/button
after i click the delete for any of the data it works but i can t make it redirect me to the edit/delete page. here is the code for the table:
<table>
<tr>
<td>ID</td>
<td>Nume poveste</td>
<td>edit</td>
<td>delete</td>
</tr>
<?php
foreach($results_stories as $data) {
echo "<tr>";
echo "<td>" . $data->id_story . "</td>";
echo "<td>" . $data->title . "</td>";
echo "<td><a href='edit_data.php?id=" . $data->id_story . "'>edit</a></td>";
echo "<td><a href='delete_row.php?id=" . $data->id_story . "'>del</a></td>";
echo "</tr>";
}
?>
and here is the code for the delete.php:
try {
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to delete a record
$query = $conn->query("DELETE FROM stories WHERE id_story = '$_GET[id]'");
$stmt = $pdo->prepare($sql);
// use exec() because no results are returned
$stmt->bindParam(':id_story', $data->id_story, PDO::PARAM_INT);
if($stmt->execute()) {
echo "Record deleted successfully";
header("Location: http://localhost/auth2/edit.php");
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
any ideas?
To properly use prepared statements you should have:
$stmt = $conn->prepare("DELETE FROM stories WHERE id_story = ?");
if($stmt->execute(array($_GET['id']))) {
The ? is a placeholder for the value. The PDO driver adds it to the query and quotes it as needed.
To resolve the header issue I'd do:
header("Location: http://localhost/auth2/edit.php?response=Record+deleted+successfully");
Then on edit.php:
if(!empty($_GET['response'])) {
echo htmlspecialchars($_GET['response'], ENT_QUOTES);
}
How can I update a row in my mySql database from a HTML form. I have tried every technique and nothing seems to work. I would like that users could update their own profile page information.
I have a form on my page but the data doesn't get sent through.
What am i missing?
Here is my code:
------------INDEX.php
<?php
require_once("inc/database.php");
require_once("inc/query.php");
?>
<div class="wrapper">
<div class="content">
<h1>User Profiles</h1>
<?php
while ($row = $results->fetch()) {
$id = ($row["id"]);
$name = ($row["name"]);
$age = ($row["age"]);
$password = ($row["password"]);
print '<div ' . 'class= id-' . ($id) . '">';
print "<p>" . ($name) . "</p>";
print "<p>" . ($password) . "</p>";
print "<p>" . ($age) . "</p>";
print "</div>";
}
?>
</div>
</div>
<form action="inc/addnew.php" method="post">
<p>Name: <input type="text" name="name" required></p>
<p>ID: <input type="text" name="id" value="<?php echo $id; ?>"></p>
<p><input type="submit" value="Lisää"></p>
</form>
------------QUERY.php
<?php
try{
$results = $db->query("SELECT name, password, age, id FROM users");
$results->execute();
// echo "Our query ran successfully.";
} catch (Exception $e){
echo "Data could not be retrived from the database.";
exit;
}
------------DATABASE.php
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=user_profile;port=8889', 'User_profile','bFeLcZjMmVw4PBaF');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo "Could not connect to the database.";
exit;
}
------------UPDATE.php
<?php
require_once("database.php");
if( isset( $_POST['name'] ) && strlen( $_POST['id'] )){
$id = $_POST['id'];
$name = $_POST['name'];
$results=("UPDATE users SET name='$name' WHERE id=$id");
}
header("Location: ../index.php");
}
else
{
//error either $_POST['login'] is not set or $_POST['login'] is empty form field
echo 'Name or ID field was empty. Please fill out those fields. Back to site <br>';
}
How you expect this query to execute?
$results=("UPDATE users SET name='$name' WHERE id=$id");
you are just generating a query here on UPDATE.php without actually doing anything with it.
Replace this line with:
$results = $db->query("UPDATE users SET name='$name' WHERE id=$id");
You need to prepare and execute your query, not just define it as a string:
$sth = $db->prepare("UPDATE users SET name=:name WHERE id=:id")
$sth->execute(array("name" => $_POST["name"], "id" => $_POST["id"]));
You should be using placeholders to insert your data. Your query uses string interpolation which is extremely dangerous due to SQL injection bugs. Do not put $_POST data directly into a query, it's never safe.
I have looked up the error for this and I think I am calling the statement before for it to be initialized. I have made a simple connection class that I can include into all of my files that will be talking to the mysql server. Knowing how I am with things, I am most likely over thinking things. I cant seem to find what I am doing wrong.....
Top part of the code is cut off as it only contains the HTML head and php starting code that is non-important for this.
//include database connection
include('connection.php');
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM sc_steamgames WHERE appid = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_GET['appid']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
//select all data
$query = "SELECT * FROM sc_steamgames";
$stmt = $con->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
echo "<a href='add.php'>Create New Record</a>";
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>AppID</th>";
echo "<th>Title</th>";
echo "<th>Release Date</th>";
echo "<th>Last Updated</th>";
echo "</tr>";
//retrieve our table contents
//fetch() is faster than fetchAll()
//http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$appid}</td>";
echo "<td>{$title}</td>";
echo "<td>{$releasedate}</td>";
echo "<td>{$lastupdate}</td>";
echo "<td>";
//we will use this links on next part of this post
echo "<a href='edit.php?id={$appid}'>Edit</a>";
echo " / ";
//we will use this links on next part of this post
echo "<a href='#' onclick='delete_user( {$appid} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{ //if no records found
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( appid ){
//this script helps us to
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'index.php?action=delete&id=' + appid;
}
}
</script>
</body>
</html>
connection.php
/* Database Info */
// Host/IP
$host = "localhost";
// Database Name
$db_name = "**";
// Username
$username = "**";
//Password
$password = "**";
/* End Database Info */
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}