Delete row in table - MySQL, PHP, HTML - php

I have an HTML table displaying data from a MySQL database. I want to add a "delete row" button, so that with a click I can delete a row from the database table (data linked to the Member's ID).
I can see what the SQL should be doing, but I don't know how to implement it with PHP.
I also have a search page where you can search for a member by inputting their first name and I want to add the same delete function to that search page too.
But for now I want to get it working on an HTML table that shows all the data first!
Here is my code (minus the connecting and disconnecting from database and all that):
// Retrieve Member Details
$sql = "SELECT MemberID, FirstName, Surname, DOB, Address, County,
PostCode, MobileNo, Email FROM Members";
$result = mysql_query($sql, $connection);
//create table
echo "<table>";
// Loop through the data and then display chosen data
echo "<h2>Member Details</h2>";
echo "<tr><th>Member ID</th><th>First Name</th><th>Surname</th>
<th>DOB</th><th>Address</th><th>County</th><th>Post Code</th>
<th>Mobile Number</th><th>Email</th><tr>";
while($a_row = mysql_fetch_assoc($result))
echo "<tr><td>" . $a_row['MemberID']
. "</td><td>" . $a_row['FirstName']
. "</td><td>" . $a_row['Surname']
. "</td><td>" . $a_row['DOB']
. "</td><td>" . $a_row['Address']
. "</td><td>" . $a_row['County']
. "</td><td>" . $a_row['PostCode']
. "</td><td>" . $a_row['MobileNo']
. "</td><td>" . $a_row['Email']
. "</td><tr>";
//close table
echo "</table>";
Code for Search page:
<?php
// Connecting to Database Server
$connection = mysql_connect("localhost", "1520621",
// If connection cannot be made to Database Server
if (!$connection)
die("Cannot connect to Database");
// Select the database
mysql_select_db("db1520621", $connection)
// If Database cannot be found
or die("Cannot find Database");
// SQL
// Select all data from Members table where FirstName matches that which is inserted into searchName using POST
$sql ="SELECT * FROM Members";
$sql.=" WHERE FirstName=\"".$_POST["searchName"]."\"";
// Execute the query
$queryResult=mysql_query($sql);
//Check for errors and display following messages if there is
if (mysql_error())
{
echo "Problem with Query<br>";
echo "The following error message was returned from MySQL:<br>";
echo mysql_error();
exit;
}
//Create table
echo "<table>";
echo "<h2>Member Details</h2>";
echo "<tr><th>First Name</th><th>Surname</th><th>DOB</th><th>Address</th><th>County</th><th>Post Code</th><th>Mobile Number</th><th>Email</th><tr>";
// If no results found show message. If results found, loop if there is more than 1 result
if (mysql_num_rows($queryResult)==0)
{
echo "No members with that name";
}
else
{
while ($dbRecord=mysql_fetch_array($queryResult))
{
echo "<tr><td>".$dbRecord["FirstName"]."</td><td>".$dbRecord["Surname"]."</td><td>".$dbRecord["DOB"]."</td><td>".$dbRecord["Address"]."</td><td>".$dbRecord["County"]."</td><td>".$dbRecord["PostCode"]."</td><td>".$dbRecord["MobileNo"]."</td><td>".$dbRecord["Email"]."</td></tr>";
}
}
// Close connection to Database
mysql_close($connection);
?>

You should be using PHP Data Objects (http://php.net/manual/en/ref.pdo-mysql.php) or MySQLi (http://php.net/manual/en/book.mysqli.php).
The Ending <tr> table on the echo line is not closed (</tr>) which might be messing with the HTML output.
SQL query for deleting:
$query = sprintf("DELETE FROM Members WHERE MemberID = '%s'",
mysql_real_escape_string($member_id));

Here is the full code to delete row from database. First you have to add delete link and pass member id to be deleted.
// Check if delete button is clicked and delete respective row
if(isset($_GET['DeleteID']) AND !empty($_GET['DeleteID']))
mysql_query("DELETE FROM Members where MemberID = '".$_GET['DeleteID']."'", $connection);
// Retrieve Member Details
$sql = "SELECT MemberID, FirstName, Surname, DOB, Address, County, PostCode, MobileNo, Email FROM Members";
$result = mysql_query($sql, $connection);
//create table
echo "<table>";
// Loop through the data and then display chosen data
echo "<h2>Member Details</h2>";
echo "<tr><th>Member ID</th><th>First Name</th><th>Surname</th><th>DOB</th><th>Address</th><th>County</th><th>Post Code</th><th>Mobile Number</th><th>Email</th><th>Delete</th><tr>";
while($a_row = mysql_fetch_assoc($result)){
echo "<tr><td>" . $a_row['MemberID'] . "</td><td>" . $a_row['FirstName'] . "</td><td>" . $a_row['Surname'] . "</td><td>" . $a_row['DOB'] . "</td><td>" . $a_row['Address'] . "</td><td>" . $a_row['County'] . "</td><td>" . $a_row['PostCode'] . "</td><td>" . $a_row['MobileNo'] . "</td><td>" . $a_row['Email'] . "</td>";
echo "<td>Delete</td></tr>";
}
//close table
echo "</table>";
Search page code
<?php
// Connecting to Database Server
$connection = mysql_connect("localhost", "1520621", "w9p1n5");
// If connection cannot be made to Database Server
if (!$connection)
die("Cannot connect to Database");
// Select the database
mysql_select_db("db1520621", $connection)
// If Database cannot be found
or die("Cannot find Database");
// SQL
if(isset($_GET['DeleteID']) AND !empty($_GET['DeleteID']))
mysql_query("DELETE FROM Members where MemberID = '".$_GET['DeleteID']."'", $connection);
// Select all data from Members table where FirstName matches that which is inserted into searchName using POST
$sql ="SELECT * FROM Members";
$sql.=" WHERE FirstName=\"".$_REQUEST["searchName"]."\"";
// Execute the query
$queryResult=mysql_query($sql);
//Check for errors and display following messages if there is
if (mysql_error())
{
echo "Problem with Query<br>";
echo "The following error message was returned from MySQL:<br>";
echo mysql_error();
exit;
}
//Create table
echo "<table>";
echo "<h2>Member Details</h2>";
echo "<tr><th>First Name</th><th>Surname</th><th>DOB</th><th>Address</th><th>County</th><th>Post Code</th><th>Mobile Number</th><th>Email</th><tr>";
// If no results found show message. If results found, loop if there is more than 1 result
if (mysql_num_rows($queryResult)==0)
{
echo "No members with that name";
}
else
{
while ($dbRecord=mysql_fetch_array($queryResult))
{
echo "<tr><td>".$dbRecord["FirstName"]."</td><td>".$dbRecord["Surname"]."</td><td>".$dbRecord["DOB"]."</td><td>".$dbRecord["Address"]."</td><td>".$dbRecord["County"]."</td><td>".$dbRecord["PostCode"]."</td><td>".$dbRecord["MobileNo"]."</td><td>".$dbRecord["Email"]."</td>";
echo "<td>Delete</td></tr>";
}
}
// Close connection to Database
mysql_close($connection);
?>

Related

Creating a PHP API (Convert data from mySQL to JSON);

So my 1st target is to convert expecting data from mySQL as JSON before use XML.
Things i trying to solve- Connect two tables from database for specific user and display it on screen.
Everything is in one PHP file:
<?php
include 'db.php';
session_start();
ob_start();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users
INNER JOIN user_quiz ON users.user_uid = user_quiz.user_uid
WHERE users.user_uid = '".$_SESSION['u_uid'] ."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
// for check if record exist
echo "<br> id: ". $row["id"]. " - Name: ". $row["user_first"]. " " . $row["user_last"] . " id:" . $row["user_uid"] . " Selected qustion " . $row["q_topic"] . " ". $row["q_id"] . "<br>";
}
} else {
echo "0 results";
}
$myJSON = json_encode($outp);
echo $myJSON;
?>
So now where is a issue.. When i do SQL like that:
SQL:
$sql = "SELECT * FROM users";
PHP is convert data as JSON data... but when i trying to do that for specific user i have empty []... That's why i use echo to see if i have output or i have error but... i have displays value... Had no idea what's going on... need advice.

errorTable 'college.college' doesn't exist : query error

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include 'conn.php';
// Attempt select query execution
$db_select = mysqli_select_db($conn,'college');
if (!$db_select) {
die("Database selection failed:: " . mysql_error($conn));
}else{
} //You don't need a ; like you do in SQL
$result = mysqli_query($conn,"SELECT * FROM college") or die("error".mysqli_error($conn));
echo "<table>"; // start a table tag in the HTML
$result = array();
while($row = mysqli_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['city'] . "</td><td>" . $row['clients'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysqli_close($conn);
?>
I am getting error in query statemenet that table college does exist. I have created table college in phpmyadmin and populated it with fake values, but still I am getting query error. The error is in line 14.

inserting into SQL with PHP

Essentially I want to:
pull info from mySQL server
create a table of students with their name, phone number, and exam date
I want a checkbox next to each student pulled from mySQL and when the checkbox is clicked and the user hits submit, it inserts a value into mySQL column 'contacted'under that specific student. The value will either be "yes" or "NULL"
I used primary key (id) which auto increments to create unique checkbox names for each student
application: The user will retrieve a table of our students and their exam dates. The user will call (via phone) the students and ask about their exam. Once the user has contacted that student, they check the checkbox to show that that particular student has already been contacted. That information will be stored in mySQL for that particular student to show that student was contacted.
here is my code:
<?php
define('DB_NAME', 'Students');
define('DB_USER', 'admin');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
$sql = sprintf("SELECT id,f_name,l_name,phone,exam_date FROM Student_data");
$result = mysql_query($sql);
$table_count = 0;
$student_id = array();
echo "<script>
function DoTheThing()
{
" .
for($x = 0; $student_id[$x] != NULL; $x++)
{
$in = sprintf("INSERT INTO Student_data (contacted) VALUES ('". $_POST[$row['id']] ."') WHERE id = '" . $row['id'] . "';" );
$db_selected->mysql_query($in)
}
. "
}
</script>";
echo "<table width= 400 border=1><form action=\"DoTheThing()\" method=\"POST\">
<tr>
<th width='175' scope='col'>Name</th>
<th width='150' scope='col'>Phone</th>
<th width='125' scope='col'>Exam Date</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><center>" . $row['f_name'] . " ". $row['l_name']. "</center></td>";
echo "<td><center>". $row['phone'] ."</center></td>";
echo "<td><center>". $row['exam_date'] ."<input type=\"checkbox\" name=\"" . $row['id'] . "\" value=\"yes\"></center></td>";
echo "</tr>";
$student_id[$table_count] = $row['id']
$table_count = +1;
}
echo "</form></table>
<br/><br/><input style = \"height:35px;width:95px;font-size:20px;\" type=\"submit\" name=\"submit\" value=\"Submit\">
";
mysql_close($link);
?>
edit: Sorry, realized I never posted my question
It stopped working when I attempted to insert the "yes" or "NULL" value into mySQL. I am very new to mySQL and was wondering if any of my statements were wrong.
This should be a very big boost of help, basically a shell. All that is left to do is inserting the data into your SQL server.
I commented the code so you could see what was going on, when, and where.
Also, you should definitely stay AWAY from mysql_* as it's deprecated. My example was made using mysqli_*. Another options would be PDO.
<?php
//Set variables (Can be done on another file for more security)
$Host = "Localhost";
$User = "admin";
$Pass = "password";
$DB = "Students";
//Connect to the databse using mysqli. NOT MYSQL WHICH IS DEPRECATED
$con = mysqli_connect($Host, $User, $Pass, $DB);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//if submitted
if(isSet($_POST['submit'])) {
//submit data using mysqli_query and then reload the page.
//clear POST variables before you reload the page.
unset($_POST);
//reload the page
echo "<META http-equiv='refresh' content='0'>";
} else { //if not submitted
//define search variable, and query it.
$db_selected = mysqli_query($con, "SELECT id,f_name,l_name,phone,exam_date FROM Student_data");
//Start table
echo "<form method='POST'>";
echo " <table>";
echo " <tr>";
echo " <th>Name</th>";
echo " <th>Phone</th>";
echo " <th>Exam Date</th>";
echo " <th></th>";
echo " </tr>";
//Loop through sql database
while($row = mysqli_fetch_array($check)) {
echo " <tr>";
echo " <td>".$row['f_name']." ".$row['l_name']."</td>";
echo " <td>".$row['phone']."</td>";
echo " <td>".$row['exam_date']."</td>";
echo " <td><input type='checkbox' name='checkbox['".$row['id']."']' value='1'></td>";
echo " </tr>";
}
//end table
echo " </table>";
echo "<input type='submit' value='Submit' name='submit'>";
echo "</form>";
}
?>

Import data from a txt file in a MySQL database with PHP on visit

I'm using PHPMyAdmin to run my MySQL database.
Suppose we have this txt file "people.txt", a MySQL database and a PHP page in which are showed the data from the database. Suppose that data in the text file are stored with this syntax:
2015/16/01|Alex|Paris
2015/13/01|Johnny|Berlin
2015/11/01|Mary|Oslo
You can notice that each field is separated with a |
Is there any way to import these data using a PHP script? I want to show you a different script that, when the page is visited, send data to the database:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `People` (data, name, city)
VALUES ('2015/10/01', 'Will', 'Rome')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I want to emulate this script in order to let check, each time the page is visited, the txt file. Any help?
I tried to merge the PHP script that shows my data and the one that import them from the txt file but it doesn't seem to work properly..
<?php
$con=mysqli_connect("localhost","username","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed: " . mysqli_connect_error();
}
$sql = "
LOAD DATA INFILE 'people.txt'
INTO TABLE `People`
FIELDS TERMINATED BY '|'
";
$result = mysqli_query($con,"SELECT * FROM `People`");
echo "<table class='people'>
<tr class='titles'>
<th>Data</th>
<th>Name</th>
<th>City</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Data'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['City'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Use the "LOAD DATA INFILE" statement to just load the data into the table every time the page is visited.
$sql = "
LOAD DATA INFILE 'people.txt'
INTO TABLE `People`
FIELDS TERMINATED BY '|'
";
One part of the SQL to look into are the REPLACE or IGNORE option, which determines what will happen if the script tries to insert a row that duplicate an existing unique key, if your table has any.
Also, if your input file has fields in a different order than your database table, then you can provide a list of columns at the end of the SQL, like (data, name, city).
Other than those things, I think you should simply be able to replace the $sql variable in your posted code with something like the above SQL, then run (as in your original code):
if ($conn->query($sql) === TRUE) {
echo "OK!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

Delete multiple rows from mysql with checkbox

I've got a query that displays a table with information about a message, I also have a column that gives the option to select the messages that the user wants to delete with a checkbox, once they have ticked the messages they want to delete, they then click on a submit button which takes them to the process page where the SQL statement to delete each selected message is made; however, the statement doesn't seem to work, this is what I have so far:
THE MESSAGE DISPLAY PAGE:
if ($_SESSION['user_session'] == "$current_user")
{
{
echo "<table border='1'>
<tr>
<th>Message ID</th>
<th>Username</th>
<th>Subject</th>
<th>Message</th>
<th>Delete?</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['message_id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['sub'] . "</td>";
echo "<td>" . $row['message'] . "</td>";
echo "<td><input type='checkbox' name='check_list[]' value='" . $row['message_id'] . "' /></td>";
echo "</tr>";
}
echo "</table>";
}
}
THE PROCESS PAGE WITH SQL STATEMENT:
if(!empty($_POST['check_list']))
{
foreach($_POST['check_list'] as $check)
{
//connection to the database
$dbhandle = mysql_connect("XXX", "XXX", "XXX")
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("XXX",$dbhandle)
or die("Could not select examples");
//execute the SQL query to update the "returned" field to 1 wherever the loan_id is checked.
$result = mysql_query("DELETE FROM message WHERE message_id='$check'");
}
if ($result)
{
echo 'Messages Deleted';
}
}
if(!empty($_POST['check_list']))
{
$dbhandle = mysql_connect("XXX", "XXX", "XXX") or die("Unable to connect to MySQL");
$selected = mysql_select_db("XXX",$dbhandle) or die("Could not select examples");
$result = mysql_query("DELETE FROM message WHERE message_id IN (" . implode(',', $_POST['check_list']) . ")", $dbhandle);
if ($result !== false)
echo 'Messages deleted.';
}
You obviously should implement some more testing of the contents of $_POST['check_list'] before executing the query. We don't want evil people to do silly stuff.
As far as I can see there's nothing wrong with your code, you should really try a var_dump($check) before the SQL query to output what it contains, and a var_dump($_POST['check_list']) at the very beggining of the second page.
Also, I suggest you to take out the database connection of the foreach as you are doing multiple innecesary connections, like this:
if(!empty($_POST['check_list'])) {
// Output the variable $_POST['check_list']
var_dump($_POST['check_list']);
//connection to the database
$dbhandle = mysql_connect("XXX", "XXX", "XXX") or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("XXX",$dbhandle) or die("Could not select examples");
foreach($_POST['check_list'] as $check) {
// Output the $check variable to see what it contains
var_dump($check);
//execute the SQL query to update the "returned" field to 1 wherever the loan_id is checked.
$result = mysql_query("DELETE FROM message WHERE message_id='$check'");
// For each $check, verify what message_id got deleted
if ($result) {
echo 'Message ID Deleted: ' . $check;
}
}
}

Categories