Why am i getting a fatal error? [duplicate] - php

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 9 years ago.
Here is the snippet of code that is causing the error.
public function storeUser($email, $password) {
require_once 'include/user.config.inc.php';
$uuid = uniqid('', true);
//echo $uuid;
$hash = $this->hashSSHA($password);
//echo $hash;
$encrypted_password = $hash["encrypted"]; // encrypted password
//echo $encrypted_password;
$salt = $hash["salt"]; // salt
//echo $salt;
$query = "INSERT INTO user_table (unique_id, email_id, encrypted_password, salt, created_at) VALUES ( :uuid, :email, :encrypted_password, :salt, NOW()) ";
$query_params = array(
':uuid' => $uuid,
':email' => $email,
':encrypted_password' => $encrypted_password,
':salt' => $salt
);
try {
//These two statements run the query against the database table.
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error! Problem with first query!";
die(json_encode($response));
}
}
I am getting an error:
Notice: Undefined variable: db
Fatal error: Call to a member function prepare() on a non-object
It seems that $query and $query_params is causing the problem but I don't know why. It seems right to me.
Here's the other snippet of code
if ($db->isUserExisted($email)) {
// user is already existed - error response
$response["error"] = 2;
$response["error_msg"] = "User already exist";
echo json_encode($response);
} else {
$db->storeUser($email, $password);
}

Taking a guess here...
require_once only includes the file once, ever*. You have probably required that file before elsewhere, it's not getting loaded again, your $db variable is nowhere to be found.
* In the current script execution.

You never initialize your $db object.
You need something like the following before "$stmt = $db -> prepare($query);"
$db = new mydbclass();

Related

"Notice: Undefined variable" in PHP. How can I fix it? [duplicate]

