mysqli_query() expects parameter 1 to be mysqli error - mysqli

I have a problem with my scripts I need to change minimal of 30 scripts to the "new" mysqli but its terrible I know some basics but now I'm complete lost...
The connection to the database is ok, but now I have this error with this kind of rule in the script.... can someone help me out so I can learn from it ?
$sql_email_check = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT email
FROM users WHERE email='$email' AND status='Alive'");
$sql_username_check = mysqli_query($GLOBALS["___mysqli_ston"],
"SELECT username FROM users WHERE username='$reg_username'");
Update 1:
I cleared the error from the first rule of the script, i saw something on google similair.
This was my script:
$sql_email_check = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT email FROM users WHERE email='$email' AND status='Alive'");
And now this:
$sql_email_check = mysqli_query($con, "SELECT email FROM users WHERE email='$email' AND status='Alive'");
i replaced: $GLOBALS["___mysqli_ston"], with $con, $con i have already dentifyed in a other filte with the connection with db and included in this file Is this right and will it work ? the error's are disapearing but if it will work ?

This is how I do it...
$connection = new mysqli('database_name', 'user', 'password', 'table_name');
$email = 'emailAddressYouWantToLookUp';
$sql = "SELECT email FROM users WHERE email = '$email' AND status = 'Alive';";
$results = $connection->query($sql);
$emailFoundInDatabase = '';
if ($results->num_rows > 0) {
while($row = $results->fetch_assoc()) {
$emailFoundInDatabase = $row['email'];
};
};
echo $emailFoundInDatabase;

Close!
The solution was
replacing: $GLOBALS["___mysqli_ston"], with $con,
I have $con in a other file that makes a connection with the database and included in this script.
Also got a weird error about
i replaced that with:
and now all error's are gone and this script is working 100%
Thanks

Related

Fatal error: require_once(): Failed opening required ... Novice programmer, appreciate any guidance

