Data won't save into MySQL database - php

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) {
}

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

Cannot Insert ID into MySQL Table

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()

PHP Error: call to a member function bind_param() on a non-object

I have a php script which should connect to a database, check whether a row with the given field exists and, if it exists, update another field of the same row. However, the UPDATE query seems to fail, and I can't see why. I tried to google the problem but couldn't find a working solution. I tried to echo($mysqli->error) but it gave me an empty string.
Here's the code:
<?php
session_start();
include "../config.php";
if(isset($_GET['actionForgot']) && !empty($_GET['restore'])) {
$piva=trim($_GET['restore']);
$mysqli = new mysqlc();
$stmt = $mysqli->prepare("SELECT username,email FROM login WHERE piva = ?");
$stmt->bind_param("s", $piva);
if (!$stmt->execute()) {
trigger_error('The query execution failed; MySQL said ('.$stmt->errno.') '.$stmt->error, E_USER_ERROR);
}
$stmt->bind_result($username, $email);
if($stmt->fetch()) {
$password = generatePassword(10);
$crypPass = MD5($password);
$stmt = $mysqli->prepare("UPDATE login SET password = ? WHERE piva = ?"); //Here's the error!
if(!$stmt->bind_param("ss",$crypPass,$piva)){
echo "fail";
} else if (!$stmt->execute()) {
trigger_error('The query execution failed; MySQL said ('.$stmt->errno.') '.$stmt->error, E_USER_ERROR);
echo "fail";
} else {
sendEmailRestore($username, $password, $email);
echo $email;
}
} else {
echo "nexists";
}
$stmt->close();
}else{
echo "false";
}
?>
P.S. I'm sure the problem is not in config.php because other similar php scripts work just fine.
EDIT: Could it have something to do with the fact I'm using the same variable $stmt for two queries?
I've found the problem! It had something to do with $mysqli being used for two different queries. I have no idea why this should give problems of any kind, but I changed the code to this:
<?php
session_start();
include "../config.php";
if(isset($_GET['actionForgot']) && !empty($_GET['restore'])) {
$piva=trim($_GET['restore']);
$mysqli = new mysqlc();
$stmt = $mysqli->prepare("SELECT username,email FROM login WHERE piva = ?");
$stmt->bind_param("s", $piva);
if (!$stmt->execute()) {
trigger_error('The query execution failed; MySQL said ('.$stmt->errno.') '.$stmt->error, E_USER_ERROR);
}
$stmt->bind_result($username, $email);
if($stmt->fetch()) {
$password = generatePassword(10);
$crypPass = MD5($password);
$mysqli2 = new mysqlc(); //NOTICE THIS LINE
$stmt = $mysqli2->prepare("UPDATE login SET password = ? WHERE piva = ?"); //AND THIS
if(!$stmt->bind_param("ss",$crypPass,$piva)){
echo "fail";
} else if (!$stmt->execute()) {
trigger_error('The query execution failed; MySQL said ('.$stmt->errno.') '.$stmt->error, E_USER_ERROR);
echo "fail";
} else {
sendEmailRestore($username, $password, $email);
echo $email;
}
} else {
echo "nexists";
}
$stmt->close();
}else{
echo "false";
}
?>
and it works just fine.
I'd still like to know why I was doing it wrong, though...

I need to check my db to see if a username or email is already in use

I've started a thread or two so far but nothing has got resolved. I'm not able to use the mysqlnd because i'm using a shared hosting account with godaddy.
All i need to do is check if my email address and/or username is in use; if they are in use throw and error, if not.. all is well.
Here is my code:
$input_errors = array();
if (!empty($_POST['username'])) {
$user = $_POST['username'];
} else {
$input_errors['username'] = "Must fill out username";
}
$email = filter_input(INPUT_POST, 'usermail', FILTER_VALIDATE_EMAIL);
if (false === $email) {
$input_errors['usermail'] = "Not a valid email address";
}
if(count($input_errors) > 0) {
print_r($input_errors); die();
}
$sql = "SELECT COUNT(*) as amount FROM people WHERE username = ?
OR email = ?";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("ss", $user, $email);
$stmt->execute();
$results = $stmt->get_result();
$data = mysqli_fetch_assoc($results);
if ($data['amount'] > 0)
{
print "User already exists";
}
}
else {
$stmt = $mysqli->stmt_init();
if (!$stmt) {
echo "Init failed";
} else {
$cmd = "INSERT INTO people (username, email, sign_up_date) VALUES (?, ?, NOW() )";
if ($stmt->prepare($cmd)) {
$stmt->bind_param('ss', $user, $email );
$stmt->execute();
echo $stmt->affected_rows . " row(s) inserted";
$stmt->close();
} else {
echo "Prepare failed";
}
mysqli_close($mysqli);
}
}
bind_result() does not work.
Change your sql statement to the following:
$sql = "SELECT COUNT(*) as amount FROM people WHERE username = '".mysqli_real_escape_string($_POST['username'])."' OR email = '".mysqli_real_escape_string($email)."'";

Categories