Cannot Insert ID into MySQL Table - php

What I am trying to do is allow the user to create a table and I want to add the userID of the user into the first line of the table so I can access it later. However, when trying to insert the ID, I keep getting an error message saying I cannot add it. Here is my code:
<?php
# $db = new mysqli('localhost', 'root', 'secret', 'Pokemon'); //open db
if ($db->connect_error) {
echo 'ERROR: Could not connect to database, error is '. $db->connect_error;
exit;
} else {
echo 'Successful connection established<br />';
}
$deckName = stripslashes($_POST['deckName']); //sql sanitize for each input.
$deckName = $db->real_escape_string($deckName);
$checkQuery = "SELECT userID FROM userInfo WHERE userEmail = ?";
$checkStmt = $db->prepare($checkQuery);
$checkStmt->bind_param("s", $SESSION['userEmail']);
$checkStmt->execute();
if ( ($checkStmt->errno <> 0) || ($checkStmt->num_rows > 0) )
{
$checkStmt->close();
echo 'ERROR: Something is wrong';
exit;
}
$res = $checkStmt->get_result();
$row = $res->fetch_assoc();
$checkStmt->close();
$query = "CREATE TABLE `".$deckName."` (userID int(3), pokeID int(3), pokeName varchar(20), quantity int(1),
PRIMARY KEY (userID) )";
$stmt = $db->prepare($query);
$stmt->execute();
if ($stmt->errno <> 0)
{
$stmt->close();
$db->close();
echo 'ERROR: Could not create table';
exit;
}
$stmt->close();
$query = "INSERT INTO `".$deckName."` (userID) VALUES(?)";
$stmt = $db->prepare($query);
$stmt->bind_param("i", $row['userID']);
$stmt->execute();
if ($stmt->errno <> 0)
{
$stmt->close();
$db->close();
echo 'ERROR: Could not add to database';
exit;
}
$stmt->close();
$db->close();
header("Location: viewCards.php");
?>
It creates the table, but will not insert the userID. I have looked at this trying to find what the issue is, and I would like a fresh set of eyes to look at it if possible.

Use $_SESSION['userEmail'] instead of $SESSION['userEmail'] and there is no session_start()

Related

sql database query issues

For the last week a have been stuck on one part of my website, the register script. I have got it to create new users in the database which is fine however it when someone enters a duplicate user name that I have issues with.
The database is set up to not allow duplicated so if you try you get a lovely error printed on the web page and although functional doesn't look great.,
what I have been trying to do and have looked at many many examples of how to do it but it never works for me. I Would love some help and please don't be a jerk and say there are answers/ it's a duplicate because I have tried. If you don't want to help then move on :).
here is the code:
<?php
include 'pdo_connect.php';
if(!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)'; //if duplicate exists returns a duplicate error.
$params = array($uname, $upassword);
$results = dataQuery($query, $params);
}
?>
UPDATE 1
<?php
include 'pdo_connect.php';
if(!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try
{
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)'; //if duplicate exists returns a duplicate error.
}
catch (Exception $e)
{
echo "username taken";
}
$params = array($uname, $upassword);
$results = dataQuery($query, $params);
}
?>
tried the try catch as suggested but same issue the server error is displayed on screen i think its because it still executes and it doesnt "crash".
here is the error i get: (when i try to register as admin which already exists)
error
UPDATE 2
same result :(
<?php
include 'pdo_connect.php';
if(!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try
{
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)'; //if duplicate exists returns a duplicate error.
$params = array($uname, $upassword);
$results = dataQuery($query, $params);
}
catch (Exception $e)
{
echo "username taken";
}
}
?>
UPDATE 2
<?php
include 'pdo_connect.php';
if(!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try
{
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)'; //if duplicate exists returns a duplicate error.
$params = array($uname, $upassword);
$results = dataQuery($query, $params);
}
catch (PDOException $e)
{
echo "username taken";
}
}
?>
still does the same :(
UPDATE 3
<?php
include 'pdo_connect.php';
if (!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try {
$query = $ConString->prepare("SELECT * from users where uname = $uname ");
$query->execute([$uname]);
$results = $query->fetchall();
if (count($results) > 0) {
echo "username taken";
} else {
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)';
$params = array($uname,$upassword);
$results = dataQuery($query, $params);
}
}
catch (Exception $e) {
echo "username taken";
}
}
?>
these 2 errors:
enter image description here
pdo_connect code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', 'pass');
function dataQuery($query, $params) {
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
} else {
return $queryResults->rowCount();
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step tp close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg;
}
}
?>
Before insert you will need to run a select statement, select id or what ever from you users table that matches the username supplied on register, if the select statement return results then the username is taken otherwise run the insert.
<?php
include 'pdo_connect.php';
if (!empty($_POST)) {
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
//here i want to search for the duplicate username and if none then carry on ar if match echo "alredy taken"
try {
$query = $ConString->prepare("SELECT * from users where uname = ? ");
$query->execute([$uname]);
$results = $query->fetchall();
if (count($results) > 0) {
echo "username taken";
} else {
$query = 'INSERT INTO `users` ( `uname`, `password`) VALUES (?,?)';
$params = array($uname,$upassword);
$results = dataQuery($query, $params);
}
}
catch (Exception $e) {
echo "username taken";
}
}
?>
You will need to modify my code to match with your methods, because as it stand you have done your own sql functions.
found it!
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', 'Unhackable');
function dataQuery($query, $params) {
// what kind of query is this?
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
} else {
return $queryResults->rowCount();
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step tp close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo "too slow, username already taken";
//echo $errorMsg;
}
}
?>
commented out echoing the error message and echoing a customised message, i know its not great but it does the job.