This question already has answers here:
mysqli_prepare() expects parameter 1 to be mysqli
(3 answers)
Closed 1 year ago.
I have a registration form here. I am a dummy in PHP (this is PHP for an Android app). It worked, but I found that I can register with the same username and email, so I added functions to check the database for the same username and prevent that, as I am dummy, I get this error when trying to register -
Notice: Undefined variable: con in /storage/ssd1/448/5907448/public_html/Register.php on line 27
Warning: mysqli_prepare() expects parameter 1 to be mysqli, null given in /storage/ssd1/448/5907448/public_html/Register.php on line 27
Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, null given in /storage/ssd1/448/5907448/public_html/Register.php on line 28
Warning: mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt, null given in /storage/ssd1/448/5907448/public_html/Register.php on line 29
{"success":true}
My PHP code
<?php
$response = array();
if (!isset($_POST["username"], $_POST["email"], $_POST["password"])) {
$response['success'] = false;
$response['Error'] = "No needed data";
echo json_encode($response);
exit(0);
}
ob_start();
$con = mysqli_connect("host", "username", "password", "database");
ob_end_clean();
if (!$con) {
$response['success'] = false;
$response['Error'] = "Error Connecting" . PHP_EOL;
$response['Error'] .= "Error Code: " . mysqli_connect_errno() . PHP_EOL;
$response['Error'] .= "Error: " . mysqli_connect_error() . PHP_EOL;
echo json_encode($response);
exit(0);
}
function registerUser() {
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (username, email, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $username, $email, $password);
mysqli_stmt_execute($statement);
}
function usernameAvailable() {
global $con, $username;
$statement = mysqli_prepare($con, "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["success"] = false;
if (usernameAvailable()){
registerUser();
$response["success"] = true;
}
echo json_encode($response);
?>
PS: Connection data changed to default.
Add your variable $con to the parameters of your functions that need access to the database i.e. registerUser() and usernameAvailable()
You referenced a global, $con, and it’s returning undefined. Ensure that it has a value by debugging it using print_r or other alternatives. Due to it returning undefined no functions are running.
Although it is bad practise to reference a global variable, I would recommend either setting up a function that returns the $con variable or passing it.
function returnCon(){
$con = mysqli_connect("host", "username", "password", "database");
return $con
}
You can then use
$con = returnCon();

PDO Insert not working with bindParam

I am currently using PDO to connect to my database and it works, but when a user logs in, I want it to check if the user's id is already in a row, I have already done this in the code below:
<?php
require 'steamauth/steamauth.php';
if(!isset($_SESSION['steamid'])) {
$username = "Unknown";
$avatar = "defaultUser";
$accid = "Unknown";
$credits = "Not Applicable";
$avatarSmall = "smallUser"; //For Dashboard
} else {
include ('steamauth/userInfo.php');
$username = &$steamprofile['personaname'];
$avatar = &$steamprofile['avatarmedium'];
$accid = &$steamprofile['steamid'];
$avatarSmall = &$steamprofile['avatar']; //For Dashboard
$db_user = "USERNAME";
$db_pass = "PASSWORD";
$db_host = "HOST";
$db_name = "DATABASE NAME";
$db = new PDO("mysql:host=".$db_host.";db_name=".db_name, $db_user, $db_pass);
try{
$check = $db->prepare("SELECT userID from userData WHERE userID = :accountID");
$check->bindParam(':accountID', $accid, PDO::PARAM_INT);
$check->execute();
if(!$check){
die("Server Error: 404Check, Please Contact A Member Of Staff If This Error Continues.");
}else{
if($check->rowCount() > 0) {
$creditsQuery = $db->prepare("SELECT userCredits FROM userData WHERE userID = :accountID3");
$creditsQuery->bindParam(":accountID3", $accid, PDO::PARAM_INT);
$creditsQuery->execute();
//Set Credits To Variable From Database Column
$credits = $creditsQuery->fetch(PDO::FETCH_ASSOC);
}else{
$sql = $db->prepare("INSERT INTO userData (userID, userCredits) VALUES (:accountID2, '0')");
$sql->bindParam(':accountID2', $accid, PDO::PARAM_INT);
$sql->execute();
if(!$sql){
die('Server Error: 404Insert, Please Contact A Member Of Staff If This Error Continues.');
}
}
}
}catch(PDOException $e){
die ("Server Error: 404Connection, Please Contact A Member Of Staff If This Error Continues.");
}
}
?>
Although, when I login, it doesn't seem to store the user's id or credits as 0, and the table (userData) is empty.
Thanks,
Matt
This is wrong:
$check->execute();
if(!$check){
^^^^^^^
$check doesn't magically change into a boolean true/false if the execute fails. It will ALWAYS be a prepared statement object, and therefore always evaluate to true.
You didn't enable exceptions in PDO, therefore it runs in the default "return false on failure" mode, which means your code should be:
$res = $check->execute();
if(!$res) {
die(...);
}
And this holds true for your other prepare/execute blocks as well - Your script is killing itself before it ever gets to the insert query, because your test for database failure is wrong.

PHP code not inserting DETAILS in MYSQL database PDO [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
So I have this code that I'm executing when someone presses the "register" button.
I've read over the thing 10 times and can't find what I'm doing wrong.
The problem is: When you click register it doesn't insert the details into the database (even though it says it registered the user). I even looked through my db.php where I store the DB details.
Code for register page:
<?php
if(isset($_POST['register'])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$checkUsername = $odb->prepare("SELECT COUNT(*) FROM users WHERE username = :username");
$checkUsername->execute(array(':username' => $username));
$countUsername = $checkUsername -> fetchColumn(0);
$checkEmail = $odb->prepare("SELECT COUNT(*) FROM users WHERE email = :email");
$checkEmail->execute(array(':email' => $email));
$countEmail = $checkEmail -> fetchColumn(0);
if(!($countEmail == 0))
{
echo '<p>This e-mail has been taken.</p>';
}
elseif(!($countUsername == 0))
{
echo '<p>Error - this username has been taken.</p>';
}
else
{
try
{
$insertUser = $odb -> prepare('INSERT INTO users (username,password,email) VALUES(:username, :password, :email)');
$insertUser -> execute(array(':username' => $username, ':password' => $password, ':email' => $email));
echo 'Sucessfully registered.';
}
catch (PDOException $e)
{
echo 'Error: ' .$e->getMessage();
}
}
}
?>
When I use if(isset($_POST['register'])){ it doesn't echo any message or alter the database.
When I use if(isset($_GET['register'])){ it echos user registered but nothing is added to the database.
Here's my DB.php :
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'some_db');
define('DB_USERNAME', 'some_dbuser');
define('DB_PASSWORD', 'password');
$odb = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD);
$odb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
I hope someone knows what's going on, thanks!
Your form is processing as a GET request, not POST. The default form method is GET so either change/add method="post" or use $_GET. Using POST is a better option when sending user private user data.
Option A:
<form method="POST">
Option B (changing variable assignment):
if(isset($_GET['register'])){
$username = $_GET['username'];
$password = $_GET['password'];
$email = $_GET['email'];
$checkUsername = $odb->prepare("SELECT COUNT(*) FROM users WHERE username = :username");
$checkUsername->execute(array(':username' => $username));
$countUsername = $checkUsername -> fetchColumn(0);
$checkEmail = $odb->prepare("SELECT COUNT(*) FROM users WHERE email = :email");
$checkEmail->execute(array(':email' => $email));
$countEmail = $checkEmail -> fetchColumn(0);
if(!($countEmail == 0)) {
echo '<p>This e-mail has been taken.</p>';
} elseif(!($countUsername == 0)) {
echo '<p>Error - this username has been taken.</p>';
} else {
try {
$insertUser = $odb -> prepare('INSERT INTO users (username,password,email) VALUES(:username, :password, :email)');
$insertUser -> execute(array(':username' => $username, ':password' => $password, ':email' => $email));
echo 'Sucessfully registered.';
} catch (PDOException $e) {
echo 'Error: ' .$e->getMessage();
}
}
}
Also as previously noted passwords shouldn't be stored in plain text. MD5 and SHA1 are better than doing that but they aren't the best methods any more. Take a look at these posts:
http://php.net/manual/en/faq.passwords.php#faq.passwords.fasthash
https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords
I think you have a problem with the PDO data check this out:
http://php.net/manual/en/pdo.prepare.php
I am a MYSQL guy but I get the same error when not using mysql_real_escape_string and this error looks to be same but with PDO.

Mysqli: Fatal error: Call to a member function prepare() on null [duplicate]

This question already has answers here:
Fatal error: Call to a member function prepare() on a non-object in
(2 answers)
Closed 7 years ago.
I'm trying to convert a login function into class with some functions, it was working until I converted it into class, this is my code:
class merwaa_login {
public $conn;
public function __construct($conn) {
$this->conn = $conn;
if(isset($_POST['login-submit'])) {
$username = merwaa_clean($_POST['username']);
$password = merwaa_clean($_POST['password']);
$sql = $conn->prepare("SELECT * FROM users WHERE username = ? OR email = ?;");
$sql->bind_param('ss', $username, $username);
$sql->execute();
$all = $sql->get_result();
$all = $all->fetch_assoc();
if (count($all) === 0){
echo 'البيانات المدخلة خاطئة!';
}
else{
$hashed_pwd = $all['password'];
if (password_verify($password,$hashed_pwd)) {
echo 'كفو';
$_SESSION['username'] = $username = $all['username'];
if(isset($POST['rememberme'])) {
$uid = $all['ID'];
merwaa_set_jwt($username,$uid);
}
} else{
echo 'خطأ';
}
}
}
}
}
May I've some grammar mistakes, please notice me about it.
Change this :-
$sql = $conn->prepare("SELECT * FROM users WHERE username = ? OR email = ?;");
To this :-
$sql = $this->conn->prepare("SELECT * FROM users WHERE username = ? OR email = ?;");
Or, you could change public $conn to global $conn. Then you won't need to make the above change.
try to use $this->conn->prepare instead of $conn->prepare
and a proper connection object should be passed to the constructor

PHP PDO prepared insert - does not insert data and show no errors [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
This problem is driving me crazy, i tried everything. Is does not give me any error, but it does not insert anything to the database either. Database connection is good, and there should be no typos. Please take a look, and see if you can find the problem:
$err = array();
if (isset($_POST['submit'])) {
$ip = gethostbyname($_SERVER['REMOTE_ADDR']);
$date = "2012-02-02 02:02:02"; //Example
$uploader_name = $_POST['uploader_name'];
// Validation happens here...
if (empty($err)) {
$host = "host";
$dbname = "db";
$user = "user";
$pass = "pass";
try {
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$sql = "INSERT INTO `table` (`ip`, `date`, `uploader_name`)
VALUES (:ip, :date, :uploader_name)";
$stmt = $dbh->prepare($sql);
# the data we want to insert
$params = array(
':ip' => $ip,
':date' => $date,
':uploader_name' => $uploader_name
);
$stmt->execute($params);
$dbh = null;
} catch(PDOException $pe) {
die('SQL Error');
}
if (empty($err)) {
$err[] = "Success!";
}
}
}
Also, Im sure it gets to the insert part, because i get the 'Success' message.
Use this code to execute your statement. If there is a non-fatal error, it will display it.
$stmt->execute($params) or die(print_r($stmt->errorInfo(), true));
Almost certainly your db user does not have permissions to execute the statement you're asking against the table you're trying to execute against.
Are you using auto-commit? If not you may need to wrap your query in a transaction.
try
{
$dbh->beginTransaction();
// your code.
$dbh->commit();
}
catch(PDOException $pe)
{
$dbh->rollback();
die($pe->getMessage());
}
http://php.net/manual/en/pdo.transactions.php

Categories