PHP to delete a row from mysql database [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
I have a PHP that I am unable to get it to work. Its function is to connect to my db and delete the input email address from the database. But for some reason, the result is always "Data Not Deleted". I am sure of all the details like db connect details and columns names etc. still the code doesn't work.
Code:
<?php
// php code to Delete data from mysql database
if(isset($_POST['delete']))
{
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "newsletter";
// get id to delete
$email = $_POST['email'];
// connect to mysql
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// mysql delete query
$query = "DELETE FROM `email_user` WHERE `email` = $email";
$result = mysqli_query($connect, $query);
if($result)
{
echo 'Data Deleted';
}else{
echo 'Data Not Deleted';
}
mysqli_close($connect);
}
?>
<!DOCTYPE html>
<html>
<head>
<title> PHP DELETE DATA </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="unsub.php" method="post">
ID TO DELETE: <input type="text" name="email" required><br><br>
<input type="submit" name="delete" value="Clear Data">
</form>
</body>
</html>
Please point out what I am doing wrong in here?
Thanks

You need to add quotes around $email in your query as it is a string.
$query = "DELETE FROM `email_user` WHERE `email` = '$email'";
Note:- Your code is wide-open for SQL INJECTION.You have to use prepared statements
Help reference:-
mysqli::prepare
PDO::prepare

Try modifying the query to following:
"DELETE FROM `email_user` WHERE `email` = '$email'"

Related

Set up simple form submission to mySQL database [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Reference - What does this error mean in PHP?
(38 answers)
Can I mix MySQL APIs in PHP?
(4 answers)
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 4 years ago.
I'm trying to set up a very simple form to submit data to a MySQL database (I've never actually set up a MySQL database or the connections required to interact with it via a web form myself before).
I have a simple HTML form in my web page, to allow the user to enter a name, email address, and a question that they want to ask:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
Page title
</head>
<body>
<h1>Customer Information</h1>
<form id="customerInfoForm" accept-charset = "utf-8" action = "insert.php" method = "post" >
<table id = "customerInfoTable">
<tr><td>Name: </td><td><input type = "text" name = "customerName" ></input></td></tr>
<tr><td>Email: </td><td><input type = "text" name = "customerEmail"></input></td></tr>
<tr><td>Enquiry: </td><td><input type = "text" name = "enquiryText"></input></td></tr>
</table>
<br>
<input type = "submit" value = "Sumit"></input>
</form>
</body>
</html>
<?php
$con = mysql_connect('localhost','[retracted]','[retracted]');
if(!$con) {
echo 'Not connected to server!';
}
$Name = $_POST['customerName'];
$Email = $_POST['customerEmail'];
$Query = $_POST['enquiryText'];
$sql = "INSERT INTO Enquiries(Name, Email, Query) VALUES ('$Name', '$Email', '$Query')";
if(!mysql_query($con, $sql)) {
echo 'Data not inserted';
} else {
echo 'Data inserted';
}
?>
In the insert.php file that's called when clicking the 'Submit' button on the form, I have the following:
<?php
//Check if data has been entered
if( isset( $_POST['data'] ) && !empty( $_POST['data'] ) )
{
$data = $_POST['data'];
} else {
header( 'location: form.html' );
exit();
}
//set up mysql
$sql_server = 'localhost';
$sql_user = 'user';
$sql_pwd = 'password';
$sql_db = 'database';
//Connect to sql database
$mysqli = new mysqli( $sql_server, $sql_user, $sql_pwd, $sql_db) or die( $mysqli->error );
//Insert details into table
$insert = $mysqli->query( "INSERT INTO Enquiries ('data') VALUE ( '$data' )" );
//Close mysqli connection
$mysqli->close;
?>
However, currently, when I click the 'Submit' button on my form, I get an error displayed in my browser:
error ); //Insert details into table $insert = $mysqli->query( "INSERT INTO Enquiries ('data') VALUE ( '$data' )" ); //Close mysqli connection $mysqli->close; ?>
i.e. the above error is displayed as the content of the webpage, so it seems I'm doing something wrong with the database connection, but I'm not sure what... Can anyone point me in the right direction?

