prepare statement fatal error - php

<?php
//Defining page title
define('WEBSITE_TITLE', 'Register');
//Content location
$content = 'content/register.php';
//Database connection
try {
$dbh = new PDO('mysql:host=localhost;dbname=saldev', 'admin', '420blazeit');
$dbh = null;
} catch (PDOException $e) {
die();
}
//Including website template
include_once 'template.php';
if(isset($_POST['submitRegister'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$email = $_POST['email'];
$rank = 'user';
$ins = $dbh->prepare("INSERT INTO 'users'('username', 'password', 'email', 'rank') VALUES (''username','password', 'email','user')");
$ins->execute();
echo 'Success! you have been register';
header("Location: index.php");
}
?>
I get the following error: "Fatal error: Call to a member function prepare() on null in C:\workspace\register.php on line 23"
I have been trying to find out what the problem is, but I haven't got a clue how to fix this. Somebody please help! :c

You have two single quotes '. Replace
$ins = $dbh->prepare("INSERT INTO 'users'('username', 'password', 'email', 'rank') VALUES (''username','password', 'email','user')");
to
$ins = $dbh->prepare("INSERT INTO users (username, password, email, rank) VALUES ('username','password', 'email','user')");
Also remove $dbh = null;.

Well, you setting null on $dbh
$dbh = null;
Also you should not use ' inside the mysql query for tables or columns names.

Related

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

Simple Insert Variable PHP into MySQL

I have a simple bit of code that I can't get working.
<?php
$mysqli_connection = new MySQLi('localhost', 'root', 'secret', 'edgeserver');
if ($mysqli_connection->connect_error) {
echo "Not connected, error: " . $mysqli_connection->connect_error;
$username = 'Eddie';
$username = mysql_real_escape_string($username);
$email = 'eddie_the_eagle#hotmail.com';
$email = mysql_real_escape_string($email);
$sql = "INSERT INTO `users` (`username`, `email`)
VALUES ( '".$username."', '".$email."')";
$res = $mysqli_connection->query($sql);
}
?>
When I run the code no error appears but the users table remains empty.
Try This
<?php
$mysqli_connection = new MySQLi('localhost', 'root', 'secret', 'edgeserver');
if ($mysqli_connection->connect_error)
{
echo "Not connected, error: " . $mysqli_connection->connect_error;
}//Change
$username = 'Eddie';
$username = mysqli_real_escape_string($mysqli_connection,$username);//Change
$email = 'eddie_the_eagle#hotmail.com';
$email = mysqli_real_escape_string($mysqli_connection,$email); //Change
$sql = "INSERT INTO users (username, email) VALUES ( '".$username."', '".$email."')";
$res = $mysqli_connection->query($sql);
?>
You were mixing two API's mysql and mysqli. Stop using deprecated mysql
$username = mysqli_real_escape_string($mysqli_connection,$username);
$email = mysqli_real_escape_string($mysqli_connection,$email);
And you forgot to close your if condition too
if ($mysqli_connection->connect_error) {
echo "Not connected, error: " . $mysqli_connection->connect_error;
}//<------forgot
There are two problems:-
you are mixing mysql_* with mysqli_*
no error checking is done.
Try like this:-
<?php
$mysqli_connection = new MySQLi('localhost', 'root', 'secret', 'edgeserver');
if ($mysqli_connection->connect_error)
{
echo "Not connected, error: " . $mysqli_connection->connect_error;
}//Change
$username = 'Eddie';
$username = mysqli_real_escape_string($mysqli_connection,$username);//connection link must be provided as a first parameter
$email = 'eddie_the_eagle#hotmail.com';
$email = mysqli_real_escape_string($mysqli_connection,$email); //same here
$sql = "INSERT INTO users (username, email) VALUES ( '".$username."', '".$email."')";
$res = $mysqli_connection->query($sql);
?>
Note:-Please habitat yourselves to use error reporting when you are going to do any stuff. thanks.
You forgot to close your if statement, so your insert logic will only run if there is an connect error.
Move the last } to a new line after
$mysqli_connection->connect_error;

Data not inserting into database

So I have my form that sends data to my php file that then enters it into the database. Here's the php backend part
<?php
$db = new mysqli('localhost','root','x','app');
$username = $_POST['username'];
$db->query("INSERT INTO people (first_name) VALUES ('{$username}'");
?>
But my question is, why isn't username being put into the database?
You are missing a bracket ) in the following line:
("INSERT INTO people (first_name) VALUES ('{$username}' ")
^ // <= right there
change it to:
("INSERT INTO people (first_name) VALUES ('{$username}')")
Yet, as pointed out in comments, you are open to SQL injection when using your present method.
Use prepared statements, or PDO.
Here follows an example of a prepared statement:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = #mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');
if (!$mysqli) {
die('Connect Error: ' . mysqli_connect_error());
}
// $username = $_POST['username'];
$username = mysqli_real_escape_string($mysqli,$_POST['username']);
$sql = ("INSERT INTO people (first_name) VALUES (?)");
$stmt = $mysqli->prepare($sql) or die("Failed Execution");
$stmt->bind_param('s', $username);
$stmt->execute();
echo $stmt->error;
echo "SUCCESS";
exit();
Plus, using error reporting is important before going live.
http://www.php.net/mysqli_error
Should you want to get into learning PDO,
Here are a few tutorials for you to look into:
PDO tutorial one
PDO tutorial two
PDO tutorial three
Here is a PDO example:
<?php
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';
try{
$db= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$email = $_POST['email'];
$username = $_POST['username'];
$result_set = $db->prepare("INSERT INTO `yourTable` (`email`, `username`)
VALUES (:email, :username)");
$result_set->bindParam(1, $email);
$result_set->bindParam(2, $username);
$result_set->execute(array(':email' => $email, ':username' => $username));
echo "Data successfully written.";
return $db;
}catch(PDOException $e){
echo $e;
return false;
}
?>
PDO error handling links:
http://www.php.net/manual/en/pdo.error-handling.php
http://www.php.net/manual/en/pdo.errorinfo.php

Why won't the data be stored in my database?

Sorry I am new to php so please be patient with me. I am creating a user interface and when I register it says I have registered but it doesn't store the data into the database. can someone please help me!
<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
$uLength = strlen($uname);
$pLength = strlen($pword);
if ($uLength >= 10 && $uLength <= 20) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Username must be between 10 and 20 characters" . "<BR>";
}
if ($pLength >= 8 && $pLength <= 16) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Password must be between 8 and 16 characters" . "<BR>";
}
if ($errorMessage == "") {
$user_name = "root";
$pass_word = "";
$database = "user authentication";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM login WHERE USERNAME = $uname";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "Username already taken";
}
else {
$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
}
else {
$errorMessage = "Database Not Found";
}
}
}
?>
<html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION ="signup.php">
Username: <INPUT TYPE = 'TEXT' Name ='username' value="<?PHP print $uname;?>" maxlength="20">
Password: <INPUT TYPE = 'TEXT' Name ='password' value="<?PHP print $pword;?>" maxlength="16">
<P>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Register">
</FORM>
<P>
<?PHP print $errorMessage;?>
</body>
</html>
You might also want to rather make use of PDO then you don't have to to do the cleanup of the user input as PDO will take care of that for you. You might want to creat a file that hold all your connection details like this:
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'user authentication');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DSN', 'mysql:host='. DB_HOST . ';dbname=' . DB_NAME);
?>
You then might want to create a class to do the connection to your database like:
<?php
class database{
public function databaseConnect(){
/*Creates a new instance of the PDO called $db.
* NOTE: the use of DSN, DB_USER and so on. These variable live in the dbsettings file.
*/
$db = new PDO(DSN,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
}
?>
Then you might want to create a class to register your user like:
<?php
//Include the database class file to allow access to properties and methods within that class.
require_once 'class.database.php';
//echo 'I am database class file now included in the users class file. <br />';
//This method will be user to check if the user enter the correct username password pair.
class users{
public function checkValidUser($username){
$userExists = false;
try {
$db = database::databaseConnect();
$stmt = $db->prepare('SELECT uname FROM table WHERE uname=:username');
$stmt->bindParam(':uname', $username, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() == 1){
$userExists = true;
}
$db = null;
} catch (PDOException $e) {
$userExists = false;
}
return $userExists;
}
public function addUser($firstname, $lastname, $username,$password){
$success = true;
//Connect to the database
try {
$db = database::databaseConnect();
//$db->databaseConnect();
$stmt = $db->prepare('INSERT INTO table (FirstName, LastName, Username, Password) VALUES (:firstname, :lastname, :username, :password)');
$stmt->bindParam(':firstname', $firstname, PDO::PARAM_STR);
$stmt->bindParam(':lastname', $lastname, PDO::PARAM_STR);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$success = $stmt->execute();
if ($success){
$success = true;
}
$db = null;
} catch (PDOException $e) {
//echo 'There was an error adding a new user. Please go back and try again. If this problem persits please contact the administrator.';
$success = false;
}
return $success;
}
?>
Hope that this helps.
enter link description here$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
You're not inserting the values into proper fields, it appears. You're inserting the $uname into L1 and md5($pword) into L2 but in the select query above, you have a different field name for username and I presume the same for password.
$SQL = "SELECT * FROM login WHERE USERNAME = $uname";
Most likely, your insert query should be something like:
$SQL = "INSERT INTO login (USERNAME, PASSWORD) VALUES ('{$uname}', MD5('{$pword}'))";
I added single quotes around the username and password since presumably they are strings. Also, I added curly braces around the variables to segregate what is SQL from what is PHP.
One last thing, I would check into doing this with PDO as Willem suggested

Convert php code with Mysql ext to PDO won't work

I have decided for security to convert my simple php with mysql code to PDO,since it will tighten my security.My old code:
$host = "localhost";
$user = "username";
$pass = "pass";
$database = "mydatabase";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$name=$_POST['name'];
$message=$_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$query="INSERT INTO table (date_time, name, message,ip) VALUES (NOW(),'$name','$message','$ip')";
If (mysql_query($query,$linkID)){
//Success
}else{
//Failure
}
My new code is:
$hostname = 'localhost';
$username = 'username';
$password = 'pass';
$dbname = 'mydatabase';
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
if($_POST['name'] && $_POST['message']) {
$name = $_POST['name'];
$message = $_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO table (date_time, name, message,ip)VALUES (NOW(), :name, :message,'$ip')";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':message', $message, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "OK";
}
}
It's very strange that when i point my browser to index.php?name=someName&message=someMessage my PDO code won't echo a single thing(even echo "ok" ) or an error so i can fugure out where is the problem.
I can confirm that no data is inserted to the database.
I've even added try catch but nothing changed. My php is supporting PDO and the simple Mysql code is working.
Any ideas? Thanks
In your case,
if($_POST['name'] && $_POST['message']) {
Should be:
if($_GET['name'] && $_GET['message']) {

Categories