PDO statement fetchall not returning required result

I have read all other PDO topic in stackoverflow and tried all the stuff, but still its not working, i don't know whats wrong
on the Edit/Change Password page
I am using this code
ob_start();
session_start();
require_once './../account/config.php';
$id = $_SESSION['id'];
if (isset($_POST["submit"])) {
$opwd = mysql_real_escape_string($_POST['oldpwd']);
$npass = mysql_real_escape_string($_POST['newpwd']);
$anpass = mysql_real_escape_string($_POST['renewpwd']);
$sql = "SELECT COUNT(*) AS count from users where id = :id";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":id", $id);
$stmt->execute();
$result = $stmt->fetchAll();
here, $result[0]["password"] is not fetching the result from table users and column password
I even tried $result["password"] but not working,
in other pages same method is working very perfect but here its not fetching result
So, even user puts correct old password, its returning Current Password is Incorrect
if($result[0]["password"] !== $opwd) {
$msg = "Current Password is Incorrect";
}
elseif($npwd !== $rnpwd) {
$msg = "New Passwords did not match.";
}
elseif (($result[0]["password"] === $opwd) && $npwd === $rnpwd) {
$sql = "UPDATE `users` SET (`password`, `retype`) = (:npswd , :anpwd) WHERE `id` = :id";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":npswd", $npass);
$stmt->bindValue(":anpwd", $anpass);
$stmt->bindValue(":id", $id);
$stmt->execute();
$msg = "Your Password is changed successfully";
$msgType = "success";
}
else {
$msg = "Error Occured. Please Contact us if you have some issue.";
}
}
catch (Exception $ex) {
echo $ex->getMessage();
}
}
Please guide me what am i missing here

PHP Select Statement - Errors

