Failed To Call Member Function Query On A Non-object, MySQLI - php

I have a problem with producing a Register using my MySQLI Code. The tables/connection variable is matching up, and the correct variables being passed through the query is populated with expected strings, when running a query or prepare & execute when performing any type of query, I get returned with the following:
Fatal error: Call to a member function query() on a non-object in
/var/www/New/API/FormValidations.php on line 40
My code is as followed:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username='$Username'");
$Query->execute();
$Number = $Query->num_rows;
if ($Number !== 0)
{
echo "Username Already In Use";
}
else
{
$Insert_User = $STD->prepare("INSERT INTO Users ('Username', 'Password') VALUES ('$Username', '$Password)");
$Insert_User->execute();
echo "Account Created!";
}
Here is My Connection Script:
$STD = new mysqli('localhost', 'root', 'xxxxx', 'SLMS');
$AccessCon = new mysqli('localhost', 'root', 'xxxxx', 'DBAccess');
if ($AccessCon->connect_error) {
die("Access Has Been Revoked. Please Contact Administration");
}
if ($STD->connect_error) {
die("Standard Access Has Been Revoked. Please Contact Administration");
}
and my SQL Table for Users:
CREATE TABLE IF NOT EXISTS `Users` (
`ID` int(255) NOT NULL AUTO_INCREMENT,
`Username` varchar(255) NOT NULL,
`Password` text NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
I have tried commenting out all my query code, and running
$Query = $STD->query("SHOW TABLES");
$Results = $STD->fetch_array(MYSQLI_ASSOC);
this still returned an error, on my $Query variable.
I have also tried modifying my code to search for something that is already present in the database:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username='Test'");
and tried to enclose my $Username As followed:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username='{$Username}'");
This has performed No Success. I was wondering if someone could shed some light on this situation?
Edit:
Commenting out the entire script and just running:
$Query = $STD->query("SHOW TABLES");
$test = $Query->fetch_array(MYSQLI_ASSOC);
print_r($test);
Returns a result.
UPDATE:
I have modified my code to:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username=?");
$Query->bind_param("s", $Username);
$Query->execute();
Final Update:
Fatal error: Call to a member function bind_param() on a non-object
in /var/www/New/Register.php on line 45
This is the new Error.
The offending lines:
$Insert_User = $STD->prepare("INSERT INTO Users ('Username', 'Password') VALUES (?, ?)");
$Insert_User->bind_param("ss", $Username, $Password);
$Insert_User->execute();

When using prepare you have to bind the varables that hold your values.
Example:
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
here is link to prepared statements
Update
this:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username=s");
should be:
$Query = $STD->prepare("SELECT * FROM Users WHERE Username=?");
this:
$Insert_User = $STD->prepare("INSERT INTO Users ('Username', 'Password') VALUES ('U', 'P)");
should be:
$Insert_User = $STD->prepare("INSERT INTO Users ('Username', 'Password') VALUES (?, ?)");
this :
$Insert_User->bind_param('U', $Username);
$Insert_User->bind_param('P', $Password);
should be this:
$Insert_User->bind_param('ss', $Username,$Password);

Related

Creating and Updating User Table With PHP/MySql Script

I am reading a book on PHP, MYSQL, JAVASCRIPT and JQUERY. While reading, I do type the code and see how it worked. I have the following script which I ran to create a table named: "users', and subsequently update the table with two users. When I ran the script in my browser, it only created the new table but failed to update it with the new users. I do not receive any error. Below is the entire script.
<?php // setup_users.php
require_once 'login.php';
$connection = new mysqli($hn, $un, $pw, $db);
if ($connection->connect_error) die($connection->connect_error);
$query = "CREATE TABLE users (
forename VARCHAR(32) NOT NULL,
surname VARCHAR(32) NOT NULL,
username VARCHAR(32) NOT NULL UNIQUE,
password VARCHAR(32) NOT NULL
)";
$result = $connection->query($query);
if (!$result) die($connection->error);
$salt1 = "qm&g";
$salt2 = "ph!#";
$forename = 'Baban';
$surname = 'Sadik';
$username = 'bsadik';
$password = 'babansadik1';
$token = hash('ripemd128', "$salt1$password$salt2");
add_user($connection, $forename, $surname, $username, $token);
$forename = 'Abdullah';
$surname = 'Abubakar';
$username = 'aabubakar';
$password = 'abakar1';
$token = hash('ripemd128', "$salt1$password$salt2");
add_user($connection, $forename, $surname, $username, $token);
function add_user($connection, $fn, $sn, $un, $pw) {
$query = "INSERT INTO users VALUES('$forename', '$surname', '$username', '$token')";
$result = $connection->query($query);
if (!$result) die($connection->error);
}
?>
Where did go wrong please?
You just missed to put column names in the insertion query in add_user function and you are passing undefined variables
Do like this
$query = "INSERT INTO users(forename, surname, username, password)
VALUES('$fn', '$sn', '$un', '$pw')";
Your add_user function has parameters different to what you are trying to use in the query itself.
Change the query to the following:
INSERT INTO users VALUES('$fn', '$sn', '$un', '$pw')
Note that you should use prepared statements instead, as currently the code is susceptible to SQL Injection attacks. If the book you're using doesn't contain information on using prepared statements, scrap the book and find one that does instead.

