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;
}
}
?>
Related
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
I am creating a web service for android and PHP registration process.
I am following this tutorial http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
The Issue is: My JSON works on localhost but not on a server. On a server it gives me this error but it stores the data on database successfully.
Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/pmc/public_html/zeusonline.me/zeus/include/DB_Functions.php on line 45
and the line 45 is:
$user = $stmt->get_result()->fetch_assoc();
Code samples->
Register.php file
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("status" => TRUE);
if (isset($_GET['username']) && isset($_GET['email']) &&
isset($_GET['country']) && isset($_GET['phone_number']) &&
isset($_GET['password']) && isset($_GET['lat']) && isset($_GET['lon'])) {
// receiving the post params
$username = $_GET['username'];
$email = $_GET['email'];
$country = $_GET['country'];
$phone_number = $_GET['phone_number'];
$password = $_GET['password'];
$lat = $_GET['lat'];
$lon = $_GET['lon'];
// check if user is already existed with the same email
if ($db->isUserExisted($email)) {
// user already existed
$response["status"] = FALSE;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
}
else if ($db->isUserExisted($phone_number)) {
// user already existed
$response["status"] = FALSE;
$response["error_msg"] = "User already existed with " . $phone_number;
echo json_encode($response);
}
else {
// create a new user
$user = $db->storeUser($username, $email, $country , $phone_number,
$password, $lat, $lon);
if ($user) {
// user stored successfully
$response["status"] = TRUE;
$response["user"]["uid"] = $user["unique_id"];
$response["user"]["username"] = $user["username"];
$response["user"]["email"] = $user["email"];
$response["user"]["country"] = $user["country"];
$response["user"]["phone_number"] = $user["phone_number"];
$response["user"]["country"] = $user["country"];
$response["user"]["height"] = $user["height"];
$response["user"]["weight"] = $user["weight"];
$response["user"]["is_number_verified"] =
$user["is_number_verified"];
$response["user"]["is_safe"] = $user["is_safe"];
$response["user"]["is_login"] = $user["is_login"];
$response["user"]["lat"] = $user["lat"];
$response["user"]["lon"] = $user["lon"];
$response["user"]["created_at"] = $user["created_at"];
echo json_encode($response);
} else {
// user failed to store
$response["Status"] = False;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["Status"] = TRUE;
$response["error_msg"] = "Required parameters are missing!";
echo json_encode($response);
}
?>
DB_Functions.php file
<?php
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($username, $email, $country, $phone_number,
$password, $lat, $lon) {
$uuid = uniqid('', true);
$height = 0;
$weight = 0;
$is_number_verified = False;
$is_safe = True;
$is_login = False;
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$stmt = $this->conn->prepare("INSERT INTO users (unique_id, username,
email, country, phone_number, password, salt, height, weight,
is_number_verified, is_safe, is_login, lat, lon, created_at) VALUES(?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,NOW())");
$stmt->bind_param("ssssssssssssss", $uuid, $username, $email, $country,
$phone_number, $encrypted_password, $salt, $height, $weight,
$is_number_verified, $is_safe, $is_login, $lat, $lon);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE phone_number
= ?");
$stmt->bind_param("s", $phone_number);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
}
?>
The URL for testing :
http://pakmanzil.com/zeusonline.me/zeus/register.php?username=bilal&email=bi#gmail.com&country=england&phone_number=03333524145&password=123&lat=0.0&lon=0.0
Change the email and phone_number to make it works please :)
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);
?>
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;
}
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();