I am student and I work on a noteapp. I made 2 methods in my DB-Handler within my Login-Mask for users to Login or Register.
<?php
class DBHandler
{
var $hostname;
var $user;
var $pw;
var $db;
var $connection;
function connectToDB($hostname,$user,$pw,$db){
$this->hostname = $hostname;
$this->user = $user;
$this->pw = $pw;
$this->db = $db;
$this->connection = new mysqli($this->hostname,$this->user,$this->pw,$this->db);
if ($this->connection->connect_error) {
die('Failed to connect' . $this->connection->connect_error);
}
$this->ensureNotesTable();
$this->ensureUsersTable();
}
function ensureUsersTable(){
assert($this->connection);
$queryCreate = "CREATE TABLE IF NOT EXISTS users(id INT(5) PRIMARY KEY AUTO_INCREMENT, username VARCHAR(100) NOT NULL, password VARCHAR(100) NOT NULL)";
$this->connection->query($queryCreate);
}
function ensureNotesTable(){
assert($this->connection);
$queryCreate = "CREATE TABLE IF NOT EXISTS notesnew(id INT(5) PRIMARY KEY AUTO_INCREMENT, title VARCHAR(100) NOT NULL, content VARCHAR(100) NOT NULL, userid INT(5) NOT NULL)";
$this->connection->query($queryCreate);
}
function ensureUsername($username,$password){
assert($this->connection);
echo $username;
$query = "SELECT * FROM users WHERE username = (?)";
$statement = $this->connection->prepare($query);
$statement->bind_param('s',$username);
$results = $statement->execute();
echo $this->connection->errno.'-'.$this->connection->error;
if(mysqli_num_rows($results) >= 1){
echo $this->connection->errno.'-'.$this->connection->error;
echo "Username already exists";
} echo "Username is free!";
$this->addUser($username,$password);
}
function addUser($username,$password){
assert($this->connection);
$queryCreate = "INSERT INTO users(username, password) VALUES (?,?)";
$statement = $this->connection->prepare($queryCreate);
$statement->bind_param('ss', $username, $password);
return $statement->execute();
echo "You have been registered!";
}
function getUserId($username){
assert($this->connection);
$queryCreate = "SELECT id FROM users WHERE username = $username";
$row = $this->connection->query($queryCreate);
$userid = mysqli_fetch_row($row);
return $userid[0];
}
function addNote($title, $text, $userID){
assert($this->connection);
$queryCreate = "INSERT INTO notesnew(title, content, userid) VALUES (?,?,?)";
$statement = $this->connection->prepare($queryCreate);
$statement->bind_param('ssi', $title,$text,$userID);
return $statement->execute();
}
}
Within ensureUsername I wanna check if the username which is used for the registration has already been picked by another user.
Within addUser I wanna do the Insert statement, to add the user to the database, if the username is free.
I tried about 3 hours today but it always gives me errors. I hate it! Maybe im just too stupid for it.
At the moment its saying:
Warning: mysqli::query() expects parameter 1 to be string, object
given in
C:\Users\ReallySorry\PhpstormProjects\NoteAppMongo\DBHandler.php on
line 57 0- Warning: mysqli_num_rows() expects parameter 1 to be
mysqli_result, null given in
C:\Users\ReallySorry\PhpstormProjects\NoteAppMongo\DBHandler.php on
line 60
Does anybody know what im doing wrong?
Thanks ...
The depressed student
Your problem is here:
$statement = $this->connection->prepare($query);
$statement->bind_param('s',$username);
$results = $this->connection->query($statement)
When you're using prepared statements (well done – so many people here don't!) you need to use the execute() method on your statement rather than calling query() on your connection. So, this should work:
$results = $statement->execute()
Some minor changes to the original -
function ensureUsername( $username=false, $password=false ){
$rv=false;/* Return Value */
if( !assert( $this->connection ) or !$username or !$password ) return $rv;
$db=$this->connection;/* shorthand for laziness */
$sql = "select `username` from `users` where `username`=?;";
$stmt = $db->prepare( $sql );
$stmt->bind_param('s', $username );
$res = $stmt->execute();
$stmt->store_result();
if( $res ){
$rv=( $stmt->num_rows > 0 ) ? 'Sorry, that Username already exists!' : $this->addUser( $username, $password );
}
$stmt->free_result();
$stmt->close();
echo $rv;
}
function addUser( $username, $password ){
$db=$this->connection;/* No need for assert now, if the script gets here the db conn must exist */
$sql = "insert into `users` (`username`, `password`) values (?,?);";
$stmt = $db->prepare( $sql );
$stmt->bind_param('ss', $username, $password );
return $stmt->execute() ? 'You have been registered!' : 'Sorry, there was a problem';
}

How to check if username already exist using PDO?