Inserting values into a table with a PHP-variable name

I'm setting up a simple website where each user gets their own table (bad idea, I know), in which other users can put comments into - like a super budget version of a Facebook-wall.
This is what my query looks like when I create the table:
$userTable = mysqli_query($conn, "CREATE TABLE `".$epost."`(
ID INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
eMail VARCHAR(50) NOT NULL,
comment VARCHAR(500) NOT NULL,
timestampp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)");
However, when I try to take the values from a form, and insert them into the specific table they can't seem to find their way in there. Here's my code of that:
<?php
include 'connect.php';
/*if(isset ($_POST['userUser']))*/
$valueEmail = mysqli_real_escape_string($conn, $_POST['userEmail']);
$valueUser = mysqli_real_escape_string($conn, $_POST['userUser']); /*have the user to input the name, so i can connect to the correct DB*/
$valueMessage = mysqli_real_escape_string($conn, $_POST['userMessage']);
$findUserTable = "SELECT * FROM UserInfo WHERE Firstname = '$valueUser'";
$findUserEmail = mysqli_query($conn, $findUserTable);
if(mysqli_num_rows($findUserEmail) > 0) /*finding the name of the persons email*/
{
while ($result = mysqli_fetch_assoc($findUserEmail))
{
$email = $result['Email'];
}
}
/* VALIDATION HERE */
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
header("refresh:10 url=userProfil.php");
/*echo '<script>alert("Meddelande skapat!");</script>';*/
echo $sql;
mysqli_close($conn);
?>
I've been trying different 'versions' of the variable, like ".$email.", '.$email.' and ".$epost.". I get the correct name when i echo out my query or just the variable - but it can't seem to find the table?
I'm very aware that my code smells badly, so please spare me on that point.
You just simple write your query forget to execute it.
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
Use this
mysqli_query($conn,$sql);//for execute
Better use Bind and prepare statement as
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES (? ,?)"; /* wrong query?*/
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $valueEmail, $valueMessage);
/* Execute the statement */
$stmt->execute();
$row = $stmt->affected_rows;
if ($row > 0) {
echo "data inserted";
} else {
"error";
}
Read http://php.net/manual/en/mysqli-stmt.bind-param.php

PHP returning output from a Stored Procedure

