For User before Update - php

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);
}

Related

PHP script inserting data into db return success on execution but record is not inserted in db?

strong textBelow is the code used for inserting a record into the database. Script is getting executed where as the record is not getting inserted into database but the php script is getting executed with out any fail. Please help me with this.
<?php
$servername = "xxx.xx.x.xxx";
$username = "usr";
$password = "pwd";
$dbname = "Dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$postdata = json_decode(file_get_contents('php://input'), true);
$tablename = "tablename";
function guidv4($data)
{
assert(strlen($data) == 16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
if(is_array($postdata)){
$sql = "INSERT INTO ".$tablename." (id, ssid, address, lat, lng, state, country, city, cat, subcat, sname, createdAt,pincode) VALUES ";
$valuesArr = array();
foreach($postdata as $row){
//$loc = explode(", ", $row['loc']);
//$lat = mysqli_real_escape_string($conn, $loc[0]);
//$lng = mysqli_real_escape_string($conn, $loc[1]);
$id = guidv4(random_bytes(16));
//$id = mysqli_real_escape_string($conn, $row['id']);
$ssid = mysqli_real_escape_string($conn, $row['sname']);
$address = mysqli_real_escape_string($conn, $row['address']);
$lat = mysqli_real_escape_string($conn, $row['lat']);
$lng = mysqli_real_escape_string($conn, $row['lng']);
$state = mysqli_real_escape_string($conn, $row['state']);
$country = mysqli_real_escape_string($conn, "India");
$city = mysqli_real_escape_string($conn, $row['city']);
$cat = mysqli_real_escape_string($conn, $row['cat']);
$subcat = mysqli_real_escape_string($conn, $row['subcat']);
$sname = mysqli_real_escape_string($conn, $row['sname']);
$createdAt = mysqli_real_escape_string($conn, $row['createdAt']);
$pincode = mysqli_real_escape_string($conn, $row['pincode']);
$valuesArr[] = "('$id', '$ssid', '$address', '$lat', '$lng', '$state', '$country', '$city', '$cat', '$subcat', '$sname', '$createdAt','pincode')";
}
$sql .= implode(',', $valuesArr);
$conn->query($sql) or exit(mysql_error());
}
$conn->close();
?>
It seems that the $valuesArr array elements are not being concatenated correctly
You should separate the PHP variables from the text, using the concatenation operator ".", like so:
$valuesArr[] = "('" . $id ."', '" .$ssid . "', '" . $address ."', '" . $lat ."', '" . $lng . "', '" $state . "', '" . $country . "', '" . $city . "', '" . $cat . "', '" . $subcat ."', '" . $sname . "', '" . $createdAt . "','pincode')";

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);
?>

MySQL Update doesn't work, but delete works perfect

<?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.
}

PHP X MYSQL | Error in Injecting data using $_POST [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I have been trying to input data from $_Post variables but I cannot spot where the error is? Hope you can help me.
Below is the code:
$conn = mysql_connect("localhost", "root");
if (isset($_POST['studLog'])) {
$uName = $_POST['uName'];
$pWord = $_POST['pWord'];
mysql_select_db("sis_main", $conn);
if (mysql_num_rows(mysql_query("SELECT * from student where stud_uname='$uName' and stud_pword='$pWord'"))) {
include("stud-view.html");
} else {
echo 'Account doesnt exist!';
echo "<br><br>";
echo "<a href='stud-start.html'>GO BACK!</a>";
}
} else if (isset($_POST['studReg'])) {
mysql_select_db("sis_main", $conn);
$stdID = $_POST['studID'];
$fname = $_POST['firstNme'];
$mname = $_POST['midNme'];
$lname = $_POST['lastNme'];
$stadd = $_POST['stAdd'];
$ctadd = $_POST['ctAdd'];
$bdate = $_POST['bDate'];
$gendr = $_POST['gender'];
$email = $_POST['email'];
$mobno = $_POST['mobNum'];
$uname = $_POST['newUName'];
$pword = $_POST['newPWord'];
$age = birthday($bdate);
if (mysql_query("INSERT INTO student values (`$stdID`,`$fname`,`$lname`, `$mname`,`$stadd`,`$ctadd`,`$age`,`$bdate`,`$gendr`, `$email`,`$mobno`,`$uname`,`$pword`);")) {
echo 'Account Successfully Regsitered!';
} else {
echo 'ERROR: '.mysql_error();
echo "<a href='stud-start.html'>GO BACK!</a>";
}
}
}
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '#gmail.com, 09981744039, kuyschan, kuyschan)' at line 1
This is suppposed to be a comment, but i have a low reputation here.
Before i answer your question, please do not use the mysql functions as its no longer supported . Consider a switch to either MYSQLI or PDO. Also, do not trust user input. Meaning do not directly post field values from your form to your database as an attcker can easily exploit it by adding funny javascripts or worse.
To your question,
In your insert statement, you did not specify the columns:
Try:
<?php
$sql = "INSERT INTO student (`studID`, `firstNme`, `lastNme`,`stAdd`,`ctAdd`,`bDate`,`gender`,`email`,`mobNum`,`newUName`,`newPWord`)VALUES
('" . mysqli_real_escape_string($con, $_POST['studID']) . "',
'" . mysqli_real_escape_string($con, $_POST['firstNme']) . "',
'" . mysqli_real_escape_string($con, $_POST['lastNme']) . "',
'" . mysqli_real_escape_string($con, $_POST['stAdd']) . "',
'" . mysqli_real_escape_string($con, $_POST['ctAdd']) . "',
'" . mysqli_real_escape_string($con, $_POST['bDate']) . "',
'" . mysqli_real_escape_string($con, $_POST['gender']) . "',
'" . mysqli_real_escape_string($con, $_POST['email']) . "',
'" . mysqli_real_escape_string($con, $_POST['mobNum']) . "',
'" . mysqli_real_escape_string($con, $_POST['newUName']) . "',
'" . mysqli_real_escape_string($con, $_POST['newPWord']) . "')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Where $con is your database connection.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}

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

Categories