Wordpress: PHP delete database row in foreach cycle - php

Hi guys I am very new to PHP development.
I am writing a smiple script to get and email perameter from the url, cycle through some rows in a database table and delete the row if it is found.
I have got everything except the deleting of the row. I would really appreciate someone talking me through my mistake to help me understand. I think the error lies in the WHERE condition.
The error message I get is:
ERROR: Could not able to execute DELETE FROM wp_email_address_db WHERE alaofolasade#yahoo.com==alaofolasade#yahoo.com.
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
global $wpdb;
//sanatise and lowercase email addy from URL
$emailToRemove = filter_var ( strtolower($_GET["usermail"]), FILTER_SANITIZE_EMAIL);
//get DB table
$data = $wpdb->get_results("SELECT * FROM wp_email_address_db`");
foreach ($data as $d) {
//sanatise and lowercase email addy from DB
$email = filter_var ( strtolower($d->email_address), FILTER_SANITIZE_EMAIL);
//check if the email addy is in this row
if($email == $emailToRemove){
//get info
echo 'true <br/>';
echo 'id: '.$d->id.'<br/>';
//I need to delete this row
$sql = "DELETE FROM wp_email_address_db WHERE $email = $emailToRemove";
if(mysqli_query($link, $sql)){
echo "Records were deleted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
}
// $columnTitles = ['id','email_address','imported_via'];
?>

You have a typo in email and the value in where clause should be within single quotes:
change this to:
$sql = "DELETE FROM wp_email_address_db WHERE email = '$emailToRemove'";

Your query should be this :
$sql = "DELETE FROM wp_email_address_db WHERE email = '$emailToRemove'";

It is always better to use quotation (single quote', double quote ") also defining the column with back-tick.
Query:
$sql = "DELETE FROM wp_email_address_db WHERE `email` = '".$emailToRemove."'";
Your main error is $email which should be the column name with back-tick here WHERE $email = $emailToRemove

Should not be the query something like
DELETE FROM wp_email_address_db WHERE email_field_name = '$emailToRemove'
instead of
DELETE FROM wp_email_address_db WHERE $email = $emailToRemove
In your query you are passing the value of $email as field name and I assume that the field alaofolasade#yahoo.com does not exist

Try replacing
$sql = "DELETE FROM wp_email_address_db WHERE $email = $emailToRemove";
with
$sql = "DELETE FROM wp_email_address_db WHERE '$email' = '$emailToRemove'";

I removed the foreach, you don't need to retrieve ALL the mails from your database.
Moreover I used the prepared statements to avoid SQL injections
This kind of script which perform delete query to database HAVE to be protected from all users. Only admins should be allow to this script
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
// WARNING: You should check the identity of the user performing this action, MySql DELETE action is dangerous
global $wpdb;
//sanatise and lowercase email addy from URL
$emailToRemove = filter_var ( strtolower($_GET["usermail"]), FILTER_SANITIZE_EMAIL);
$sqlDeleteQuery = '
DELETE
FROM wp_email_address_db
WHERE email = ?
';
$statement = mysqli_prepare($link, $sqlDeleteQuery);
// Bind the email to your query (the ? ), this avoid the SQL injection attack
$statement->bind_param('s', $emailToRemove);
if (false !== mysqli_stmt_execute($statement)) {
die('The MySql query failed ! Error : ' . mysqli_error($link));
}
$emailsDeleted = mysqli_stmt_affected_rows($statement);
echo sprintf('"%d" emails deleted', $emailsDeleted);
I can't try the above code, so please let me know if something is wrong :)

Solved it by:
<?php
require_once($_SERVER["DOCUMENT_ROOT"]."/wp-load.php");
if (isset($_GET["usermail"])) {
global $wpdb;
$remove = filter_var(strtolower($_GET["usermail"]), FILTER_SANITIZE_EMAIL);
$wpdb->query("DELETE FROM wp_email_address_db WHERE email_address='$remove'");
echo "You have successfully been unsubscribed.";
}
?>

Related

How I should fix if else statement didn't work

I want to test if user enter incorrect file number and ic, the message "Inccorect ref no and ic no" will shown, but it didn't work like that. It always shown the message "Thanks you for register attendance with us." Help me please..I'm new.
<?php
require "init.php";
$file_number = $_POST["file_number"];
$ic_no = $_POST["ic_no"];
$attendance = $_POST["attendance"];
//$ic_no = $_REQUEST['ic_no'];
$sql = "INSERT INTO reg_attend(file_number,ic_no,attendance) SELECT reg_meeting.file_number,reg_staff.ic_no,'".$attendance."' FROM reg_meeting,reg_staff WHERE (reg_meeting.file_number = '".$file_number."' AND reg_staff.ic_no = '".$ic_no."')";
$result = mysqli_query($conn,$sql);
$response = array();
if($result)
{
//var_dump($result);
$code = "reg_success";
$message = "Thanks you for register attendance with us.";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode($response);
}
else
{
$code = "reg_failed";
$message = "Incorrect REF No. and IC No.";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode($response);;
}
mysqli_close($conn);
?>
You need to validate your incoming data before you insert into your DB. It looks like currently, you will be inserting empty values into your reg_attend table. As this is likely successful, you will not be reaching the else.
If you need to validate that the passed in data exists, do a select first e.g.
SELECT reg_meeting.file_number,reg_staff.ic_no,'".$attendance."' FROM reg_meeting,reg_staff WHERE (reg_meeting.file_number = '".$file_number."' AND reg_staff.ic_no = '".$ic_no."')"
then check the results of that, before inserting.
As a side note, please please DO NOT use this code as shown. You should prefer to use query parameters with either PDO or mysqli. See https://www.php.net/manual/en/pdo.prepare.php

how to get verify if user is already registered

Guys, I am new in PHP and nowadays am working on android application and in this application I have connected my app with PHP MySQL DB and everything is working fine but the problem is now I want to check if user cnic no is available in DB so query give me to return back if no so it will be inserted in DB please help me i will be really thankful to you all of the guys
Thanks
<?php
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$DefaultId = 0;
$ImageData = $_POST['image_path'];
$ImageName = $_POST['image_name'];
$Fullname = $_POST['fullname'];
$CNIC = $_POST['cnic'];
$Mobile = $_POST['mobile'];
$Address = $_POST['address'];
$District = $_POST['district'];
$Gender = $_POST['gender'];
$Education = $_POST['education'];
$Ward = $_POST['ward'];
$Ps = $_POST['ps'];
$Uc = $_POST['uc'];
$Bjf = $_POST['bjf'];
$By = $_POST['by'];
$Dt = $_POST['dt'];
$Email = $_POST['email'];
$GetOldIdSQL ="SELECT id FROM information ORDER BY id ASC";
$Query = mysqli_query($conn,$GetOldIdSQL);
while($row = mysqli_fetch_array($Query)){
$DefaultId = $row['id'];
}
$ImagePath = "images/$DefaultId.png";
$ServerURL = "laserlightskincare.com/$ImagePath";
//$InsertSQL = "insert into information (image_path,image_name,Fullname,CNIC,mobile,Address,District,ps,uc,ward,Gender,education,Doj,bjf,boy) values ('$ServerURL','$ImageName','$Fullname','$Cnic','$Mobile','$Address','$District','$PS','$UC','Ward','$Gender','Education','$Doj','$bjf','$boj','$boy')";
$InsertSQL = "insert into information (image_path,image_name,Fullname,CNIC,mobile,Address,District,Gender,education,ward,ps,uc,bjf,boy,Doj,email) values ('$ServerURL','$ImageName','$Fullname','$CNIC','$Mobile','$Address','$District','$Gender','$Education','$Ward','$Ps','$Uc','$Bjf','$By','$Dt','$Email')";
if(mysqli_query($conn, $InsertSQL)){
file_put_contents($ImagePath,base64_decode($ImageData));
echo "You have successfully registered";
}
mysqli_close($conn);
}else{
echo "Not Uploaded";
}
?>
First store your cnic value in an array using select statement and for() loop.
Then using the if() condition compare the cnic value in your db with the cnic value inserted. If the value is found then print that the cnic is used once else insert the data using your insert query.
Hope this helps you.
NOTE :
You should use some more appropriate value then the cnic value to check if the data is there in the db or not. I would suggest you compare the email addresses or mobile numbers of the users as they are unique for each user who signs up entering their email address and mobile number and it cannot be used again for the signup process.
Before the insert query; make a select query and check if the result is empty or not,
Another solution is to make a unique index for cnic information table so you can not insert a new record

sql query work only with small strings and not with big length strings

here's the php script tht gets the string and insert it in the db .
<?php
include 'connect.php';
$name = $_POST['name'];
$message = $_POST['message'];
$message = nl2br($message);
if(isset($name) && isset($message)){
$sql = "INSERT INTO messages VALUES('','".$name."', '".$message."')";
if($sqlrun = mysqli_query($connection , $sql)){
header('Location:../write.php');
}else{
echo "query doesnt work";
}
}
?>
what can be the reason it works only with small strings?
in the database the field is a text that contain 1000 bits maximum .
Why don't you check if there were any errors? any information is better than no information.
$sql = "INSERT INTO messages VALUES('','".$name."', '".$message."')";
if($sqlrun = mysqli_query($connection , $sql)){
header('Location:../write.php');
exit();
}else{
echo "query doesnt work: " . mysqli_error(); // jaaaj information!
}
I don't know why , but after i cheked the sql query time after time i realized that for the first argument in the values ( the '' which is dedicated for an auto-increment field) , i have to put NULL in there so that the query should be like this :
$sql = "INSERT INTO messages VALUES(NULL,'".$name."', '".$message."')";
again , i don't know exactly why now it works .
anyway thanks everyone !

Trying to create login with cookies

I'm try to get cookies on to a browser. It's giving me parameter 1 error and parameter 3. This code works elsewhere on my site but not here. Can someone help me?
if ((!isset($_POST["uname"])) || (!isset($_POST["password"])))
{
header ("Location: wddnt/clients/'. $tattoo_extern_acct . '/index.html");
exit;
}
$userpass = md5($_POST['password']);
#$db = mysqli_connect("$dbc_ser", "$dbc_usr", "$dbc_pwd", "$dbc_db");
$sql = "SELECT id, name, company, job_title, cell_num, office_num, office_email,
login_right, first_run, attempts, locked_out FROM login
WHERE email = '".$_POST["email"]."'
AND password = PASSWORD('$userpass')";
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$result = mysqli_query($db, $sql);
while ($info = mysqli_fetch_array($result))
{
$id = stripslashes($info['id_files']);
$u_acct = stripslashes($info['uname']);
$name = stripslashes($info['name']);
$job_title = stripslashes($info['job_title']);
$location = stripslashes($info['company']);
$cell_num = stripslashes($info['cell_num']);
$office_num = stripslashes($info['office_num']);
$office_email = stripslashes($info['office_email']);
$login_right = stripslashes($info['login_right']);
$first_run = stripslashes($info['first_run']);
$attempts = stripslashes($info['attempts']);
$locked_out = stripslashes($info['locked_out']);
$land_page = stripslashes($info['land_page']);
}
}
Try debugging some of the individual variables. What is in $sql, for example? Is it correct?
Is the "Cannot connect" clause executed, or does it get to the query and fail there? (I am not sure what "parameter 1 error and parameter 3" means).
Don't forget to escape the 'email' value by the way - this code has an SQL injection hole.
header ("Location: wddnt/clients/'. $tattoo_extern_acct . '/index.html");
This is not going to work the way you expect.
$sql = "SELECT id, name, company, job_title, cell_num, office_num, office_email,
login_right, first_run, attempts, locked_out FROM login
WHERE email = '".$_POST["email"]."'
You need to read up on SQL injection.
while ($info = mysqli_fetch_array($result))
You allow multiple accounts with the same email address / password?????
It's giving me parameter 1 error and parameter 3
Couldn't you post the actual error message you get?
$id = stripslashes($info['id_files']);
WTF? Smartquotes?
I'm not sure i understand your question but the last time i checked anyone who wants to use cookies uses the $_COOKIE global variable, either for setting them or accessing them. $_POST is made to get stuffs from forms, not cookies.
Please check the manual for more details about $_COOKIE
Regards

user registration php

<?php
include"include/connection.php";
$checkusername=mysql_query("SELECT * FROM employer WHERE eusername='$username'");
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = "insert into employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry) values ('".$_POST['first_name']."','".$_POST['last_name']."','".$_POST['gender']."','".$_POST['email']."','".$_POST['username']."','".$_POST['password']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['city']."','".$_POST['country']."')";
$result = mysql_query($query) or die (mysql_error());
echo " Thanks for registration";
}
?>
This is my code for inserting registration form data into a database. This code adds the data but also gives a parse error, but does not give the error if the username already exists.
Notice: Undefined variable: username in C:\Program Files\EasyPHP5.3.0\www\register_hirer2.php on line 6
Thanks for registration
line 6 is:
$checkusername=mysql_query("SELECT * FROM employer WHERE eusername='$username'");
Well, your $username is undefined indeed.
Most probably you want to use $_POST['username'].
And of course this obligatory XKCD comic:
If the "data source" is an html form (supposedly using method="post") you have to use $_POST['username'] when register_globals is set to off (which is the default since ...ages). see http://docs.php.net/security.globals
Also have a read of http://php.net/manual/en/security.database.sql-injection.php
<?php
include"include/connection.php";
$query = "SELECT
*
FROM
employer
WHERE
eusername='". mysql_real_escape_string($username). "'
";
$checkusername=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = "INSERT INTO employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry) values (". same mysql_real_escape_string() thing here for each parameter .")";
$result = mysql_query($query) or die (mysql_error());
echo " Thanks for registration";
}
?>
You can also use prepared statements. This way you don't need/can't forget using an escaping function.
edit and btw: you don't need the SELECT before the INSERT in order to make the username unique. Actually it will make things even harder since now you have to deal with race conditions. You'd have to lock the table between those two queries.
If you add an unique index for the username in your table MySQL will not allow the insertion of a doublet but instead return a specific error code which your script can fetch and handle without the need of dealing with race conditions.
define('ER_DUP_ENTRY', 1062);
$mysql = mysql_connect('..', '..', '..');
mysql_select_db('..', $mysql) or die(mysql_error($mysql));
$fields = array(
'efname'=>'first_name',
'elname'=>'last_name',
'egender'=>'gender',
'eemail'=>'email',
'eusername'=>'username',
'epwd'=>'password',
'eadd'=>'address',
'ephone'=>'phone',
'ecity'=>'city',
'ecountry'=>'country'
);
$sqlparams = array();
foreach($fields as $sql=>$form) {
if ( !isset($_POST[$form]) ) {
die('missing post parameter '. $form);
}
$sqlparams[$sql] = "'".mysql_real_escape_string($_POST[$form], $mysql)."'";
}
$query = '
INSERT INTO
employer
'. join(', ', array_keys($sqlparams)) .'
VALUES
('.join(',', $sqlparams).')
';
// table:employer has been defined with "unique key idxName (eusername)"
$result = mysql_query($query, $mysql);
if ( false!==$result ) {
echo " Thanks for registration";
}
else if ( ER_DUP_ENTRY===mysql_errno($mysql) ) {
echo 'username already exists';
}
else {
echo 'an error occurred';
}
That is because you do not define $username anywhere. It looks as though you want to use $_POST['username']
mysql_query("SELECT * FROM employer WHERE eusername='{$_POST['username']}'");
Also, your code is vulnerable to a SQL Injection
You never define $usernameanywhere, so it gives that error because you are trying to use a variable that it doesn't have a value for.
This is most likely because you've not defined the '$username' variable. I presume that you're relying on this being populated from the incoming GET/POST data (most likely via the depreciated register_globals) which is bad practice.
As such, you'll need to either populate $username via $_POST or $_GET.
More importantly, you should update the insert query to escape the incoming 'untrusted' data using mysql_real_escape_string (e.g.: mysql_real_escape_string($_POST['username']), etc.)
As #Yacoby said your code is vulnerable to an SQL Injection to prevent it you can use mysqli or PDO , if you would like to use mysqli use the following code:
<?php
include"include/connection.php";
$query = "SELECT
*
FROM
employer
WHERE
eusername='". mysql_real_escape_string($username). "'
";
$checkusername=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($checkusername)==1)
{
echo "username already exist";
}
else
{
$query = $conn->prepare("INSERT INTO employer(efname,elname,egender,eemail,eusername,epwd,eadd,ephone,ecity,ecountry)) values ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)"; // preparing the insert
$query->bind_param("ssssssssss" , $variable1 , $variable2 , $variable3 , $variable4 , $variable5 , $variable6 , $variable7 , $variable8 , $variable9 , $variable10); // binding parameters
$query->execute(); // sending the parameter values
$query->close(); // closing the query
$conn->close(); // closing the connection
if ($query) { // checking if the query has been executed with no errors
echo " Thanks for registration";
}
}
?>
BE SURE TO CHANGE THE $conn AND variables to whatever you want!

Categories