MySQL Update doesn't work, but delete works perfect - php

<?php
$connect = mysqli_connect('localhost', 'root', 'samagulf', 'wordpress');
$input = filter_input_array(INPUT_POST);
$country = mysqli_real_escape_string($connect, $input["country"]);
$city = mysqli_real_escape_string($connect, $input["city"]);
$for = mysqli_real_escape_string($connect, $input["for"]);
$title = mysqli_real_escape_string($connect, $input["title"]);
$details = mysqli_real_escape_string($connect, $input["details"]);
$price = mysqli_real_escape_string($connect, $input["price"]);
$email = mysqli_real_escape_string($connect, $input["email"]);
$phone = mysqli_real_escape_string($connect, $input["phone"]);
$photo = mysqli_real_escape_string($connect, $input["photo"]);
if($input["action"] === 'edit') {
$query = "UPDATE wp_wpdatatable_1
SET country=' " . $country . " ',city=' " . $city . " ',for=' " . $for . " ',title='
" . $title . " ',details=' " . $details . " ',price=' " . $price . " ',email='
" . $email . "
',phone=' " . $phone . " ',photo=' " . $photo . " '
where wdt_ID=' " . $input["wdt_ID"] . " ' ";
mysqli_query($connect, $query);
}
if($input["action"] === 'delete') {
$query = "DELETE FROM wp_wpdatatable_1
where wdt_ID=' " . $input["wdt_ID"] . " ' ";
mysqli_query($connect, $query);
}
echo json_encode($input);
?>

Here, use prepared statements. This will solve the issues you have such as quoting. Also, it prevents SQL injection. N.B You do not need to escape anymore.It's not necessary when using prepared statements
$stmt = $connect->prepare("UPDATE wp_wpdatatable_1 SET country=?, city=?, for=?, title=?, details=?, price=?, email=? phone=? photo=? WHERE wdt_ID=?");
$stmt->bind_param('sssssssss', $country, $city, $for, $title, $details, $price, $email, $phone, $photo, $input['wdt_ID']); //bind placeholders to values
if($stmt->execute() == true){//check for success/failure(returns true/false)
echo 'Updated';//it worked
} else {
echo 'Failed to update: '.$connect->error; //Oops error.
}

Related

For User before Update

