PHP insert into mysql database with dates - php

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

Related

Updating MySQL table with a PHP script

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

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

mysqli_stmt_fetch() Not Working

I am trying to save a value from a mysqli_stmt_fetch() statement. When my application is run, it returns No Value for this variable. I am new to PHP and cannot fully debug this file. Where is the bug at?
My php file:
<?php
require("password.php");
$connect = mysqli_connect("website", "account", "my_pass", "db");
$name = $_POST["name"];
$theme = $_POST["theme"];
$username = $_POST["username"];
$email = $_POST["email"];
$defaultRadius = $_POST["radius"];
$password = $_POST["password"];
function registerUser() {
global $connect, $name, $username, $theme, $email, $defaultRadius, $password;
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$statement = mysqli_prepare($connect, "INSERT INTO user (name, username, theme, email, default_radius, password) VALUES (?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssssss", $name, $username, $theme, $email, $defaultRadius, $passwordHash);
mysqli_stmt_execute($statement);
mysqli_stmt_bind_result($statement, $colUserID, $colName, $colUsername, $colTheme, $colEmail, $colDefaultRadius, $colPassword);
while(mysqli_stmt_fetch($statement)){
$response["userId"] = $colUserID;
}
mysqli_stmt_close($statement);
}
function usernameAvailable() {
global $connect, $username;
$statement = mysqli_prepare($connect, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
$count = mysqli_stmt_num_rows($statement);
mysqli_stmt_close($statement);
if ($count < 1){
return true;
} else {
return false;
}
}
$response = array();
$response["success"] = false;
$response["reason"] = 0;
if (usernameAvailable()){
registerUser();
$response["success"] = true;
} else {
$response["reason"] = 1;
}
echo json_encode($response);
?>
The variable that I am trying to set is located inside the registerUser function. It states:
while(mysqli_stmt_fetch($statement)){
$response["userId"] = $colUserID;
}
Thanks for any help!
Edit:
My new/current code is as follows:
<?php
require("password.php");
$connect = mysqli_connect("xenicdev.x10host.com", "xenicdev_root", "shadow1", "xenicdev_data");
$name = $_POST["name"];
$theme = $_POST["theme"];
$username = $_POST["username"];
$email = $_POST["email"];
$defaultRadius = $_POST["radius"];
$password = $_POST["password"];
function registerUser() {
global $connect, $name, $username, $theme, $email, $defaultRadius, $password, $response;
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$statement = mysqli_prepare($connect, "INSERT INTO user (name, username, theme, email, default_radius, password) VALUES (?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssssss", $name, $username, $theme, $email, $defaultRadius, $passwordHash);
mysqli_stmt_execute($statement);
mysqli_stmt_bind_result($statement, $colUserID, $colName, $colUsername, $colTheme, $colEmail, $colDefaultRadius, $colPassword);
while(mysqli_stmt_fetch($statement)){
return $colUserID;
}
}
function usernameAvailable() {
global $connect, $username;
$statement = mysqli_prepare($connect, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
$count = mysqli_stmt_num_rows($statement);
mysqli_stmt_close($statement);
if ($count < 1){
return true;
} else {
return false;
}
}
$response = array();
$response["success"] = false;
$response["reason"] = 0;
if (usernameAvailable()){
$userId = registerUser();
$response["userId"] = $userId;
$response["success"] = true;
} else {
$response["reason"] = 1;
}
echo json_encode($response);
?>
It returns null as "userId" instead of the ID though... Please note the ID is not null in the SQL Database. In my testing case, the ID is 8.
StringRequest code used to call this PHP file from Android:
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://xenicdev.x10host.com/Register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, int themeId, String password, String email, int defaultRadius, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("username", username);
params.put("theme", themeId + "");
params.put("email", email);
params.put("radius", defaultRadius + "");
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Hi you can try this if you need last insert userID. Then this will help you i have changed some of your code
<?php
require("password.php");
$connect = mysqli_connect("xenicdev.x10host.com", "xenicdev_root", "shadow1", "xenicdev_data");
$name = $_POST["name"];
$theme = $_POST["theme"];
$username = $_POST["username"];
$email = $_POST["email"];
$defaultRadius = $_POST["radius"];
$password = $_POST["password"];
function registerUser() {
global $connect, $name, $username, $theme, $email, $defaultRadius, $password;
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $connect->prepare("INSERT INTO user (name, username, theme, email, default_radius, password) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $name, $username, $theme, $email, $defaultRadius, $passwordHash);
$stmt->execute();
return $userID = $stmt->insert_id;
}
function usernameAvailable() {
global $connect, $username;
$statement = mysqli_prepare($connect, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
$count = mysqli_stmt_num_rows($statement);
mysqli_stmt_close($statement);
if ($count < 1){
return true;
} else {
return false;
}
}
$response = array();
$response["success"] = false;
$response["reason"] = 0;
if (usernameAvailable()){
$userID = registerUser();
$response["success"] = true;
$response["userId"] = $userID;
} else {
$response["reason"] = 1;
}
echo json_encode($response);
?>

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