Validating email for a specific username using php and MYSQL [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
So, I am trying to validate whether username and email entered by a user in an html form are correct according to Database
I have a database called testing and a table called info which has two fields:
name and email.
this is the code
<html>
<body>
<form action="conn.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname="testing";
$name=$_POST['name'];
$mail=$_POST['email'];
// Create connection
$conn1 = new mysqli($servername, $username, $password, $dbname);
$query='select email from info where name= "$name"';
$results = mysqli_query($conn1,$query);
$row= mysqli_fetch_assoc($results);
echo $row["email"];
$email=$row["email"];
if($mail==$email){
echo " correct values";
}
else
echo " incorrect";
//echo $name, $email;
// Check connection
//if ($conn1->connect_error) {
// die("Connection failed: " . $conn1->connect_error);
//}
//echo "Connected successfully";
$conn1->close();
?>
but the result is always incorrect. The values that i enter in the text boxes match the values in the database.
You should use placeholders, the code would be something like this:
$query = 'SELECT emal FROM info WHERE name = ?';
$stmt = mysqli_stmt_prepare($conn1, $query);
mysqli_stmt_bind_param($stmt, 's', $name);
mysqli_stmt_execute($stmt);
$results = mysqli_stmt_get_result($stmt);
For better readable code, read up on the object-oriented mysqli-interface, or better yet use PDO.
alternatively you can use string concatenation like
Update this line
$query='select email from info where name= "$name"';
with
$query='select email from info where name= "'.$name.'" ';
or with
$query="select email from info where name= '".$name."' ";

php password_verify still not working

I have read many articles on this password_hash and has applied as much as I can if not all the things I read about it
Still the password_verify still refuses to authenticate values no matter how much I tried. PHP Version 5.61.6 and SQL version 5.7.9
any form of help is appreciated, am already exhausted from trying many string combinations
<!DOCTYPE html>
<html>
<head>
<title>Administrator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?PHP
//.......all variables are collected from html form....
$conn = mysqli_connect("localhost", "uname", "pword", "dbname");
mysqli_set_charset($conn, 'utf8');
//.......`SN` column has the unique attribute
$sql = "SELECT * FROM Sign_Up WHERE `SN`=$sn";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$date = date('Y-m-j g:i:s');
//.......idgen is a function previously defined
$id = idgen();
//.......prints $id before hashing....
echo $id."<BR>";
$id = password_hash('$id', PASSWORD_DEFAULT);
//......string length before storing
echo strlen($id)."<BR>";
//......table columns
$f = $row["FirstName"];
$l = $row["LastName"];
$bn = $row["BusinessName"];
$ba = $row["BusinessAddress"];
$sq = "INSERT INTO Distributors (`FirstName`, `LastName`, `BusinessName`, `BusinessAddress`) VALUES ('$f', '$l', '$bn', '$ba')";
$res = mysqli_query($conn, $sq);
}
}
?>
</body>
</html>
And the code for verifying the hash is
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<?PHP
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysqli_set_charset($conn, 'utf8');
//.....phone number has a unique attribute
$sql = "SELECT `ID` FROM Distributors WHERE `PhoneNumber`='number'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$result1= mysqli_num_rows($result);
$look = mysqli_fetch_array($result)['ID'];
print $look."<BR>";
$look = trim($look);
print $look."<BR>";
print strlen($look)."<BR>";
//......all print statements yields expected results and hashed password is stored
//......in VARCHAR (255)...I also tried CHAR
$ver = password_verify('user input data', '$look');
if ($ver) {
print "ok";
}
else {
print "no";
}
?>
</body>
</html>
Use php variables without any quote or inside double quotes, "":
$id = password_hash($id, PASSWORD_DEFAULT); // no quotes around $id
$ver = password_verify('user input data', "$look"); // double quotes around $look
Single quote strings are not parsed i.e. treated as literal strings while double quoted strings are parsed and therefore variables names are expanded with their values.
When hashing use:
$id = "school";
Password_hash($id);
When verifying use:
Password_verify($id, $data_from_database);

Access denied for user 'root'#'localhost' (using password: NO)

