Delete Page PHP MYSQL - php

Hey guys I have created A delete page, It does not work when I just submit the form and the URL is http://localhost/delete-session.php but once I change the URL to http://localhost/delete-session.php?id=1 it works, What am I missing In my code to make it work?
<h1>Delete Page</h1>
<h3>Enter the booking number of the session you would like to delete!</h3>
<form action ="delete-session.php" method="post">
Booking ID:(Refer To Database):<input type="text" name="booking">
This is the php
if(isset($_GET['booking'])){
$id=$_GET['booking'];
if(!is_numeric($id)){
echo "sorry, there appears to have been an error.";
exit;
}
} else {
echo "sorry, there appears to have been an error.";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "olympics";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$id=$_GET['id'];
if(!is_numeric($id)){
echo "Sorry, there is an error";
exit;
}
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="DELETE from olympiics where booking='$id'";
echo $sql;
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);

I'm going to take a crack at this.
I'm guessing it's because when you go to http://localhost/delete-session.php?id=1 you're passing the id=1 via GET, so when you retrieve the GET input from in your code it succeeds with $id=1, but in your HTML your form is send via POST.
As a fix try using $id=$_POST['booking'];

Bench test your code.
It starts getting $id=$_GET['booking']; which does not exist because you have set the method="post" in your <form> tag.
So use $id=$_POST['booking'];
Then later on it does $id=$_GET['id']; overwriting the value you already attempted to get from above.
This would explain why it requires the extra id paramter on http://localhost/delete-session.php?id=1 as using the querystring to send data will send the id parameter in the $_GET['id'] array, and I dont see why you would want to do this anyway as it has been done at the top of your code by getting this id value from $id=$_POST['booking']
It also makes code so much easier to read and more importantly debug if you adopt an indentation standard in your script like below.
Try this out for size, without adding the id=1 to the querystring
if(isset($_POST['booking'])){
$id=$_POST['booking'];
if(!is_numeric($id)){
echo "sorry, there appears to have been an error. Booking must be numeric";
exit;
}
} else {
echo "sorry, there appears to have been an error.";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "olympics";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="DELETE from olympiics where booking='$id'";
$res = mysqli_query($conn, $sql);
if ($res !== FALSE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
As you are using the mysqli extension, you should also be using parameterized queries to prevent SQL Injection.
if(isset($_POST['booking'])){
$id=$_POST['booking'];
if(!is_numeric($id)){
echo "sorry, there appears to have been an error. Booking must be numeric";
exit;
}
} else {
echo "sorry, there appears to have been an error.";
exit;
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "olympics";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="DELETE from olympiics where booking=?";
$stmt = mysqli_prepare($conn, $sql);
if ( $stmt === FALSE ) {
echo mysqli_error($conn);
exit;
}
mysqli_stmt_bind_param($stmt, 'i', $id);
$res = mysqli_stmt_execute($stmt);
if ($res !== FALSE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

Change form method to get, or use $_REQUEST instead of $_GET

Related

is there some easy way of editing last row data from form (php)

my goal is to build a form that will update a row (automatically updates the last row)
what i have in hand write now is this see picture below
it just adds new row instead of editing last available one
Screenshot:
it updates contact (just adds new ones instead of updating the last column) column but i want to update the last one ex id 3
the rest is just being added not updated
thank you.\
I am happy to clarify more.
edit: here is the form and code (password = null)
PHP code:
<?php
if (!empty($contact)){
if (!empty($password)){
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "student";
// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error()){
die('Connect Error ('. mysqli_connect_errno() .') '
. mysqli_connect_error());
}
else {
$sql = "INSERT INTO student_table2 (contact)
values ('$contact')";
if ($conn->query($sql)){
header("Location: http://localhost/imgtxt/add/add.html");
exit();
}
}
else {
echo "Error: ". $sql ."
". $conn->error;
}
$conn->close();
}
else {
echo "Password should not be empty";
die();
}
}
else {
echo "contact should not be empty";
die();
}
?>

PHP Mysqli_query returns successful, but no insert into my table

I have tried debugging and cannot seem to get to the bottom of this problem. My query returns successful, however nothing is inserted into my table within my database. I am working on a CRUD application to enter holdings of cryptocurrency, and this is simply the Create button. My function gets to the very end of the if statement, and Mysqli_query returns a 1. Could this be issues with permissions in PHPAdmin? Or possibly something to do with Ports?
The code below:
$con = createDB();
if (isset($_POST['create'])){
createData();
}
function createData(){
$username = textboxValue('Username');
$BTC = textboxValue('BTC');
$ETH = textboxValue('ETH');/*$ETH =(isset($_POST['ETH']) ? $_POST['ETH'] : '');*/
$DASH = textboxValue('DASH');
if($username && $BTC && $ETH && $DASH){
$sql = "INSERT INTO cryptoholdings(username,BTC_holdings,ETH_holdings,DASH_holdings)
VALUES('$username','$BTC','$ETH','$DASH')";
if($GLOBALS['con']->query($sql) ){ /*(mysqli_query($GLOBALS['con'],$sql))*/
$GLOBALS['con']->commit();
echo "Record Successfully inserted...!";
}
else{
echo "Error Recording Data <br>" . mysqli_error($GLOBALS['con']);
}
}
else{echo "Provide all data in textboxes.";
}
}
function createDB(){
$servername='localhost';
$username='root';
$password='password';
$dbname='holdings';
//create connection to our database "holdings"
$con=mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection Failed: ". mysqli_connect_error());
}
//create Database
$sql= 'CREATE DATABASE IF NOT EXISTS $dbname';
if(mysqli_query($con,$sql)){
$con = mysqli_connect($servername,$username,$password,$dbname);
$sql= 'CREATE TABLE IF NOT EXISTS cryptoholdings(
username VARCHAR(25) NOT NULL,
BTC_holdings FLOAT(11) NOT NULL,
ETH_holdings FLOAT(11) NOT NULL,
DASH_holdings FLOAT(11) NOT NULL)';
if(mysqli_query($con,$sql)){
return $con;}
else{
echo "Error when Creating Table...";
}
}
else{
echo "Error while creating Database...". mysqli_error($con);
}
}
function textboxValue($value){
$textbox = mysqli_real_escape_string($GLOBALS['con'],trim($_POST[$value]));
if(empty($textbox)){
return false;
}
else{
return $textbox;
}
}
First check that the connection was very okay by echoing something from the db or by doing sth on the db. 2nd try using another method other than the global con being used. For the purpose of testing and finding solution, I recommend you create a simpler table (of one or 2 fields) and try inserting into the fields. I recommend this method of connection below.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

I have sort of php code, in this i want to send connection variable ($conn) into another page so that i can create table for database dynamically

<?php
$a = $_GET['host'];
$b = $_GET['username'];
$c = $_GET['password'];
$d = $_GET['db_name'];
define("localhost",$a);
define("username",$b);
define("password",$c);
define("db",$d);
$conn = mysqli_connect(localhost,username,password);
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt create database query execution
$sql = "CREATE DATABASE $d ";
if(mysqli_query($conn, $sql)){
echo "Database demo created successfully";
header("Location:create_table.php");
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
In this i need to send $conn with header to send it to create_table.php page.
because i am getting details of connection from user. so i cannot include this file into create_table.php . please help to find out how can i send connection variable into another file.
<?php
$server= "localhost";
$user= "root";
$pass= "";
$conn= mysqli_connection($server, $user, $pass);
if(!$conn){
echo "Database Connection Install Failed ! ".mysqli_errno() ;
}
else {
echo "Database Connection Establiseh Successfully! ";
}
?>

PHP Redirect stopped working?

I have wrote a script to update a MySql DB from a form.
After the DB has been updated I want the page to auto redirect to another page.
This has been working fine however since switching hosting provider non of my sites re-directs work.
Here is the code:
<?php
$servername = "localhost";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id= $_POST[id];
$dob=$_POST[dob];
$sql=("update users set dob='$dob' where id='$id'")or die('Error 23 ' . mysql_error());
if ($conn->query($sql) === TRUE) {
echo "Updated successfully<br /><br />";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
<?php
header("location:index.php?action=updated"); ?>
When I run the code the DB updates but the page just displays Updated successfully?
try using javascript to redirect like below:
if ($conn->query($sql) === TRUE) {
echo "<script>
alert('Updated successfully');
window.location.href = 'index.php?action=updated';
</script>";
}
Don't echo anything and try to redirect afterwards. Instead simply redirect without any echoing.
if ($conn->query($sql) === TRUE) {
header("location:index.php?action=updated");
exit;
} else
echo "Error: " . $sql . "<br>" . $conn->error;
try this :
<?php
ob_start();
header('Location: http://www.example.com/index.php?action=updated', true);
?>

Data already Inserted I want to update the data

I am getting issue in update code.I am able to inserted data in database.I am passing null values in table. I want to update that null values.I am getting the sccessfully message but data is not updating. Please help me....
//Insert code
<?php
// Start the session
session_start();
?>
<?php
// Start the session
session_start();
?>
<?php
try{
$product=$_POST['product'];
/*
$product2=$_POST['product2'];
$product3=$_POST['product3'];
*/
// form data
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$conn=mysql_connect($servername, $username, $password) or die('Connection failed: ' . mysql_error());
#mysql_select_db($database, $conn) or die("Could not select your database".mysql_error());
$insertQuery = "Insert into contactus(Id,Product) values('null','$product')";
$result = mysql_query($insertQuery);
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../index.html';</script>";
}
else
{
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../index.html';</script>";
}
mysql_close($conn);
header('Location: /newstore/contact.html');
}
catch(Exception $e) {
echo ("<script>alert('Something went terribly wrong. Please try again later.');location.href = ''../index.html';</script>");
return false;
}
?>
//Update code
<?php
// Start the session
session_start();
?>
<?php
try{
// form data
$name=$_POST['name'];
$email=$_POST['email'];
$mobile=$_POST['mobile'];
$product=isset($_POST['product']);
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$conn=mysql_connect($servername, $username, $password) or die('Connection failed: ' . mysql_error());
#mysql_select_db($database, $conn) or die("Could not select your database".mysql_error());
;if ((strlen($name) < 3) or (strlen($email) < 3) or(strlen($mobile) < 3))
{
echo ("<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>");
}else
{
$UpdateQuery = "update contactus set Name='$name',Email='$email',Mobile='$mobile' where Id='(select count(*) from contactus)' ";
$result = mysql_query($UpdateQuery);
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../newstore/index.html';</script>";
}
else
{
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
}
}
mysql_close($conn);
}
catch(Exception $e) {
echo ("<script>alert('Something went terribly wrong. Please try again later.');location.href = ''../newstore/index.html';</script>");
return false;
}
?>
I see no point in doing an Insert and then doing an Update. You already have all the data, so just Insert it all at once.
EDIT AFTER COMMENTS
First Handler:
<?php
start_session();
if(isset($_POST['product'])){
$product=$_POST['product'];
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$mysqli = new mysqli($servername, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again. (" . mysqli_connect_error() . ")');location.href = '../newstore/index.html'</script>");
exit();
}
if ($result = $mysqli->query("INSERT INTO contactus (Id,Product) VALUES ('null','$product')")) {
// Grab new ID when INSERT is successfull, add it to Session
$_SESSION['contact_id'] = $mysqli->insert_id;
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../index.html';</script>";
} else {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../index.html';</script>";
$mysqli->close();
exit();
}
$mysqli->close();
}
header('Location: /newstore/contact.html');
?>
Second Handler:
<?php
start_session();
// form data
$name=isset($_POST['name'])?$_POST['name']:"";
$email=isset($_POST['email'])?$_POST['email']:"";
$mobile=$_POST['mobile'];
if ((strlen($name) < 3) || (strlen($email) < 3) || (strlen($mobile) < 3)){
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
exit();
}
//database Connection details
$servername = "localhost";
$username = "root";
$password = "";
$database="store";
$error = "";
$mysqli = new mysqli($servername, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again. (" . mysqli_connect_error() . ")');location.href = '../newstore/index.html'</script>");
exit();
}
if ($stmt = $mysqli->prepare("UPDATE contactus SET `Name`=?, `Email`=?, `Mobile`=?) WHERE `ID`=?")){
/* bind parameters for markers */
$stmt->bind_param("sssi", $name, $email, $mobile, $_SESSION['contact_id']);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
if($result){
echo "<script>alert('Thank You. Your Data Received Succefully.');location.href = '../newstore/index.html';</script>";
} else {
echo "<script>alert('Something went wrong with your data inserted. Please fill the form again.');location.href = '../newstore/index.html';</script>";
}
$stmt->close();
}
$mysqli->close();
?>

Categories