I'm working on a very basic PHP programme. I'm very new to PHP and am aware that I'm using the older versions i.e not PDO. I've been working on this for a while and can't figure out why it isn't working.
I'm simply trying to delete an item from my table which matches the user input.
((also if anyone has any easy recommendations I can use to have a safer delete function as I am aware if the user input is 'r' for example, a huge chunk of the table will be deleted))
Here is my code:
<?php
//delete from table
if(isset($_POST['delete1']))
{
$deletevalue = $_POST['deletevalue'];
$deletequery = "DELETE FROM users WHERE deletevalue = $deletevalue";
$deleteresult = deleteTable($deletevalue);
}
function deleteTable ($deletevalue)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$delete_fromTable = mysqli_query($connect, $deletevalue);
print mysqli_error($connect);
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="zzz.php" method="post" />
<p> Remove Item: <input type="text" name="deletevalue" placeholder="Item
Name" /> </p>
<input type="submit" name ="delete1" value="submit" />
</form>
</body>
</html>
regarding all comments, and completely OK with security statements, you should really consider using PPS : Prepared Parameterized Statements. This will help Preventing SQL injection. Plus : use error_reporting(E_ALL); ini_set('display_errors', 1); on top of your pages will help PHP give you hint about errors :)
This is a way (not the only one) to handle your query.
Please read carefully and adapt names according to your DB structure and column names.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$host = ""; /* your credentials here */
$user = ""; /* your credentials here */
$pwd = ""; /* your credentials here */
$db = ""; /* your credentials here */
/* store in PHP variable */
$deletevalue = $_POST['deletevalue'];
echo"[ is my var ok ? -> $deletevalue ]"; /* just checking value */
// connexion to db
$mysqli = mysqli_connect("$host", "$user", "$pwd", "$db");
if (mysqli_connect_errno()) { echo "Error: no connexion allowed : " . mysqli_connect_error($mysqli); }
$query = " DELETE FROM `users` WHERE deletevalue = ? ";
$stmt = $mysqli->prepare($query); /* prepare query */
$stmt->bind_param("s", $deletevalue); /* bind param will sanitize -> 's' is for a string */
print_r($stmt->error_list); /* any error ? */
print_r($stmt->get_warnings()); /* any error ? */
print_r($stmt->error); /* any error ? */
/* another ways of checking for errors :
if (!($stmt = $mysqli->prepare(" DELETE FROM `users` WHERE deletevalue = ? "))) {
echo "Error attempting to prepare : (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("s", $deletevalue)) {
echo "Error attempting to bind params : (" . $stmt->errno . ") " . $stmt->error;
}
*/
if (!$stmt->execute()) { echo"false"; echo "Error attempting to execute : (" . $stmt->errno . ") " . $stmt->error; } else { echo"true"; }
?>
Here your code will be looks like (Except security issue)
In this code you are deleting your record on the basis of firstName of the user thats why in where clause WHERE firstName = '$deletevalue' firtName there.
if(isset($_POST['delete1']))
{
$deletevalue = $_POST['deletevalue'];
//here put your table column in where clause
$deletequery = "DELETE FROM users WHERE firstName = '$deletevalue'"; //if your form enters name of the users
$deleteresult = deleteTable($deletequery);
}
function deleteTable ($deletequery)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$delete_fromTable = mysqli_query($connect, $deletequery);
print mysqli_error($connect);
}
See in your where clause WHERE name = if you are deleting on the basis of name of the user.
and also see deleteTable($deletequery); you need to pass your query not the value.
Note:
Yes, I know you are learning basic things but my recomendations are
1) Use Prepared statements, explore little bit about it
2) Delete records based on ID (unique field) not name, name (firstName) might be same for multiple users in users table
Related
I have a form handler (I believe that is the correct terminology) called insert.php, this is used to post form data to a MySQL database on localhost. I have different tables each containing a single record and would like to choose which table the data goes to. I could duplicate the insert.php file for each table but that seems messy. How do I choose which table the data goes to via post?
current insert.php:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$sql = "UPDATE PiBQ_Temp SET reqdTemp = '$_POST[setTemp]' WHERE tempKey = 1";
mysqli_query($con,$sql);
echo "1 record added";
header ('location: index.php');
mysql_close($con)
?>
What I think is needed for the $sql = variable:
$sql = "UPDATE '$_POST[myTable]' SET '$_POST[myField]' = '$_POST[myValue]' WHERE tableKey = 1"
My html is this:
<form action="insert.php" method="post">
<input type="text" name="myField" value="<?= $myValue ?>"/>
<input type="submit" value="Submit" />
what html should I be using to feed my revised insert.php file above, if that is correct? Thanks.
try this format
$sql = "UPDATE `".$_POST['myTable']."` SET `".$_POST['myField']."` = '".$_POST['myValue']."' WHERE `tableKey` = 1";
or
$mysqli = new mysqli("host", "user", "password", "db");
$stmt = $mysqli->prepare("UPDATE `".$mysqli->real_escape_string(str_replace(" ", "", strtolower($_POST['myTable'])))."` SET `".$mysqli->real_escape_string(str_replace(" ", "", strtolower($_POST['myField'])))."` = ? WHERE `tableKey` = 1");
$stmt->bind_param("s",$_POST['myValue']);
$stmt->execute();
You should use prepared statement instead
There's some wider practices that could be improve, but based on your current code/structure, I would use something like this:
<?php
require_once 'login.php';
try {
$con = new mysqli("host", "user", "password", "db");
} catch (mysqli_sql_exception $e) {
echo "Failed to connect to MySQL: ".$e;
}
$table = (isset($_POST['myTable'])) ? $_POST['myTable'] : null;
$reqdTemp = (isset($_POST['setTemp'])) ? $_POST['setTemp'] : null;
$tempKey = (isset($_POST['setKey'])) ? $_POST['setKey'] : null;
switch($table) {
case "thisTable":
$qry = "UPDATE `thisTable` SET thisField = ? WHERE thisKey = ?";
break;
case "thatTable":
$qry = "UPDATE `thatTable` SET thisField = ? WHERE thisKey = ?";
break;
case "anotherTable":
$qry = "UPDATE `anotherTable` SET thisField = ? WHERE thisKey = ?";
break;
default:
// do something?
break;
}
$stmt = $conn->prepare($qry);
$stmt->bind_param("si", $reqdTemp, $tempKey);
$stmt->execute();
if(!$stmt->execute()) {
echo $stmt->error;
}
else {
echo "1 record added";
}
header ('location: index.php');
mysql_close($con)
?>
Two things to note: The switch statement allows you to provide a different query based on the table name, but it assumes that the same structure is in place (i.e. update String Where Integer).
I've also assumed the thisKey is posted too, as 'setKey'.
Secondly, prepared statements.
This is more of a hint, rather than a whole solution, and you probably need to tidy it up and make it work for you outside of my assumptions
When I run the page with an empty database, it will insert the data correctly. When I run the page again, it displays there is already an ID in the database, but it inserts it anyway. Not sure how or why but I've tried every combination of booleans inside the if statements and cant get it to chooch correctly.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database:
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Ask the database for some sweet, sweet data:
$stmt1 = "SELECT orderID FROM orders";
$result = $mysqli->query($stmt1);
//flag (we want to believe that there are no similar IDS so lets make it true):
$flag = true;
//while we got some data, display that shit
while ($row = $result->fetch_assoc()) {
//asign data to variable:
$rowOrderID = $row['orderID'];
//Does it match? if it does set the flag to false so it doesnt get inserted.
if ($rowOrderID == $orderID) {
echo "Row ID" . $row["orderID"] . " Passed ID: " . $orderID . "<br>";
echo "This order is already in the database" . "<br>";
$flag = false;
}
}
//hand the flag over to who ever needs it
return flag;
}
.
if (checkOrderID($orderID) == true) {
//some mysql insert logic here
}
Why are you making this complicated. just do something like this:
$con=mysqli_connect("localhost","root","","price");
$check_query = mysqli_query($con,"SELECT * FROM orders WHERE orderID = $orderID");
if (mysqli_num_rows($check_query) == 0) {
//mysql insert logic here
}
(Noted of course you are going to have your connection logic as well)
Note: You are using Mysqli in object oriented manner but in this example i have not used object oriented manner of DB connection. The connection variable $con must be passed to mysqli_query() method.
Also... random side note, but it's generally a good idea to have a password for your root mysql user.
Here better and short, but please try to use DB connection globally not inside your mothod and try to use prepared statements. But except those you can use following code.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database: I suggest use global DB connection
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//gets recodrs based on $orderID passed to this method
$stmt1 = "SELECT * FROM orders where orderID=$orderID"; //Try to use prepared statement
$result = $mysqli->query($stmt1);
//Store number of rows found
$row_count = $result->num_rows;
if($row_count>0){
return true;
}
else{
return false;
}
}
I am trying to develop a registration form.
When I fill all the filed and submit the form, no error showing
the server is connected but no data on mysql database table. Bellow L attached the action file of form. What do I miss? and how can I solve it?
<?php
$mysqli_servername = "localhost";
$mysqli_username = "admin_try";
$mysqli_password = "rFT5hePS5u";
$mysqli_database = "indepe";
// Create connection
$conn = mysqli_connect($mysqli_servername,$mysqli_username,$mysqli_password,$mysqli_database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<a href='index.html'>Back to main page</a>";
if (isset($_GET["submitreg"]))
{
$id= mysqli_real_escape_string($conn, $_POST['id']);
$country = mysqli_real_escape_string($conn, $_POST['country']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
$re_password = mysqli_real_escape_string($conn,$_POST['re_password']);
$compnay = mysqli_real_escape_string($conn,$_POST['compnay']);
$contact = mysqli_real_escape_string($conn,$_POST['contact']);
$tell = mysqli_real_escape_string($conn,$_POST['tell']);
$sql = "INSERT INTO registration(id,country,email,password,re_password,compnay,contact,tell);
VALUES('id','$country','$email','$password','$re_password','$compnay','$contact'),'$tell'";
if ($conn->query($sql) === TRUE) {
echo "record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
if (mysqli_query($conn, $sql)) {
echo " record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
//$conn->close();
mysqli_close($conn);
?>
There are few errors in your insert query
Remove the semicolen after tell in your insert query
You gave id in values instead of $id
$tell is outside the bracket
$sql = "INSERT INTO registration(id,country,email,password,re_password,compnay,contact,tell) VALUES('$id','$country','$email','$password','$re_password','$compnay','$contact','$tell'");
Im not sure whether that is your problem or it occured your copying your code..because no error was shown
I think you mistake in insert query remove semicolon before VALUES keyword and if id column auto increment then no need to add it in insert query otherwise you need add it properly and ,'$tell' is outside the bracket please make it proper
$sql = "INSERT INTO registration(country,email,password,re_password,compnay,contact,tell) VALUES ('$country','$email','$password','$re_password','$compnay','$contact','$tell')";
I thing you need to add privileges to particular user to insert records. as you have declared $mysqli_username = "admin_try";. now go to localhost/phpmyadmin and then add privileges to particular user!!
You are using $_GET check and for submitting the form which is wrong. It's always recommened to do POST request for form submission.
if (isset($_GET["submitreg"]))
But, later in your code to get the the data you are using $_POST.
$id= mysqli_real_escape_string($conn, $_POST['id']);
Please check your form method in html make it POST and change
if (isset($_GET["submitreg"]))
to
if (isset($_POST["submitreg"]))
I have a database table which has two columns, business and tourist.
I ask a user to select one of them from dropdown list, then use the result in a SELECT statement in MySQL. I assign this column to $cclass, then I make this statement SELECT $cclass FROM flights ....
But it always returns NULL. Why does it return NULL and how do I fix this?
My code:
$check = mysql_query("SELECT $cclass FROM flights WHERE flight_no = '$flightno'");
while ($result = mysql_fetch_assoc($check))
{
$db_seats = $result['$cclass'];
}
you should replace this line:
$db_seats = $result['$cclass'];
with this:
$db_seats = $result[$cclass];
string between 2 single quotes doesn't parsed:
Strings
Have you tried doing the following:
$check = mysql_query("SELECT".$cclass." FROM flights WHERE flight_no = '$flightno'");
First of all, this code has a serious security issue, as it is vulnerable to SQL Injection. You should be using the MySQLi extension instead, and properly filtering your input.
Try something like this:
<?php
/* Create the connection. */
$mysql = new mysqli("localhost", "username", "password", "myDB");
if ($mysql->connect_error)
{
error_log("Connection failed: " . $mysql->connect_error);
die("Connection failed: " . $mysql->connect_error);
}
/* Sanitize user input. */
if (!in_array($cclass, array('business', 'tourist')))
{
error_log("Invalid input: Must be 'business' or 'tourist'");
die("Invalid input: Must be 'business' or 'tourist'");
}
$statement = $mysql->stmt_init();
$statement->prepare("SELECT $cclass FROM flights WHERE flight_no = ?");
$statement->bind_param("s", $flightno);
if (!$statement->execute())
{
error_log("Query failed: " . $statement->error);
die("Query failed: " . $statement->error);
}
if ($statement->num_rows < 1)
{
echo "No results found.";
}
else
{
$statement->bind_result($seats);
while ($statement->fetch())
{
echo "Result: $seats";
// Continue to process the data... You can just use $seats.
}
}
$mysql->close();
However, the reason your original example is failing, is that you're quoting $cclass:
$db_seats = $result[$cclass];
However, please do not ignore the serious security risks noted above.
When using a button to submit an information which is prepared but you want to add a something like title to the button, so the "value" with form like :
<form action="" method="POST">
<input type="submit" name="Man" value="Man">
</form>
With the php code like this :
if (isset($_POST['Man'])) {
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "
UPDATE users
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ss', $_POST['Man'], $_SESSION['username']);
$ok = $stmt->execute();
if ($ok == TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " .$stmt->error;
}
}
This is the code, which so many people using (normal easy code with prepared statements) but there is a one mistake... If somebody change the value of Man to eg. lol , the gender in database will be set to "lol" because the value is "lol"...
I noticed this problem in so many websites and codes here, and so the way to fix this, is to pre-define the $_POST... Check answer
You need to whitelist the allowed values in an array
if (isset($_POST['Man'])) {
$allowed_values=array("Man","Women");
if(!in_array($_POST['Man'],$allowed_values)){
echo"error message";
die();
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "
UPDATE users
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ss', $_POST['Man'], $_SESSION['username']);
$ok = $stmt->execute();
if ($ok == TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " .$stmt->error;
}
}
One simple thing to do is to pre-define the $_POST so the value will never be changed...
with simple one line code :
$_POST['Man'] = Man;
By adding this code to your code, the value cannot be changed with html so
the result wll be still the "Man" and you are good to go.