I'm creating an authentification file with php and mysql, but I have this mistake in this line:
$stmt2->bind_param('ss',$twitter_id, $name);
The error message is
Call to a member function bind_param() on a non-object in ...
Where's my mistake?
$name in my database is a VARCHAR
$twitter_id in my database is a VARCHAR
$bd is my database connection
If a user is already registered, it should show me a message saying "User already registered", and if the user isn't registered, it should insert a new id and name in my database.
session_start();
if (!isset($_SESSION['userdata'])) {
header("location: index.php");
} else {
$userdata = $_SESSION['userdata'];
$name = $userdata->name;
$twitter_id = $userdata->id;
$stmt = $bd->prepare("SELECT ID_TWITTER FROM USERS");
$stmt->execute();
$stmt->bind_result($checkUser);
if ($stmt->fetch()) {
if($checkUser!==$twitter_id){
$cSQL = "INSERT INTO USERS (ID_TWITTER, FULL_NAME) VALUES(?,?)";
$stmt2 = $bd->prepare($cSQL);
$stmt2->bind_param('ss',$twitter_id, $name);
$stmt2->execute();
$stmt2->close();
} else {
echo "User already exits";
}
}
$stmt->close();
}
Could it be a typo? does $bd exist or should it be $db ?
Shameless plug: I do this exact thing in a project I have on github. Feel free to use the classes for whatever you like; they are mostly copy-pastable.
Your real issue is that $bd->prepare() returned false.
Check that you actually called it correctly and set it to new mysqli(*params)
The error Call to a member function ... on a non-object in ... means that $db is not an object, which means that it was not instantiated to an object. Thus, $this->method() isn't possible. bind_param(string $format, mixed &*vars); uses pass-by-reference and if this fails, it throws an error.
Try it yourself by sticking this in there:
$stmt->bind_param("ss", "string", "string");
To get around this issue where it can fail, check if $db->prepare() returns true:
if ($query = $bd->prepare($sql)) {
//stuff
}
In addition, in the first query you do it is probably not a good idea to be adding the overhead of a prepare for a single query that only checks row count without user input.
Solved : it works now
$stmt = $bd->prepare("SELECT ID_PROVIDER FROM USERS WHERE ID_PROVIDER = ?");
$stmt->bind_param('s', $twitter_id);
$stmt->execute();
$stmt->bind_result($checkUser);
while ($stmt->fetch()) {
$result = $checkUser;
}
if (empty($result)) {
$cSQL = "INSERT INTO USERS (ID_TWITTER, FULL_NAME)
VALUES(?,?)";
$stmt2 = $bd->prepare($cSQL);
$stmt2->bind_param('ss', $twitter_id, $name);
$stmt2->execute();
$stmt2->close();
}else {
echo "User already exits";
}
Related
I have created a PHP file called DB_Functions which contains my Delete method for removing a database row by User Id. Code:
//Delete User
public function deleteUser($id){
$stmt = $this->conn->prepare("DELETE FROM users WHERE user_id = ?");
$stmt->bind_param("s", $id);
$result = $stmt->execute();
$stmt->close();
}
I have then created another PHP file to act as an endpoint which calls this function after the Id is received as a POST parameter. Code:
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
//json response array
$response = array();
if(isset($_POST['id'])){
//recieve GET parameters
$id = $_POST['id'];
$result = $db->deleteUser($id);
if($result){
$response["error"] = FALSE;
$response["message"] = "User deleted succesfully";
}else{
$response["error"] = TRUE;
$response["error_msg"] = "User did not delete";
}
echo json_encode($response);
}
When testing this using Advanced Rest Client and when using with an Andriod development I am working on, the row is deleted from the database but the parsed response in ARC is the error message and in the Android Logcat the same response message of "User did not delete" is shown?
Any help?
In your deleteUser function you are missing return statement. If you do not return anything then function will always return null.
So, In your case it's returning NULL and in further condition check it's going to else case.
public function deleteUser($id){
$stmt = $this->conn->prepare("DELETE FROM users WHERE user_id = ?");
$stmt->bind_param("s", $id);
$result = $stmt->execute();
$stmt->close();
return $result; // add this
}
Your function does not return any value, so when being compiled automatically returns a NULL value, which is why the error is always shown.
You need to add a return statement.
Return the result in the function...
public function deleteUser($id){
$stmt = $this->conn->prepare("DELETE FROM users WHERE user_id = ?");
$stmt->bind_param("s", $id);
$result = $stmt->execute();
$stmt->close();
return $result;
}
So I am grabbing the amount of rows in a specific table where the username is already in the database like so:
$second_sql = $db->prepare("SELECT * FROM users WHERE username = :username");
$second_sql->bindParam(':username', $username);
$second_sql->execute();
if($second_sql->rowCount() == 1) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
The problem is it's not working. If you need more of the script just tell me.
Some databases does not report the row count with PDO->rowCount() method.
SQLite, for instance.
So don't use rowCount(); doing so makes your code less portable.
Instead use the COUNT(*) function in your query, and store the result in a variable.
Finally, use that variable to fetch the one and only column (users) using the fetchColumn() method.
So you can play with this:
try {
$second_sql = $db->prepare("SELECT COUNT(*) from users WHERE username = :username");
$second_sql->bindParam(':username', $username, PDO::PARAM_STR);
$second_sql->execute();
$count = $second_sql->fetchColumn();
} catch (PDOException $e) {
// Here you can log your error
// or send an email
// Never echo this exception on production
// Only on development fase
echo "Error: " . $e->getMessage();
}
if ($count) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
Perhaps you wanna test you condition for a single row:
if ($count == 1)
Hope this helps you.
Cheers!
I need a second pair of eyes on this. I can NOT figure out why this function works just fine:
function get_password($db, $id) {
try {
$sql = $db->prepare('SELECT password FROM employee
WHERE employee.emp_id = ?');
$sql->bindParam(1, $id);
$sql->execute();
$password = $sql->fetchColumn();
} catch(Exception $e) {
echo $e->getMessage();
die();
}
return $password;
}
and this function fails on fetchColumn():
function get_name($db, $email) {
try {
$sql = $db->prepare('SELECT login
FROM employee
WHERE email = ?');
$sql->bindParam(1, $email);
$sql->execute();
$user_name = $sql->fetchColumn(0);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
return $user_name;
}
I have verified the following:
I am trimming the email, so no extra white space is in there
the query works from the command line
the prepare() statement is successful and errorInfo() returns nothing
the bindParam() statement returns true and errorInfo() returns nothing
the execute() statement returns 1 row and errorInfo() returns nothing
the fetchColumn(0) statement returns False (ARGH!!!!) but errorInfo() still returns nothing.
I have also tried using just fetchColumn(), fetchAll, and other fetch attempts.
I have also tried re-writing in the SELECT to this:
'SELECT employee.login FROM employee WHERE employee.email = ?'
but results are the same.
Is there some concept here I'm missing? Any other ideas of how I might debug this?
I have a problem with variables in an SQL Statement. I have a form where a user can update his profile. The form redirects to action.php?action=settings
When I try without $variables, there is no problem! But the thing is, I have a lot of queries like this, but not for updating.
function change_user_data($trainer) {
require("database.php");
try {
$results = $db->query("UPDATE trainer SET email='$email', status='$status', password='$password' WHERE name='$trainer'");
} catch (Exception $e) {
echo "Data could not be changed!";
exit;
}
}
and this is my action.php
if ($action == "settings") {
$email = $_POST['email'];
$status = $_POST['status'];
$password = $_POST['password'];
change_user_data($trainer);
}
When I echo those $variables, they get displayed so they are not empty. But this query updates my table but with no data, so everything is empty afterwards.
I think the problem is variable scope.
Variables defined outside of function cannot use in function except global variable or something.
You have two method.
First. If change_user_data function is in action.php file, add "global $email, $status, $password" like this:
function change_user_data($trainer) {
global $email, $status, $password;
require("database.php");
try {
$results = $db->query("UPDATE trainer SET email='$email', status='$status', password='$password' WHERE name='$trainer'");
} catch (Exception $e) {
echo "Data could not be changed!";
exit;
}
}
Or second. Pass the email, status, password data to function. Then you can use it.
Please check this manual:
http://php.net/manual/en/language.variables.scope.php
you can try this:
$results = $db->query("UPDATE trainer SET email='".$email."', status='".$status."', password='".$password."' WHERE name='".$trainer."'");
change_user_data($trainer, $email, $password, $status);
function change_user_data($trainer, $email, $password, $status) {
require("database.php");
try {
$results = $db->query("UPDATE trainer SET email='$email', status='$status', password='$password' WHERE name='$trainer'");
} catch (Exception $e) {
echo "Data could not be changed!";
exit;
}
}
After You Gettings Post varibles Then Check For those variables
whether those are empty or not
if not empty or NULL Then Update Database with Update Query With Non empty Variables
May be
Wrong data type of your columns. Check your table structure carefully. Example: if you set you column email as int then you cannot insert or update it's row value as text or letter
Incorrect variables inside single quote. Try to concatenate variable and query string for better practice
If those don't work
Try to make mysql syntax error and check values of those variables, then you can define the error.
Sorry for my bad english
You have few problems with this function:
Scoping issue, you did not pass all values
You are vulnerable to sql injection
You dont check if the record is updated
function:
function change_user_data($db, $params) {
try {
$sql = "UPDATE trainer SET email= ?, status=?, password=? WHERE name=?";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$success = ($stmt->rowCount() > 0) ? true : false;
} catch (Exception $e) {
echo "Data could not be changed!";
$success = false;
}
return $success;
}
Usage
require("database.php");
$params = array($trainer, $email, $password, $status);
$user_data_updated = change_user_data($db, $params);
if($user_data_updated){
echo 'user data updated';
}else{
echo 'user data did not update';
}
I'm trying to fetch results using mysqli->fetch_row() (or fetch_object(), fetch_array()), yet when I go to run the code at run time it gives me the following error:
Fatal error: Call to a member function fetch_row() on a non-object in...on line 23.
The var in question that does this is $results in the code below. $user and $password gain their values from another .php file that this file is being included in so that's not really important at the moment. Now correct me if I'm wrong but if $results is being set = to $db->query($query) then isn't it supposed to inherit the properties of $db aka the mysqli class?
class mySQLHelper{
public function checkPass($user, $pass){
global $db;
$db = new mysqli();
$db->connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()){
echo 'Can not connect to database';
echo mysqli_connect_errno(). mysqli_connect_error();
exit;
return false;
}
$query = "SELECT user, password FROM Users WHERE user = $user AND password = $pass " ;
echo $query;
$results = $db->query($query);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
$results->close();
$url = 'http://'. $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
if(!$results){
// mysqli_close($db);
// header("Location:.$url.login.php&msg=1");
}
else{
// mysqli_close($db);
// header("Location:.$url.featured.php");
}
}
}
Your query is failing on this line:
$results = $db->query($query);
Because of this, $results is false - not a result object as you expect.
To fix the issue, you need to add quotes around your variables (or use prepared statements):
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
I would suggest updating to use a prepared statement to prevent SQL-injection issues too though:
$stmt = $db->prepare('SELECT user, password FROM Users WHERE user = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$results = $stmt->get_result();
You script is lacking error checking, and therefore the error in the query is not handled.
$query = "SELECT user, password FROM Users
WHERE user = '$user' AND password = '$pass' " ;
// ^ quotes needed
echo $query;
$results = $db->query($query);
// handle a error in the query
if(!$results)
die($db->error);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
If you user & password field text or varchar, then you need to use single quote around them
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
You have to check, if query runs properly:
if ($result = $mysqli->query($query))
{
}
Use: var_dump($results) to check what it contains
Why are you checking if($results) after trying to manipulate it?
This...
$results->close();
//...
if(!$results){
//...
}
Should be...
if(!$results){
//...
}
$results->close();