Form to delete data from MySQL database using PHP - php

So I'm creating a small program with 2 forms, one to add data to a database, and one to delete from it. I've managed to create the first input form, but I'm slightly confused as to how I would get the second form to work. In the database "tasks" I have a table called "ID" which has the columns "ID", "Name" and "Hours"
Here's what the two HTML forms look like
<h2>Add Tasks</h2>
<form action="test.php" method="get">
Name of Task: <input type="text" name="name"><br />
Hours: <input type="number" name="hours"><br />
<input type="submit" value="Add" name="submit">
</form>
<h2>Delete Tasks</h2>
<form action="delete.php" method="get">
ID: <input type="number" name="ID"><br />
<input type="submit" value="Delete">
</form>
And the PHP for the first form "Add tasks" which inserts data
$servername = "localhost";
$username = "root";
$password = "root";
$conn = new mysqli($servername, $username, $password, "Tasks");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
};
if (isset($_GET['submit'])) {
mysqli_select_db ($conn,"Tasks");
$name = $_GET['name'];
$hours = $_GET['hours'];
$sql = "INSERT INTO ID (Name, Hours) VALUES ('".$name."','". $hours."')";
$results = mysqli_query($conn,$sql);
$query = "SELECT `Name` FROM `ID`";
$result = mysqli_query($conn, $query);
$x=0;
And the PHP for the second form which deletes tasks. This is the part that is not working
if (isset($_GET['submit'])) {
mysqli_select_db ($conn, "Tasks");
$id = $_GET['id'];
$sql = "DELETE FROM ID (ID) VALUES ('".$id."')";
$query = "SELECT `Name` FROM `ID`";
$result = mysqli_query($conn, $query);
$x=0;
How should I format the PHP for the second button. I've basically reused the code for the first form. Do I need to differentiate it somehow from the first button? Currently the page is showing up completely blank. I'm a complete novice so any help would be appreciated.

Your SQL Statement
"DELETE FROM ID (ID) VALUES ('".$id."')"
is wrong.
It should be
DELETE FROM table_name
WHERE some_column=some_value;
. So, change your statement to
DELETE FROM ID WHERE ID='$id'
Suggestions
You should use POST method for action which will result in data edit.
You should check the input, make sure it did not contain SQL statement. A good way is to use $stuff = mysql_real_escape_string($_GET["stuff"]).

I see you have name 'ID' in the form but your are trying to get 'id'. That could be the problem

The sql statement for deletion should look something like the snippet below.
$sql = "DELETE FROM ID WHERE `id`=".$id.";";
$results = mysqli_query($conn,$sql);

In addition to above answers you should give different name to the both form input tags as
<h2>Add Tasks</h2>
<form action="test.php" method="get">
Name of Task: <input type="text" name="name"><br />
Hours: <input type="number" name="hours"><br />
<input type="submit" value="Add" name="submit">
</form>
<h2>Delete Tasks</h2>
<form action="delete.php" method="get">
ID: <input type="number" name="ID"><br />
<input type="submit" value="Delete" name="delete">
</form>
So for adding into database , you can use
if (isset($_GET['submit'])){
// your code here
}
And for deleting from database , you can use
if (isset($_GET['delete'])){
mysqli_select_db ($conn, "Tasks");
$id = $_GET['id'];
$sql = "DELETE FROM ID (ID) WHERE ID='".mysql_real_escape_string($id)."' ;
$query = "SELECT `Name` FROM `ID`";
$result = mysqli_query($conn, $query);
$x=0;
}
This will solve all the problems.
If you are using same name for the type="submit" in both forms than you can use POST method on one form and GET method on the other.
And yes mysql_real_escape_string is used to prevent SQL INJECTION.

Related

PHP query for copying tables

This has to be somewhere online but I am having no luck after hours of trying to do this.
So I've HTML form on one page and a PHP page that creates a database fine..
<form action="createdb.php" method="post">
<label for="dbname"><b>Name of DB</b></label>
<input type="text" name="dbname" id="dbname"/>
<input type="submit" value="Create DB">
<?php
$conn = mysqli_connect("localhost", "root", "") or die(mysqli_error());
$dbname = $_POST['dbname'];
if (mysqli_query($conn,"CREATE DATABASE $dbname")) {
echo "Database created";
} else {
echo "Database was not created";
}
mysqli_close($conn);
?>
Then I have underneath the PHP code these forms.. The form for creating the tables work fine within the DB that has just been created.. But its the form for copying tables from a DB already created into the newly created DB.
<form action="createtable.php" method="post">
<label for="tablename"><b>Create Table within new DB</b></label>
<input type="text" name="tablename" id="tablename"/>
<input type="hidden" name="holdname" value="<?php echo $dbname ?>">
<input type="submit" value="Create Table">
</form>
<p>OR</p>
<form action="copytables.php" method="post">
<label for="tablename"><b>Copy RSS Tables</b></label>
<input type="text" name="tablename" id="tablename" readonly/>
<input type="hidden" name="holdname" value="<?php echo $dbname ?>">
<input type="submit" value="Copy Tables">
</form>
I wanted to copy the tables, structure and data called 'lookup_age' and 'score' into the new DB from a database called 'rss_db'. I've rewrote the PHP page needed in many different ways and ATM it has been left like this, as of something I seen on W3schools, which confused me even more. I know it can be easily done via PHPMYADMIN but need it through a query now and HTML form if possible. Heres what I have as followed but wondering what should the query line actually be if possible..
<?php
$conn = mysqli_connect("localhost", "root", "") or die(mysqli_error());
$dbname =$_POST['holdname'];
mysqli_select_db($conn,"$dbname");
mysqli_select_db($conn,"rss_db");
$sql = "
INSERT lookup_age
INTO $dbname
FROM rss_db";
mysqli_close($conn);
?>
I don't know if these will help but you could try:
create table `table2` like `table1`;
insert `table2` select * from `table`;
or, as a single line perhaps
create table `table2` as select * from `table1`;
try this query, to copy the tables:
$sql = " create table '$dbname' as select * FROM 'rss_db'";
FINALLY FOUND IT!! As simple as...
$query = "INSERT INTO $dbname.lookup_age
SELECT * FROM rss_db.lookup_age";

Selecting a row in PHP and putting that data into a form/text fields

I have page which has a table and for each row a corresponding button. I am trying to select that specific row and place the data into the text fields of a form but, the query doesn't seem to be working. Any help is much appreciated. Thanks. Here's the code so far:
<?php
if (isset($_POST['add'])){
unset($_POST['add']);
$id =$_POST['bookID'];
$q = "SELECT * FROM book WHERE book.bookID = $id";
$query1 = $db->query($q);
$data = $query1->fetch(PDO::FETCH_BOTH);
}
?>
<form>
<form action = "basket.php" method="post">
<p><input type="text" name="title" value="<?php print($data['Title']); ? >"/></p>
</form>
<input type="submit" name="add" value="Add to Field" />
</form>
Change about i missed something.
$db->query($q);
$db->execute(); // this line is missing you have to execute
$data = $db->fetch(PDO::FETCH_ASSOC); // no point fetching both when you know the names.

Deleting Information From Database String Input

I am looking to delete a particular row from a database using the code below. The code below is within a file called "delete.php" and it is taking input from an input box that is located on another php file called "yourReports.php".
When the form is submitted on "yourReports.php" it should delete the row from the database, however it doesn't appear to be working.
delete.php
<?php
$mysqli = mysqli_connect("localhost", "root", "DBPASS","DBNAME") or die ('Could not connect to database!');
$_POST['delete'];
$deletereport = mysqli_real_escape_string($mysqli, $_POST['delete']);
mysqli_query($mysqli,"DELETE FROM reports WHERE reportName = '".$deletereport."'");
header('Location: yourreports.php');
?>
yourReports.php
<form action="delete.php" method="post" name="form1">
<label><strong>Enter Report Name To Delete:</strong></label>
<input name="delete" id="delete" type="text">
<input value="Delete Report" name="delete" class='myButton' type="submit">
</form>
Any help would be appreciated.
Thanks
Set the method and name attribute of form to post
<form action="delete.php" method="post" name="form1">
Check if the query fails:
if(! mysqli_query($mysqli,"DELETE FROM reports WHERE reportName = '".$deletereport."'")){
echo mysqli_error();
}
[Updated]
You cannot have two inputs with the same name. Your input and delete button both have the name delete. So try considering different names for inputs.
change
mysqli_query($mysqli,"DELETE FROM reports WHERE reportName = '".$deletereport."'");
To
mysqli_query($mysqli,"DELETE FROM reports WHERE reportName = '{$deletereport}'");

Insert each array item in separate field

I have looked thoroughly, but I have not found the solution (or perhaps I didn't realize I had since I'm a novice)... Here is my problem:
My table has these six fields: username,want1,want2,want3,want4,want5. My form has username, and a multiple SELECT box where five wishes are selected. I want to insert that username and those selections together as a record, in their corresponding "cell" in the table. Here is my code (for the submit/$_POST action) so far:
*Note: I have named the multiple SELECT box "wants[]" so that it knows it's an array.
<?php
//variables
$username = $_POST['username'];
$want = $_POST['wants'];
//connect
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
//insert
mysql_query("INSERT INTO The_Table (username,want1,want2,want3,want4,want5) VALUES ('$username','$want[0]','$want[1]','$want[2]','$want[3]','$want[4]')");
?>
When I test, no bugs/errors show, but the table isn't being filled with a record. I am very new to coding, I apologize. Hopefully there is a simple solution. Thank you so much to any help or advice!!
Try this code i hope its work for you...
form.php
<form action="insert.php" method="post" name="form">
user_name : <input name="u_name" type="text" /><br />
wish 1 : <input name="wish_1" type="checkbox" value="1" /><br />
wish 2 : <input name="wish_2" type="checkbox" value="2"/><br />
wish 3 : <input name="wish_3" type="checkbox" value="3"/><br />
wish 4 : <input name="wish_4" type="checkbox" value="4"/><br />
wish 5 : <input name="wish_5" type="checkbox" value="5"/><br />
<input type="submit" />
</form>
insert.php
<?php
//variables
$username = isset($_POST['u_name'])?$_POST['u_name']:'';
$wish_1 = isset($_POST['wish_1'])?$_POST['wish_1']:'';
$wish_2 = isset($_POST['wish_2'])?$_POST['wish_2']:'';
$wish_3 = isset($_POST['wish_3'])?$_POST['wish_3']:'';
$wish_4 = isset($_POST['wish_4'])?$_POST['wish_4']:'';
$wish_5 = isset($_POST['wish_5'])?$_POST['wish_5']:'';
//connect
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
//insert
mysql_query("INSERT INTO The_Table (username,want1,want2,want3,want4,want5)
VALUES ('".$username."','".$wish_1."','".$wish_2."'
,'".$wish_3."','".$wish_4."','".$wish_5."')");
?>
In your description, you say you named the select "wishes" and the fields "wish1", "wish2" etc., but then in your code you call it ['wants'] and "want1, want2". If that's really how your code is, it would cause a problem...

How do I update multiple tables using prepared statements with mySQLi?

I have a form with two fields with the name attribute of 'photo_title' and 'photographer_name', and a hidden field named 'photo_id'. When the user pushes the submit button, i want it to update two separate tables in the database. I can get it to update a single table, but as soon as I try to leftjoin the second table, it doesn't like it.
I think there may be something wrong with my query string or the binding. How can I update two separate values in two separate tables in my Mysql database while still using prepared statements?
Here's the PHP:
if (array_key_exists('update', $_POST)) {
$sql = 'UPDATE photos SET photos.photo_title = ?, photographers.photographer_name = ?
LEFT JOIN photographers ON photos.photographer_id = photographers.photographer_id
WHERE photo_id = ?';
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_param('ssi', $_POST['photo_title'], $_POST['photographer_name'], $_POST['photo_id']);
$done = $stmt->execute();
}
}
Here's the form:
<form id="form1" name="form1" method="post" action="">
<input name="photo_title" type="text" value=""/>
<textarea name="photographer_name"></textarea>
<input type="submit" name="update" value="Update entry" />
<input name="photo_id" type="hidden" value="<?php echo $photo_id ?>"/>
</form>
Here's an answer so folks who read this question see it, instead of finding it in your comment above. I'll mark this CW so I don't get any points for it.
UPDATE photos LEFT JOIN photographers
ON photos.photographer_id = photographers.photographer_id
SET photos.photo_title = ?, photographers.photographer_name = ?
WHERE photos.photo_id = ?
FWIW, the documentation for MySQL's UPDATE syntax is illustrative.
I was working on something similar. Here is a few things that I did. Hope it helps
if (isset($_POST['update'])) {
$id=intval($_GET['photo_id']);
$photo_title=$_POST['photo_title'];
$photographer_name=$_POST['photographer_name'];
$sql = "update photos p, photographers pg set p.photo_title=:photo_title, pg.photographer_name=:photographer_name where p.photographer_id=$id and pg.photographer_id=$id";
$query = $dbh->prepare($sql);
$query->bindParam(':photo_title',$photo_title,PDO::PARAM_STR);
$query->bindParam(':photographer_name',$photographer_name,PDO::PARAM_STR);
$query->execute();
}
You can even add your photo_id to the form action in case you want to use the id on a different page.
<form id="form1" name="form1" method="post" action="index.php?id=<?php echo $photo_id;?>">
<input name="photo_title" type="text" value=""/>
<textarea name="photographer_name"></textarea>
<input type="submit" name="update" value="Update entry" />
</form>
I have a file I created that connects to the database that I named config that has the following codes. Include it with this code where your form is at the top so you don't get errors executing the code above.
<?php
// DB credentials.
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','photographer');
// Establish database connection.
try{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,
DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e){
exit("Error: " . $e->getMessage());}
?>

Categories