I have seen and read a few questions about this but I can't figure out what's going on. I have a SP that inserts into a table and then returns just a single column with the last inserted id(Since I'm executing multiple statments lastInsertID() doesn't work.
CREATE DEFINER=`graffixnyc`#`%` PROCEDURE `createUser`(
IN userName VARCHAR(50),
IN firstName VARCHAR(25),
IN lastName VARCHAR(25),
IN pass text)
BEGIN
SELECT FLOOR(RAND() * 0xFFFFFFFF) into #salt;
INSERT INTO `users` (`username`, `first_name`,`last_name`,`salt`,`password`)
VALUES (userName, firstName,lastName, (select
#salt),sha2(concat(md5(pass(select #salt)),256));
SELECT LAST_INSERT_ID() as lastinsert;
END
Now when I execute this is MySql is returns the value of the last inserted record. When I try to access it with PHP I get Null.
$paramUsername = $req->params('username'); // Getting parameter with names
$paramFirstName = $req->params('firstname');
$paramLastName = $req->params('lastname');
$paramPassword = $req->params('password');
$sql = "CALL createUser(:username, :firstname,:lastname,:password)";
try {
$dbCon = getConnection();
$stmt = $dbCon->prepare($sql);
$stmt->bindParam("username", $paramUsername);
$stmt->bindParam("firstname", $paramFirstName);
$stmt->bindParam("lastname", $paramLastName);
$stmt->bindParam("password", $paramPassword);
$stmt->execute();
$row= $stmt->fetch();
$last_id=$row["lastinsert"];
$user->id =$last_id;
I have also tried using an output Paramater like so:
CREATE DEFINER=`graffixnyc`#`%` PROCEDURE `createUser`(
IN userName VARCHAR(50),
IN firstName VARCHAR(25),
IN lastName VARCHAR(25),
IN pass text,
OUT lastinsert INT)
BEGIN
SELECT FLOOR(RAND() * 0xFFFFFFFF) into #salt;
INSERT INTO `users` (`username`, `first_name`,`last_name`,`salt`,`password`)
VALUES (userName, firstName,lastName, (select
#salt),sha2(concat(md5(pass(select #salt)),256));
SET lastinsert=(SELECT LAST_INSERT_ID());
SELECT lastinsert;
END
$paramUsername = $req->params('username');
$paramFirstName = $req->params('firstname');
$paramLastName = $req->params('lastname');
$paramPassword = $req->params('password');
$sql = "CALL createUser(:username, :firstname,:lastname,:password,
#lastinsert)";
try {
$dbCon = getConnection();
$stmt = $dbCon->prepare($sql);
$stmt->bindParam("username", $paramUsername);
$stmt->bindParam("firstname", $paramFirstName);
$stmt->bindParam("lastname", $paramLastName);
$stmt->bindParam("password", $paramPassword);
$stmt->execute();
$row = $dbCon->query("select #lastinsert;")>fetch();
$last_id=$row["#lastinsert"];
$user->id =$last_id;
When I try it like this I get this error:
{"error":{"text":SQLSTATE[HY000]: General error: 2014 Cannot execute queries
while other unbuffered queries are active. Consider using
PDOStatement::fetchAll(). Alternatively, if your code is only ever going to
run against mysql, you may enable query buffering by setting the
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.}}
So I tried FetchAll and got the same error.. I then tried this which I found here which works but since it's only returning 1 row with 1 feild it doesn't seem like I should really need to loop through anything:
$stmt->execute();
$stmt = $dbCon->prepare("select #lastinsert;");
$outputArray = $dbCon->query("select #lastinsert;")->fetchAll();
foreach($outputArray as $row)
{
$last_id=$row["#lastinsert"];
}
So if there a better way to do this? I'm sure there is. I'm pretty new to PHP and mySQL but have a lot of experience with SQLServer so any insight would be appreciated.
I figured it out.. This works well and I don't need the input paramater or the loop:
SP:
CREATE DEFINER=`graffixnyc`#`%` PROCEDURE `createUser`(
IN userName VARCHAR(50),
IN firstName VARCHAR(25),
IN lastName VARCHAR(25),
IN pass text)
BEGIN
SELECT FLOOR(RAND() * 0xFFFFFFFF) into #salt;
INSERT INTO `users` (`username`, `first_name`,
`last_name`,`salt`,`password`)
VALUES (userName, firstName,lastName, (select #salt),sha2(concat(md5(pass
),(select #salt)),256));
SELECT LAST_INSERT_ID()as lastinsert;
END
PHP:
$paramUsername = $req->params('username');
$paramFirstName = $req->params('firstname');
$paramLastName = $req->params('lastname');
$paramPassword = $req->params('password');
$sql = "CALL createUser(:username, :firstname,:lastname,:password)";
try {
$dbCon = getConnection();
$stmt = $dbCon->prepare($sql);
$stmt->bindParam("username", $paramUsername);
$stmt->bindParam("firstname", $paramFirstName);
$stmt->bindParam("lastname", $paramLastName);
$stmt->bindParam("password", $paramPassword);
$stmt->execute();
$user->id =$stmt->fetchColumn(0);
$dbCon = null;

run insert query once only when the database is created php pdo

from config.php
<?php
global $dbh;
$dbname = 'memberdb';
try {
$dbh = new PDO("mysql:host=localhost", "root", "");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbname = "`".str_replace("`","``",$dbname)."`";
$dbh->query("CREATE DATABASE IF NOT EXISTS $dbname");
$dbh->query("use $dbname");
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql ="CREATE TABLE IF NOT EXISTS $member (
mem_id int(40) NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(40) NOT NULL,
password VARCHAR(40) NOT NULL);" ;
$dbh->exec($sql);
$stmt = $dbh->prepare("INSERT INTO member (username, password) VALUES (?,?)")or die($db->errorInfo());
$stmt->bindValue(1,"admin1",PDO::PARAM_STR);
$stmt->bindValue(2,"password1",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin2",PDO::PARAM_STR);
$stmt->bindValue(2,"password2",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin3",PDO::PARAM_STR);
$stmt->bindValue(2,"password3",PDO::PARAM_STR);
$stmt->execute();
} catch(PDOException $e) {
}
?>
This is my function of new user when the user is registered using a registered button.
How to make this kind of function run only one, when the database is created and only.
I will need to put defined value for each input but i didnt not change it yet
UPDATE
The code i used is above my prob is still the same when i reload the index.php the query runs again making double entry..what i want is that when the database is create the query will run and when loaded the database is not created again so i want the query to not run again to avoid double entry.
$stmt = $dbh->prepare("SELECT * FROM member") ;
$stmt->execute();
$count = $stmt -> rowCount();
echo $count;
if( $count == 00 ){
$stmt = $dbh->prepare("INSERT INTO member (username, password) VALUES (?,?)")or die($db->errorInfo());
$stmt->bindValue(1,"admin1",PDO::PARAM_STR);
$stmt->bindValue(2,"password1",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin2",PDO::PARAM_STR);
$stmt->bindValue(2,"password2",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin3",PDO::PARAM_STR);
$stmt->bindValue(2,"password3",PDO::PARAM_STR);
$stmt->execute();
}
i only have one more question why is it sometimess the echo for count is 3 and sometimes its 33 its like the query is run twice please clear this out...this worked but maybe just maybe there are incorrect logic here please feel free to edit to make it perfect.

Calling method from a non-object?

$query = "INSERT INTO users (name, password) VALUES ('$myusername', '$mypassword')";
if (!($result = $mysqli->query($query)))
die("WHAT???? " . $mysqli->error . " EEEEEFFFFFFF.");
$count = $result->num_rows;
while ($row = $result->fetch_array()) {
if ($row[name] == $myusername) {
$mysqli->query("DELETE FROM users WHERE name='$myusername' AND password='$mypassword'");
$count = 5;
}
}
When I run this, it gives me an error:
Fatal error: Call to a member function fetch_array() on a non-object in /home/appstore/public_html/phpstoof/signedup.php on line 26
Where line 26 is where the while statement starts (while(x)). $mysqli ALREADY an instance of mysqli(). I don't see the how this is an error if the same code works on another file.
An INSERT statement has nothing to fetch.
As #mellamokb says, INSERT has nothing to fetch. Also you have used a mix of MySQL and MySQLi.
With MySQLi, the code should be like:
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_database);
$str_sql = 'INSERT INTO users (name, password) VALUES (?, ?)';
// Create a prepared statement
$stmt = $mysqli->prepare($str_sql);
// Bind parameters for markers; same order and same count in prepared statement
$stmt->bind_param('ss', $myusername, $mypassword);
// Execute query
$stmt->execute();
// *************************************************************************
// If you're using a SELECT statement, each output field must be bound to
// a variable in the same order as in SELECT
// Bind result variables
$stmt->bind_result($_var1, $_var2, $_var3, ...);
// Fetch results and generate output as an associative array
while ($stmt->fetch())
{
// Handle $_var1, $_var2, $_var3, ...
}
// *************************************************************************
// Free stored result memory
$stmt->free_result();
// Close statement
$stmt->close();
// Close connection
$mysqli->close();

Categories