I have made an API to insert data of 7 fields (fullname, city, bloodgroup, password, mobileno, lastdonated, created_date) in a mysql database using INSERT, please help me to add some code to search if the user is already added using the mobileno field and only then add the record else show the message "User already exists".
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
if(count($_REQUEST) > 0)
{
$conn = mysqli_connect("localhost", "creative_bloodapp", "PasSwORd", 'creative_bldapp');
$fullname =$_POST['fullname'];
$city =$_POST['city'];
$bloodgroup =$_POST['bloodgroup'];
$password =$_POST['password'];
$mobileno =$_POST['mobileno'];
$lastdonated =$_POST['lastdonated'];
$created_date = date('Y-m-d H:i:s');
$sql = "INSERT INTO register (fullname, city, bloodgroup, password, mobileno, lastdonated, created_date) VALUES ('" . $fullname . "','" . $city . "','" . $bloodgroup . "','" . $password . "','" . $mobileno . "','" . $lastdonated . "','". $created_date . "');";
$qur = $conn->query($sql);
if($qur){
$query="SELECT * FROM register ORDER BY mobileno DESC LIMIT 1;";
$data=array();
$result=mysqli_query($conn, $query);
$row=mysqli_fetch_assoc($result);
mysqli_close($conn);
response(1,"User has been registered!",$row);
}else{
mysqli_close($conn);
response(0,"Not Registered!",NULL);
}
}
else
{
response(0,"Not Registered!",NULL);
}
function response($status,$status_message,$data)
{
header("HTTP/1.1 ".$status);
$response['status']=$status;
$response['status_message']=$status_message;
$response['data']=$data;
$json_response = json_encode($response);
echo $json_response;
}
?>
Looking for something like this; I changed some queries and re-wrote a part for you. Also added mysqli_real_escape_string.
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
if(count($_REQUEST) > 0)
{
$conn = mysqli_connect("localhost", "creative_bloodapp", "PasSwORd", 'creative_bldapp');
$fullname = mysqli_real_escape_string($conn, $_POST['fullname']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$bloodgroup = mysqli_real_escape_string($conn, $_POST['bloodgroup']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$mobileno = mysqli_real_escape_string($conn, $_POST['mobileno']);
$lastdonated = mysqli_real_escape_string($conn, $_POST['lastdonated']);
$created_date = date('Y-m-d H:i:s');
$query="SELECT * FROM register WHERE mobileno = '".$mobileno."'";
$qur=mysqli_query($conn, $query);
if(count(mysqli_num_rows($qur) !== 0)){
$data=array();
$result=mysqli_query($conn, $query);
$row=mysqli_fetch_assoc($result);
mysqli_close($conn);
response(1,"User has been registered!",$row);
}else{
$sql = "INSERT INTO register (fullname, city, bloodgroup, password, mobileno, lastdonated, created_date) VALUES ('" . $fullname . "','" . $city . "','" . $bloodgroup . "','" . $password . "','" . $mobileno . "','" . $lastdonated . "','". $created_date . "');";
$qur=mysqli_query($conn, $query);
mysqli_close($conn);
response(0,"Not Registered!",NULL);
}
}
else
{
response(0,"Not Registered!",NULL);
}
function response($status,$status_message,$data)
{
header("HTTP/1.1 ".$status);
$response['status']=$status;
$response['status_message']=$status_message;
$response['data']=$data;
$json_response = json_encode($response);
echo $json_response;
}
Yes, Make it mobileno unique key so
if($qur)
{
// new mobileno
//add it will take
}
else
{
// repeated i will not accept, you put mobileno exist.
}
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
if(count($_REQUEST) > 0)
{
$conn = mysqli_connect("localhost", "creative_bloodapp", "PasSwORd", 'creative_bldapp');
$fullname = mysqli_real_escape_string($conn, $_POST['fullname']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$bloodgroup = mysqli_real_escape_string($conn, $_POST['bloodgroup']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$mobileno = mysqli_real_escape_string($conn, $_POST['mobileno']);
$lastdonated = mysqli_real_escape_string($conn, $_POST['lastdonated']);
$created_date = date('Y-m-d H:i:s');
$verifysql = "select id from register where mobileno='".$mobileno."'";
$qur = $conn->query($verifysql);
if($qur->num_rows == 0){
$sql = "INSERT INTO register (fullname, city, bloodgroup, password, mobileno, lastdonated, created_date) VALUES ('" . $fullname . "','" . $city . "','" . $bloodgroup . "','" . $password . "','" . $mobileno . "','" . $lastdonated . "','". $created_date . "');";
$result = $conn->query($sql);
if($result){
mysqli_close($conn);
response(200,"User has been registered!",$row);
}else{
mysqli_close($conn);
response(500,"Registeration Failed",NULL);
}
}
else{
mysqli_close($conn);
response(409,"User Already Exists!",NULL);
}
}
else
{
response(400,"Not Registered!",NULL);
}

I am unable to increament id

I searched many stackoverflow questions it didn't help
I want to increment id by fetching last id from MySQL table.
I don't want to do auto increment in MySQL table because already one column is auto incremented.
<?php
include 'db.php';
$created = date('Y-m-d H:i:s');
//$json_data = array();
$message = array();
$error = array();
if ($_GET['vendor_id'] == "") {
$message[] = array("message" => "Values Empty");
} else {
$result = mysqli_query("SELECT loo_id FROM loo_list ORDER BY loo_id DESC LIMIT 1");
if ($result) {
$order_array = mysqli_fetch_assoc($result) or die(mysqli_error());
//echo $order_array['loo_id'];
}
$loo_id = $order_array['loo_id'] + 1;
$sql = "insert into loo_list(loo_id,name,address,geolocation,price,facility_category,facilities,count,accessbility,image,type,category,created_vendor,days,timings,terms_conditions,vendor_approval,created,warning,url,user_ids,overall,admin_approval,updated)values('" . $loo_id . "','" . $_GET['loo_name'] . "','" . $_GET['address'] . "','" . $_GET['loo_location'] . "','" . $_GET['price'] . "','" . $_GET['facility_category'] . "','" . $_GET['facilities'] . "','" . $_GET['count'] . "','" . $_GET['accessbility'] . "','" . $_GET['image'] . "','Offerers','" . $_GET['category'] . "','" . $_GET['vendor_id'] . "','" . $_GET['days'] . "','" . $_GET['timings'] . "','" . $_GET['terms_conditions'] . "','1','" . $created . "','0','','" . $_GET['user_ids'] . "','" . $_GET['overall'] . "','1','" . $created . "')";
$res1 = mysqli_query($db, $sql) or die(mysqli_error());
$message[] = array("message" => "success");
}
$json_data = array("result" => $message);
echo json_encode($json_data);
?>
Try this code.
if(trim($order_array['loo_id']) === ''){
$loo_id = 1;
}else{
$loo_id = intval($order_array['loo_id']) + 1;
}

Update column from another table mysql

I have 2 tables(violator and officer) and both of them have column name reference, now what I want to do is whenever I add a new value to the violator table, the value of its reference should be equal to the value of reference on officer table. I am new to programming but how can I achieve that? I couldn't quite understand the notes I can find on the internet. This is how I add values to the violator table:
php
<?php
$user_name = "Demo";
$password = "Demopass";
$server = "localhost";
$db_name = "TMTRO";
$con = mysqli_connect($server, $user_name, $password, $db_name);
if ($con) {
$Name = $_POST['name'];
$LName = $_POST['lname'];
$LNumber = $_POST['lnumber'];
$Violation = $_POST['violation'];
$Aplace = $_POST['aplace'];
$Address = $_POST['address'];
$PNumber = $_POST['pnumber'];
$OName = $_POST['oname'];
$RNumber = $_POST['rnumber'];
$DTime = $_POST['dtime'];
$query = "insert into violators (name,lname,lnumber,violation,aplace,address,pnumber,oname,reference,datetime) values ('" . $Name . "','" . $LName . "','" . $LNumber . "','" . $Violation . "','" . $Aplace . "','" . $Address . "','" . $PNumber . "','" . $OName . "','" . $RNumber . "','" . $DTime . "');";
$result = mysqli_query($con, $query);
if ($result) {
$status = 'OK';
} else {
$status = 'FAILED';
}
} else {
$status = 'FAILED';
}
echo json_encode(array("response" => $status));
mysqli_close($con);
?>

Can not check the duplicate data in database using PHP,Mysql and Angular.js

i am finding little bit difficult to check duplicate data from database using MYsql,PHP and angular.js.I am explaining my code below.
addUser.php:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user_name=$request->user_name;
$user_email=$request->user_email;
$mob_no=$request->mob_no;
$login_name=$request->login_name;
$password=$request->password;
$user_status=$request->user_status;
$con = mysql_connect('localhost', 'root', 'Oditek123#');
mysql_select_db('go_fasto', $con);
$selquery = "SELECT * FROM db_user WHERE login_name='".$login_name."' and mob_no='".$mob_no."' and email='" . $user_email . "'";
$selres = mysql_query($selquery);
if(mysql_num_rows($selres ) > 0)
{
$erresult=mysql_fetch_array($selres);
header("HTTP/1.0 401 Unauthorized");
$erresult['msg'] = 'This user login name or mobile no or email is already exist.';
}else{
$qry ='INSERT INTO db_user (user_name,email,mob_no,login_name,password,user_status) values ("' . $user_name . '","' . $user_email . '","' . $mob_no . '","' .$login_name . '","' . $password . '","' . $user_status . '")';
$qry_res = mysql_query($qry);
$user_type = 5;
$display_name = $user_name."_admin";
$qry ='INSERT INTO db_Admin_Master (user_type,user_name,display_name,password) values ("' . $user_type . '","' . $login_name . '","' . $display_name . '","' .$password . '")';
$qry_res = mysql_query($qry);
$query='SELECT * from db_user order by user_id desc';
$res=mysql_query($query);
$result=mysql_fetch_array($res);
if ($result) {
$result['msg'] = "New User has added successfully";
} else {
header("HTTP/1.0 401 Unauthorized");
$result['msg'] = "Sorry, User could not added ";
}
echo json_encode($result);
}
?>
If you will check my code i am checking three column such as login_name,email and mob_no from database and checking it inside if statement.Here even if i am inserting the same data again it is not checking and else part is executing.Please help me to resolve this issue.
$selquery = "SELECT *
FROM db_user
WHERE login_name='".$login_name."'
OR mob_no='".$mob_no."'
OR email='" . $user_email . "'";
use OR instead of AND try

Filtering MYSQL results by date

We have a script that generate invoice once a month (cron). But we would like to add feature, that we would be able to select date range "from - to" and then generate invoice only for the date selected.
I guess making input fields with calendar pop-up isn't hard, but filtering with PHP is a bit bigger challenge, so if anyone want to take a look at my code and give me some tips, I would be grateful.
function genInvoice($clientID, $orderID=0, $paid=false)
{
if($orderID == 0)
$sql = "select tblorders.* from tblorders,tblusers where invoiceid=0 and tblorders.userid=tblusers.id " .
"and status='closed' and tblusers.clientid=" . $clientID;
else
$sql = "select tblorders.* from tblorders,tblusers where invoiceid=0 and tblorders.userid=tblusers.id " .
"and tblusers.clientid=" . $clientID . " and tblorders.id=" . $orderID;
$res = full_query($sql) or die(mysql_error());
// If no closed orders uninvoiced, just return
if(!mysql_num_rows($res))
return 0;
$amount = 0;
$orders = array();
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
// print_r($row);
// print "<br><hr>";
$amount += $row['amount'];
$orders[] = $row['id'];
}
$date = date("Y-m-d");
$status = $paid ?'Paid' : 'Unpaid';
$sql = "insert into tblinvoices (clientid, date, duedate, subtotal, total, status) values (" . $clientID . ",'" . $date .
"','" . $date . "'," . $amount . "," . $amount . ",'" . $status . "')";
$res = full_query($sql) or die(mysql_error());
$invoiceid = mysql_insert_id();
$sql = "update tblorders set invoiceid=" . $invoiceid . " where id in (" . implode(",", $orders) . ")";
$res = full_query($sql) or die(mysql_error());
$sql = "select tblorders.id as ReportID, FirstName, LastName, SearchName, CountyID, StateID, bl_orderitems.userid, bl_orderitems.amount, " .
"bl_orderitems.notes from tblorders, bl_orderitems left join bl_search on bl_search.id=packageid where tblorders.id in (" .
implode(",", $orders) . ") and bl_orderitems.orderid=tblorders.id order by tblorders.id,bl_orderitems.id";
$res = full_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
if($row['CountyID'] != 0)
$locale = getCounty($row['CountyID']);
else if($row['StateID'] != 0)
$locale = getState($row['StateID']);
if($row['SearchName'] != "")
$description = mysql_real_escape_string($row['FirstName'] . " " . $row['LastName'] . " " .
$row['SearchName'] . " " . $locale . " (Order #" . $row['ReportID'] . ")");
else
$description = "Search Package: " . mysql_real_escape_string($row['notes'] . " (Order #" . $row['ReportID'] . ")");
$sql = "insert into tblinvoiceitems (invoiceid, userid, type, description, amount, duedate) values " .
"(" . $invoiceid . "," . $row['userid'] . ",'search','" . $description . "','" .
$row['amount'] . "','" . $date . "')";
// print $sql . "<br>";
full_query($sql) or die(mysql_error());
}
sendmessage ('Invoice Created', $invoiceid);
return $invoiceid;
}
not going to look through all that code, but filtering results by a date range is easy.
SELECT id FROM some_table WHERE some_date_field BETWEEN $first_date AND $second_date

Categories