I'm using a simple form to do a database query. The database is accessed via password which I've included in the code. I'm not sure why I keep hitting the error on the string escape and the undefined variable $query = htmlspecialchars($query);
<?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);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form action="Search2.php" method="POST">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
<?php
if (isset($_POST['query']))
$query = $_POST['query'];
if (!empty($query))
$query = $_POST['query'];
// gets value sent over search form
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT LastName, FirstName FROM Staff
WHERE (`LastName` LIKE '%".$query."%') OR (`FirstName` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<p><h3>".$results['LastName']."</h3>".$results['FirstName']."</p>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
</body>
</html>
The issue here is that you've invoked a mysqli object with your credentials, however, later you try to execute with the mysql_ procedural method. You don't have a connection there. You need to stick with the mysqli object. Furthermore, you should use prepared statements to handle your user input on SQL queries.
Remove these, we don't need to do sanitization for prepared statements:
//BYE!
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
Now let's use the mysqli object and OOP prepared methods. However, first we need to construct our like statements as our query's variables aren't executed, you can't concatenate %?% directly into the prepared() statement.
$query = '%'.$query.'%';
$stmt = $mysqli->prepare("SELECT LastName, FirstName FROM Staff
WHERE LastName LIKE ? OR FirstName LIKE ?");
Now we can bind the parameters to our $stmt object.
$stmt->bind_param('ss', $query, $query);
Let's execute it now and get our data back.
$result = $stmt->execute();
Then we can loop:
while ($row = $result->fetch_assoc()) {
echo "<p><h3>".$result['LastName']."</h3>".$result['FirstName']."</p>";
}
Edit
You also don't need to escape your column names with a backtick because:
They don't have - in the name
They aren't reserved special words in MySQL.
make sure your PHP version is below 7.0 as stated here:
http://php.net/manual/en/function.mysql-real-escape-string.php
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_real_escape_string()
PDO::quote()

PHP not inserting into tables

I'm having trouble getting a practice signup form to submit data to my database ...
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$name = $email = $password = "";
?>
<form method="post">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Password: <input type="text" name="password">
<br><br>
<input type="submit" value="Submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
function fix_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
In addition to Ugur's answer, you are mismatching mysqli commands and mysql commands. Here's how to do this in an object oriented fashion:
// create mysqli database object
$mysqli = new mysqli_connect("localhost","username","password","database");
// store your query in a variable. question marks are filled by variables
$sql = "INSERT INTO table_name ('username','password') VALUES (?,?)";
// prepare command uses $sql variable as query
$stmt = mysqli->prepare($sql);
// "ss" means your 2 variables are strings, then you pass your two variables.
$stmt->bind_param("ss",$name,md5($password));
// execute does as it seems, executes the query.
$stmt->execute();
// then print your success message here.
Using prepared statements removes the need to sanitize user input, as harmful input is not substituted into the query directly. For more reading:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
There are some good tips for using prepared statements in many different scenarios, as well as towards the bottom, there is an explanation on how prepared statements prevent SQL injection.
Missing table name
mysql_query("INSERT INTO ...... ('username','password') VALUES ('$name', md5('$password'))");
You're mixing mysql_* with mysqli_* functions, i.e.: mysqli_connect and mysql_query and you're wrapping your column names in quotes, plus you're missing the table name to insert into.
Try the following, fixed code:
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysqli_query("INSERT INTO `your_table` (`username`,`password`) VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
You're also using password storage technology that dates back to 1996. MD5 is no longer considered safe to use.
I suggest you look into PHP's password function: http://php.net/password
And if you're having problems with your fix_input() function, you should consider using the mysqli_real_escape_string() function.
then setting up a DB connection while passing a variable to it.
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
and instead of using:
$name = fix_input($_POST["name"]);
use the following:
$name= mysqli_real_escape_string($db, $_POST['name']);
and do the same for the rest.
you don't have table name in your query! also do not use quotation in your column name :)
you have mixed up mysqli and mysql.
Change
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
to
mysqli_query("INSERT INTO yoour_table(username',password) VALUES ('$name', md5('$password'))");

Categories