am currently working on a project and i have the script for insertion.my table is called survey and the fields are id,username,password,province. the username is set to unique key. the insertion process is working fine without any duplicate entry but when i try to insert a duplicate entry at always shows me this error
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'bluff' for key 'username'
I know what this error mean, my problem is that how can i can if username already exist or not i want an alert message to pop up..
here is my code
class.user.php
public function username($username){
$stmt = $this->db->prepare("SELECT count(*) FROM tish_images WHERE username = :username");
$stmt->execute(array($username));
$number_of_rows = $result->fetchColumn();
if($number_of_rows >= 1) {
echo 'username does exist'; // or return so you get the value
} else {
echo 'username does not exist'; //also return?
}
}
public function create($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO tish_images(username,password,province) VALUES(:username, :password, :province)");
$stmt->bindparam(":username",$username);
$stmt->bindparam(":password",$password);
$stmt->bindparam(":province",$province);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
index.php
<?php
include_once 'DB.php';
$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';
$province = isset($_GET['province']) ? $_GET['province'] : '';
if(isset($_FILES['files'])){
$id = $_GET['id'];
$username = $_POST['username'];
$password = $_POST['password'];
$province = $_POST['province'];
if($crud->upload($id,$FILE_NAME,$FILE_SIZE,$FILE_TYPE,$username,$password,$province))
{
echo "<script type='text/javascript'>alert('Successfully Updated!');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Updating Failed!');</script>";
}
}
if(isset($_GET['id']))
{
$id = $_GET['id'];
extract($crud->getID($id));
}
You should run a SELECT before performing the query to see if the username exists.
// count how many rows with user name exists
$checkUserStmt = $this->db->prepare("
SELECT count(1)
FROM tish_images
WHERE username = :username
");
$checkUserStmt->execute(array(":username" => $username));
// fetch the count result
if ($checkUserStmt->fetchColumn() > 0) {
// username already exists
} else {
// username available
} //if
A few notes.
You still might get a duplicate entry error if you have two users trying to register the same username at close interval.
You should hash the password see Secure hash and salt for PHP passwords
To check if username or email already exists. I added email in there as this is also useful. You don't want two users with the same email address. Well I wouldn't see the need for it. :)
Complete code added and up to date.
$query_check_user_name = $this->db_connection->prepare('SELECT user_name, user_email FROM users WHERE user_name=:user_name OR user_email=:user_email');
$query_check_user_name->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_check_user_name->bindValue(':user_email', $user_email, PDO::PARAM_STR);
$query_check_user_name->execute();
$result = $query_check_user_name->fetchAll();
if ($result > 0) {
echo "Someone with that username/email already exists.";
} else {
//Continue with proccessing the form
}
OR
$query_check_user_name = $this->db_connection->prepare('SELECT user_name, user_email FROM users WHERE user_name=:user_name OR user_email=:user_email');
$query_check_user_name->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_check_user_name->bindValue(':user_email', $user_email, PDO::PARAM_STR);
$query_check_user_name->execute();
$result = $query_check_user_name->fetchAll();
if ($result > 0) {
return true;
} else {
return false;
}

Data won't save into MySQL database

I can connect to my DB, but nothing saves into it. In the section where it is suppose to save it into the DB, it echos "New User" and the $sql line with the data that should be saved. Can anyone see why this shouldn't be saving my data?
$dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
//$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if($dbh){
echo "Connected successfully";
}else{
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_SESSION['steamid'])) {
include ('steamauth/userInfo.php');
if (!empty($steamprofile['steamid'])) {
$stmt = $dbh->prepare("SELECT count(*) from user WHERE steam_id = :steam_id");
$stmt->bindValue(':steam_id', $steamprofile['steamid']);
$stmt->execute();
$count = $stmt->fetchColumn();
}
//Row will return false if there was no value
if ($count == 0) {
//insert new data
echo "New user";
$sql = "INSERT INTO user (display_name, user_url, steam_id, profile_image)
VALUES ('$steamprofile[personaname]', '$steamprofile[profileurl]', $steamprofile[steamid], '$steamprofile[avatar]')";
echo($sql);
// die();
} else {
//User exist
echo "User exists";
}
}else{
echo "no user signed in";
}
Table Schema: http://gyazo.com/ef9badc3ae72b73557ed80efe2413ea3
There it goes.
if ($count == 0) {
echo "New user";
$sql = "INSERT INTO user (display_name, user_url, steam_id, profile_image)
VALUES ('$steamprofile[personaname]', '$steamprofile[profileurl]', $steamprofile[steamid], '$steamprofile[avatar]')";
$dbh->query($sql); // You missed that line of code.
echo($sql); // This will only echo out your query, not the result.
} else {
//User exist
echo "User exists";
}
You didn't execute the INSERT sql statement. You can use the following statement after $sql:
$result = mysqli_query($sql);
Make sure you read the $result and do appropriate things, e.g.:
if($result === true) {
// success
} else {
// failed
}
As in your codes the $sql has not been executed, it will print only the variable. Execute it first.
Execute insert query. Try this snippet in your code.
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
} catch (PDOException $ex) {
}

Categories