Updating MySQL table with a PHP script - php

I am developing an android application, where I want to insert the address of the user to the database calling a PHP script on a website.
In the first try, it has to insert the address into the database and after that, it has update the same tuple.
This is the PHP script I have, but it gives an error in line number 36 (Call to a member function bind_param()).
Nevertheless, insertion is working perfectly fine.
class DbOperations1{
private $con;
function __construct(){
require_once dirname(__FILE__).'/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
public function createUser ($name, $email, $password) {
if($this->isUserExist($name, $email))
{
return 0;
}else{
$password = md5($password);
$stmt = $this->con->prepare("INSERT INTO `test` (`id`,`name`, `email`, `password`) VALUES (NULL, ? , ? , ? );");
$stmt->bind_param ("sss", $name, $email, $password);
if ($stmt->execute()){
return 1;
} else {
return 2;
}
}
}
public function Address($id_user, $address, $road, $city, $country) {
if($this->isAddressExist($id_user, $address))
{
$stmt = $this->con->prepare("UPDATE address a, users u SET `address`=$address,`road`=$road,`city`=$city,`country`=$country WHERE a.id_user=u.id");
$stmt->bind_param("ssss", $address, $road, $city, $country);
if ($stmt->execute()){
return 2;
} else {
return 3;
}
}else{
$stmt = $this->con->prepare("INSERT INTO `address` (`id_address`, `id_user`,`address`, `road`, `city`, `country`) VALUES (NULL, ?, ? , ? ,? ,? );");
$stmt->bind_param ("sssss", $id_user, $address, $road, $city, $country);
if ($stmt->execute()){
return 0;
} else {
return 1;
}
}
}
public function userLogin($email, $password){
$password = md5($password);
$stmt = $this->con->prepare("SELECT id FROM users WHERE email = ? AND password = ?");
$stmt->bind_param("ss",$email,$password);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
public function getUserByemail($email){
$stmt = $this->con->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s",$email);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();
}
private function isUserExist($name, $email){
$stmt = $this->con->prepare("SELECT id FROM test WHERE name = ? OR email = ?");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
private function isAddressExist($id_user){
$stmt = $this->con->prepare("SELECT id_address FROM address WHERE id_user = ?");
$stmt->bind_param("s", $id_user);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
}

According to your comments, the error is because of call to prepare failing.
Following code will allow to get more info:
if($this->isAddressExist($id_user, $address))
{
$stmt = $this->con->prepare("UPDATE address a, users u SET `address`=$address,`road`=$road,`city`=$city,`country`=$country WHERE a.id_user=u.id");
if($stmt != False) {
$stmt->bind_param("ssss", $address, $road, $city, $country);
if ($stmt->execute()){
return 2;
} else {
return 3;
}
} else {
// this line will give an insight into an error message
echo $this->con->error;
}
}
After getting the error message from MySQL:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'road=Sarak,city=Khost,country=Afghanistan WHERE a.id_user= 10' at line 1
we locate exact error location and there is $address variable used, while it shall be ?! Such statement can't be prepared.
Using following update statement should fix it:
$stmt = $this->con->prepare("UPDATE address a, users u SET `address`=?,`road`=?,`city`=?,`country`=? WHERE a.id_user=u.id");

public function Address($id_user, $address, $road, $city, $country) {
if($this->isAddressExist($id_user))
{
$stmt = $this->con->prepare("UPDATE address SET `address`=?,`road`=?,`city`=?,`country`=? WHERE id_user= ?");
if($stmt != False) {
$stmt->bind_param("ssss", $address, $road, $city, $country,$id_user);
if ($stmt->execute()){
return 2;
} else {
return 3;
}
} else {
// hopefully this line will give an insight into an error message
echo $this->con->error;
}
} else{
$stmt = $this->con->prepare("INSERT INTO `address` (`id_address`, `id_user`,`address`, `road`, `city`, `country`) VALUES (NULL, ?, ? , ? ,? ,? );");
$stmt->bind_param ("sssss", $id_user, $address, $road, $city, $country);
if ($stmt->execute()){
return 0;
} else {
return 1;
}
}
}
This should work. When it comes to parameter binding you have to use ? (question mark ) instead of the parameter name and bind the parameters by name in the correct order in bind_param function.

$stmt = $this->con->prepare("UPDATE address SET `address`=$address,`road`=$road,`city`=$city,`country`=$country WHERE a.id_user=u.id");
try to update one table

Related

unique id registration check script not working [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
i am getting an error when running this file using Postman error is "Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in C:\wamp64\www\Android\include\DbOperations.php on line 20"
For more details check this link:
https://www.dropbox.com/s/jecshgs34ra50qi/Untitled.jpg?dl=0
File DbOperations.php
<?php
class DbOperations{
private $con;
function __construct(){
require_once dirname(__FILE__).'/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
/*CRUD -> c -> CREATE */
public function createUser($name, $surname, $username, $user_pass, $address, $pin, $mail, $phone){
if(this->isUserExist($username,$mail,$phone)){
return 0;
}else{
$password = md5($user_pass);
$stmt = $this->con->prepare("INSERT INTO `user_data` (`name`, `surname`, `username`, `password`, `address`, `pin`, `mail`, `phone`) VALUES (?, ?, ?, ?, ?, ?, ?, ?);");
$stmt->bind_Param("ssssssss",$name,$surname,$username,$password,$address,$pin,$mail,$phone);
if($stmt->execute()){
return 1;
}else{
return 2;
}
}
}
private function isUserExist($username, $mail, $phone){
$stmt = $this->con->prepare("SELECT id FROM user_data WHERE username = ? or mail = ? or phone = ?");
$stmt->bind_param("sss", $username, $mail, $phone);
$stmt->execute();
execute->store_result();
return $stmt->num_row > 0;
}
}
?>
File registerUser.php
<?php
require_once '../include/DbOperations.php';
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(
isset($_POST['reg_name']) and isset($_POST['reg_surname']) and isset($_POST['reg_username']) and isset($_POST['reg_password']) and isset($_POST['reg_address']) and isset($_POST['reg_pin']) and isset($_POST['reg_mail']) and isset($_POST['reg_phone'])
){
//operate the data further
$db = new DbOperations();
$result = $db->createUser( $_POST['reg_name'],
$_POST['reg_surname'],
$_POST['reg_username'],
$_POST['reg_password'],
$_POST['reg_address'],
$_POST['reg_pin'],
$_POST['reg_mail'],
$_POST['reg_phone']
);
if($result == 1){
$response['error'] = false;
$response['message'] = "User register successfully";
}elseif($result == 2){
$response['error'] = true;
$response['message'] = "Something wrong, try again";
}elseif ($result == 0) {
$response['error'] = true;
$response['message'] = "User already register";
}
}else{
$response['error'] = true;
$response['message'] = "Required fields are missing";
}
}else{
$response['error'] = true;
$response['message'] = "Invalid Request";
}
echo json_encode($response);
?>
You forgot to add $ sign
DbOperations.php
<?php
class DbOperations{
private $con;
function __construct(){
require_once dirname(__FILE__).'/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
/*CRUD -> c -> CREATE */
public function createUser($name, $surname, $username, $user_pass, $address, $pin, $mail, $phone){
if($this->isUserExist($username,$mail,$phone)){ //<--------change this
return 0;
}else{
$password = md5($user_pass);
$stmt = $this->con->prepare("INSERT INTO `user_data` (`name`, `surname`, `username`, `password`, `address`, `pin`, `mail`, `phone`) VALUES (?, ?, ?, ?, ?, ?, ?, ?);");
$stmt->bind_Param("ssssssss",$name,$surname,$username,$password,$address,$pin,$mail,$phone);
if($stmt->execute()){
return 1;
}else{
return 2;
}
}
}
private function isUserExist($username, $mail, $phone){
$stmt = $this->con->prepare("SELECT id FROM user_data WHERE username = ? or mail = ? or phone = ?");
$stmt->bind_param("sss", $username, $mail, $phone);
$stmt->execute();
$stmt->->store_result();
return $stmt->num_rows > 0;
}
}
?>

Object Variable Remains Undefined after being Set in Constructor

This is the code of my class, only relevant parts of course:
class User {
public $id;
public function __construct($email, $password, $firstName, $lastName) {
$db = Connection::getInstance();
// check if user exists
$id = User::findUserByEmail($email);
if($id > 0){
// echo "User already exists!";
return -1;
}
// Create new row in users table
$stmt = $db->prepare("INSERT INTO `mapdb`.`user` (`email`, `password`, `firstName`, `lastName`)
VALUES (:email, :password, :firstName, :lastName);");
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':firstName', $firstName, PDO::PARAM_STR);
$stmt->bindParam(':lastName', $firstName, PDO::PARAM_STR);
$stmt->execute();
// check f user added successfully
$newID = User::findUserByEmail($email);
if($newID > 0){
echo "success, ID = ".$newID;
$this->$id = $newID;
// $this->$email = $email;
// $this->$firstName = $firstName;
// $this->$firstName = $firstName;
} else {
echo "failure";
return -1;
}
}
}
And where I actually call the constructor:
$user = new User($email, $password, $firstName, $lastName);
echo "<br>userid: ".$user->id; // (<-- this doesn't echo correctly)
I cannot get the value from the User object whatever I try.
At the moment I get the following error:
Notice: Undefined variable: id
What could possibly deny me access from the variable?
Problem solved, instead of
$this->$id = $newID;
I should have
$this->id = $newID;
Thank goodness for stackoverflow :D

PDO: How to make checks

I create this class but i'm newbie in PHP OOP & PDO and i don't know how and where i must to make check to username is valid , email is valid and e.t.c..
This is my code
Class Users {
private $db;
public function __construct(Database $datebase) {
if (!$database instanceOf Database) {
throw new Exeption();
}
$this->db = $datebase;
}
public function userRegistration($username, $password, $email) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$regdate = date('d.m.Y');
$query = $this->db->prepare("INSERT INTO `users` (`username`, `password`, `email`, `regdate`) VALUES (?, ?, ?, ?) ");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->bindValue(3, $email);
$query->bindValue(4, $regdate);
return ($query->execute()) ? true : false ;
}
}
If you want to check something, use Respect/Validation. For example:
$usernameValidator = v::alnum()->noWhitespace()->length(1,15);
$usernameValidator->validate($_POST['username']); //true or false
$passwordValidator = v::alnum()->length(10, null);
$passwordValidator->validate($_POST['password']); //true or false
v::email()->validate($_POST['email']); //true or false
To check if the username or email exist in your database you can use SQL to search the email or username.
$query = $this->db->prepare("SELECT * FROM users WHERE email = ? ");
$query->bindValue(1, $email);
If the query returns a value than the email or username already exist in your database. From there you can show your own validation.
To check check if user or email exist you don't need another class, just add another method called userExist or emailExist and run a query and then check if you get a result.
public function emailExist($email){
$query = $this->db->prepare("SELECT * FROM users WHERE email = ? ");
$query->bindValue(1, $email);
try{
$query->execute();
//use the if statement and $query->rowCount() to check if there is a result
$rows = $query->rowCount();
if($rows === 1){
return true;
} else {
return false;
}
}catch (PDOException $e) {
die($e->getMessage());
}
}

PHP insert into mysql database with dates

I would like to be able to add children into a database, which are connected to their parents (who has a member id MID). I believe that the error lies within the date format (atleast that's what I believe), I have also tried to use strtotime($dob), however this didn't change anything.
$name = htmlspecialchars($_GET['Name']);
$dob = $_GET['DOB'];
$newDOB = date("Y-m-d", $dob);
$mid = $_GET['mid'];
if(isset($_GET['Name'], $_GET['DOB'], $_GET['mid']))
$alert = true;
if(!empty($name) && !empty($newDOB) && !empty($mid))
add_family_member($mid, $newDOB, $name);
The function that adds the member:
function add_family_member($mid, $dob, $name)
{
global $con;
$sql = "INSERT INTO Children(MID, DOB, Name) VALUES(?, ?, ?)";
$stmt = $con->prepare($sql);
if($stmt)
{
$b = $stmt->bind_param("iss", $mid, $dob, $name);
if($b)
{
$e = $stmt->execute();
if($e)
return true;
}
}
return false;
}
function add_family_member($mid, $dob, $name)
{
global $con;
$sql = "INSERT INTO Children(MID, DOB, Name) VALUES(:mid, :dob, :name)";
$stmt = $con->prepare($sql);
if($stmt)
{
return $stmt->execute(array(
'mid' => $mid,
'dob' => $dob,
'name' => $name
));
}
return false;
}
see http://www.php.net/manual/en/pdostatement.execute.php for more examples
Try...
function add_family_member($mid, $dob, $name)
{
global $con;
$sql = "INSERT INTO Children(MID, DOB, Name) VALUES(:mid, :dob, :name)";
$stmt = $con->prepare($sql);
$stmt->bindParam(':mid', $mid);
$stmt->bindParam(':dob', $dob);
$stmt->bindParam(':name', $name);
if ($stmt->execute()) {
return true;
}
return false;
}

error when try to send second query to mysql in my class

I have this code, but when i try to make second query to db it crashes, why? Here is part of the code, where it crashes
if ($this->doRegister === true) {
$db = DB::connect();
$stmt = $db->prepare('SELECT `user_id` FROM `users` WHERE `user_name` = ? OR `user_email` = ? LIMIT 1');
$stmt->bind_param('ss', $this->store['userData']['name'], $this->store['userData']['email']);
$stmt->execute();
$stmt->bind_result($userId);
$stmt->fetch();
if (is_numeric($userId)) {
$stmt = $db->prepare('INSERT INTO `users`(`user_name`, `user_password`, `user_email`, `user_ip`, `user_dateRegistered`, `user_type`) VALUES (?, ?, ?, ?, ?, ?)');
$hashedPassword = $this->encrytion('md5', md5($this->store['userData']['name']) . md5($this->store['userData']['password']));
$dateRegistered = time();
$type = 1;
$stmt->bind_param('ssssii', $this->store['userData']['name'], $hashedPassword, $this->store['userData']['email'], $_SERVER['REMOTE_ADDR'], $dateRegistered, $type);
$stmt->execute();
$this->registerUser();
} else {
return array('register' => 'User name or email already exists');
}
} else {
return $this->store['userDataState'];
}
Before executing/preparing the new query, you need to close it.
$stmt->close();

Categories