I'm a novice in server-side programming so any advice is appreciated.
I have some PHP files uploaded on a virtual server (000webhost.com) and I'm having trouble with locating a file I'm requiring in another PHP file. The register.php is attempting to "require_once" the update_user_info.php
Here's the code for register.php (Which I've taken from a tutorial and adjusted it with my variables):
<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'../update_user_info.php');
$db = new update_user_info();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST ['password']) && isset($_POST['branch']) && isset($_POST['gender'])) {
// receiving the post params
$username = $_POST['username'];
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$branch = $_POST['branch'];
$gender = $_POST['gender'];
// check if user is already existed with the same email
if ($db->CheckExistingUser($email)) {
// user already existed
$response["error"] = TRUE;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->StoreUserInfo($username, $name, $email, $password, $branch, $gender);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["user"]["username"] = $user["username"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["branch"] = $user["branch"];
$response["user"]["gender"] = $user["gender"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter (username, name, email or password) is missing!";
echo json_encode($response);
}
?>
And here's a screenshot of the error that's occurring when attempting to visit the link containing the register.php:
Screenshot of the error
What I've tried so far:
1- tried to use require_once __DIR__."/../filename.php"; and lots more of the same, basically tinkering the statement with different language constructs and constants.
2-Read tutorials on the correct way to use require once but their cases is almost always very different. Either they are using WAMP/XAMPP -meaning they have a local path not a virtual one- So no luck there.
3- tried to change .htaccess file, as someone said in a post that it solved his problem.
4- I'm certain that both files are uploaded to the same directory. Yet it says "No such file".
Does anyone have an idea of where the error could be stemming from? Thanks in advance!

Converting mysql_query to mysqli_query

I just moved to xampp version 7.0.13, which now has PHP 7.x, and the following query no longer works. I was Hoping someone can help me convert the following to mysqli query. I don't write code, so any help you could give me would be great.
// Count the number of rows in the member table
$rows = "SELECT * FROM $db_name.$tbl_name";
$count_rows = mysql_query( $rows );
here is your example with PDO:
$pdo = new PDO('mysql:host=localhost;dbname=databasename', 'username', 'password');
$sql = 'SELECT * FROM :table';
$statement = $pdo->prepare($sql);
$count = $statement->execute(array('table' => 'your-table-name'))->rowCount();

Mysqli bind_result error

I am new to SQL and PHP. My goal is simple: Check if there is already an email adress stored in database. I am using following code:
$email = info#test.pl;
$conn = new mysqli("localhost", "root", "", "mysite"); // Create connection
if ($conn->connect_error) { // Check connection
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT * FROM contacts WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$result = $stmt->num_rows;
echo $result;
Every time i get an error. It says i am using wrong numbers of parameters in bind_result. How it can be?
If you're new to all this, I would recommend using PDO instead of mysqli.
As for your error: you select * columns but bind only one.
You can change the query to select email, or do away with binding the resultset:
if all you want is to check for the presence of the email, all you need is the rowcount.

Hashing password in register and account settings

I am get login errors when i test my script by logining under my own account. Do you think hashing passwords twice a bad practice?
I have hashed the users password twice in my website. Once, when they register and once, when they update their password in account update. Also i am using bcrypt method and cost of bcrypting is 10 on both hashings and i am on localhost server.
///// this is the code in register.php page
<?php
if(isset($_POST['registeruser'])) {
session_start();
$FName = $_POST['regfname'];
$LName = $_POST['reglname'];
$Email = mysqli_real_escape_string($conn, $_POST['regemail']);
$origignalpassword = preg_replace('#[^a-z0-9_]#i', '',
$_POST['regpassword']);
$Passwordw = $_POST['confirmedpassword'];
$infosql = "SELECT * FROM users WHERE useremail = '".$Email."'";
$result = mysqli_query($conn,$infosql);
if(mysqli_num_rows($result)>=1)
{
echo "Email already taken.";
}
else if(mysqli_num_rows($result) !=1 && $Passwordw ==
$origignalpassword) {
$Passwordhash = password_hash($Passwordw,
PASSWORD_BCRYPT, array('cost' => 10));
$sql = $conn->query("INSERT INTO users(firstname,
lastname, useremail, Passwordcell) Values('{$FName}',
'{$LName}','{$Email}','{$Psswordhash}')");
header('Location: login.php');
} else {
echo 'Please check your password:' . '<br>';
}
}
?>
//// Below code is the code in my update.php page
<?php session_start();
if(isset($_SESSION['user_id'])) {
} else {
header('Location: login.php');
}
$user = $_SESSION['userid'];
$myquery = "SELECT * FROM users WHERE `userid`='$user'";
$result = mysqli_query($conn, $myquery);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
$_SESSION['upd_fnames'] = $row['firstname'];
$_SESSION['upd_lnames'] = $row['Lastname'];
$_SESSION['upd_emails'] = $row['useremail'];
$_SESSION['upd_passwords'] = $row['Passwordcell'];
$_SESSION['upd_phone'] = $row['phonenum'];
$_SESSION['upd_bio'] = $row['biography'];
?>
<?php
if (isset($_POST['updateme'])) {
$updfname = $_POST['upd_fnames'];
$updlname = $_POST['upd_lnames'];
$updemail = $_POST['upd_emails'];
$updphone = $_POST['upd_phone'];
$upd_pswd = $_POST['upd_passwords'];
$biography = $_POST['update_biography'];
$Pswod = password_hash($upd_pswd, PASSWORD_BCRYPT,
array('cost' => 10));
$sql_input = $mysqli->query("UPDATE users SET firstname = '{$updfname}', Lastname = '{$updlname}', Phonenum = '{$updphone}', useremail = '{$updemail}', Passwordcell = '{$Pswod}', biography = '{$biography}' WHERE userid=$user");
header('Location: Account.php');
}
else
{
}
?>
Your problem could be just a typo, in your registration script, instead of $Passwordhash you wrote:
"INSERT INTO users(..., Passwordcell) Values(...,'{$Psswordhash}')"
Nevertheless there are other problems with your code, and since you asked for advise, i would like to share my thoughts.
Probably the biggest problem is, that your code is vulnerable to SQL-injection. Switch to prepared statements as soon as you can, writing code will become even easier than building the query as you did, and both MYSQLI and PDO are supporting it. This answer could give you a start.
Passwords should not be sanitized. Remove the line $origignalpassword = preg_replace('#[^a-z0-9_]#i', '', $_POST['regpassword']), and just pass the input directly to the hash function password_hash($_POST['regpassword'], PASSWORD_DEFAULT). The password_hash() function works with any type of input.
It is a good habit to place an exit after each redirection, otherwise the script will continue executing. header('Location: login.php', true, 303); exit;
Do you really have reason to put the user info into the session? Instead of $_SESSION['upd_fnames'] = $row['firstname']; i would fetch the information on demand from the database. With fetching it from the database you can be sure that the information is actually set (is not null) and is up to date, you can avoid a state and you get a bit more REST full.
Then last but not least i would recommend to follow some style rules, like starting variable names always with a small letter. You can avoid some silly typos and it makes your code more readable.

PDO Prepared Select statement for checking if a user exists

I'm a pdo newbie and need to prepare and execute some php/pdo code:
This code works to allow me to create users in my database:
// Perform Insert / Update
$STH = $dbh->prepare("INSERT INTO users (username, email) values (:username, :email)");
$STH->bindParam(':username', $username);
$STH->bindParam(':email', $email);
try{
$STH->execute();
redirect_to(signupsuccess.php);
}
catch(PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
}
but before I put that data into the database I need to do a check to make sure the email doesn't already exist in the database. I need to do a SELECT, something like:
$STH = $dbh->prepare("SELECT FROM users (email) values (:email)");
$STH->bindParam(':email', $email);
try{
$STH->execute();
}
and I know I need to add
"WHERE something matches '$_POST'email') something.." ...
I'm totally lost at this point..I can do this without PDO but I want to start using PDO's prepared statements..Please help!
Just do a simple select. I recommend Using bind value if you may possibly have a null email.
$STH = $dbh->prepare("SELECT email FROM users WHERE email = :email");
$STH->bindValue(':email', $email);
try{
$STH->execute();
}
Then just check if any records are returned. If so, Update, don't insert. good luck.