I'm having a problem with the following PHP script. Specifically, the part that creates the user_id. This is part of a larger registration.php file that works fine without the section that creates the user_id.
As you can see, it's a while loop that uses a variable, $useridexits, to control the loop. It's set to true by default, so the loop runs. A random number is generated and then checked against the database. If a result is returned, the $useridexists variable is set to true and the loop continues. If no results are returned, $useridexists is set to false, so the loops stops. The number generated is then set to $userid and is then added to the database in the following section.
Here's the code:
//This section creates a new userid for each user.
//This varible is used by the while loop and is set to true by default.
$useridexists = true;
//While loop to create userid and check the database to see if the userid
//already exists. If it does, the while loop keeps going until a unique
//user id is created.
while($useridexists){
// Function to create random user id number.
function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(0, 9);
}
return $result;
}
// user id value created from randomNumber function.
$number = randomNumber(1);
//query the database to see if the user id already exists
$query = "SELECT * FROM users WHERE user_id = :number";
$query_params = array(':number' => '$number');
try {
// These two statements run the query against the database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row){
$useridexists = true;
}else{
$useridexists = false;
}
}
$userid = $number;
// This section adds the values to the database:
$query = "INSERT INTO users (username, password, email, firstname, lastname, user_id) VALUES ( :user, :pass, :email, :firstname, :lastname, :uid)";
//update tokens with the actual data:
$query_params = array(
':user' => $_POST['username'],
':pass' => $_POST['password'],
':email' => $_POST['email'],
':firstname' => $_POST['firstName'],
':lastname' => $_POST['lastName'],
':uid' => $userid
);
//run the query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Username Successfully Added! Please log in.";
echo json_encode($response);
$email= mysql_escape_string($_POST['email']);
$username = mysql_escape_string($_POST['username']);
If I comment out this section, everything works:
// user id value created from randomNumber function.
$number = randomNumber(1);
//query the database to see if the user id already exists
$query = "SELECT * FROM users WHERE user_id = :number";
$query_params = array(
':number' => '$number'
);
try {
// These two statements run the query against the database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row){
$useridexists = true;
}else{
$useridexists = false;
}
If I don't comment that section out, I don't get any errors, but nothing gets added to the database.
Everything works except the part that checks the database to see if the user_id already exists and changes the $useridexists variable to false, which should escape the while loop. When I add that, nothing gets added to the database.
BTW: I'm using a 1 digit value for testing purposes, but I'll change it to $number = randomNumber(7); once the code actually works.
Related
A student of mine was saving her score for a learning game to a MySQL database but somehow a different person's name ended up being stored in her database row. How is this possible? Here is the PHP for the insert.
// Get Configuration file
require "configenzymatic.php";
// Connect to your server
$dbh = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
///////////////////////////////////////////////////////
// Status Checker
///////////////////////////////////////////////////////
if ($_GET["status"]) {
echo "online";
exit;
}
///////////////////////////////////////////////////////
// Upload new score
///////////////////////////////////////////////////////
//set POST data as data to be checked and updated
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$level1right = $_POST['level1right'];
$level1wrong = $_POST['level1wrong'];
$level2right = $_POST['level2right'];
$level2wrong = $_POST['level2wrong'];
$level3right = $_POST['level3right'];
$level3wrong = $_POST['level3wrong'];
$level4right = $_POST['level4right'];
$level4wrong = $_POST['level4wrong'];
// check for email and set hash variable
$stm = $dbh->prepare("SELECT * FROM $tname WHERE email=?");
$stm->bindValue(1, $email, PDO::PARAM_STR);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$hashes = array($row['hash']);
$hash = $row['hash'];
$id = $row['id'];
foreach ($hashes as $hash) {
// If hash matches password, then...
if (password_verify($password, $hash)) {
// Everything is cool -- Insert the data into the database (update)
$stmt = $dbh->prepare("
UPDATE $tname
SET firstname = :firstname
, lastname = :lastname
, hash = :hash
, level1right = :level1right
, level1wrong = :level1wrong
, level2right = :level2right
, level2wrong = :level2wrong
, level3right = :level3right
, level3wrong = :level3wrong
, level4right = :level4right
, level4wrong = :level4wrong
WHERE email = :email
AND id = :id");
$stmt->execute(array($firstname, $lastname, $hash, $level1right, $level1wrong, $level2right, $level2wrong, $level3right, $level3wrong, $level4right, $level4wrong, $email, $id));
$affected_rows = $stmt->rowCount();
// check if row inserted
/* Return number of rows that were updated */
$count = $stmt->rowCount();
echo "$count";
}
}
}
The student inputted her name but someone else's name got inserted. I am totally baffled by this. Does anyone have any idea how this could occur? The person whose name was inserted in place of my student's added data at 12:30:44 today and my student added her data at 13:44:15. How did this data get mixed?
I'm not certain why you had your update wrapped in multiple loops, but it's entirely possible that users with the same password hash could exist, and (I think) would explain the behaviour you're seeing.
You are, presumably, looking to update the single user with the email and password submitted in the form? I assume you also have constraints on your table to ensure that email addresses are unique. So, you're grabbing the single user that matches that email, and checking their password. If it matches, update the single record with the same database ID. No loops!
// get password hash
$stm = $dbh->prepare("SELECT id, hash FROM $tname WHERE email=?");
$stm->execute([$_POST["email"]]);
$row = $stm->fetch(PDO::FETCH_ASSOC);
$hash = $row['hash'];
$id = $row['id'];
if (!password_verify($_POST["password"], $hash)) {
// verification failed, do something to present an error to the user
die();
}
$stmt = $dbh->prepare(
"UPDATE $tname
SET firstname=:firstname, lastname=:lastname,
level1right=:level1right, level1wrong=:level1wrong,
level2right=:level2right, level2wrong=:level2wrong,
level3right=:level3right, level3wrong=:level3wrong,
level4right=:level4right, level4wrong=:level4wrong
WHERE id=:id"
);
$stmt->execute([
":firstname" => $_POST["firstname"],
":lastname" => $_POST["lastname"],
":level1right" => $_POST["level1right"],
":level1wrong" => $_POST["level1wrong"],
":level2right" => $_POST["level2right"],
":level2wrong" => $_POST["level2wrong"],
":level3right" => $_POST["level3right"],
":level3wrong" => $_POST["level3wrong"],
":level4right" => $_POST["level4right"],
":level4wrong" => $_POST["level4wrong"],
":id" => $id
]);
$count = $stmt->rowCount();
echo "$count";
Also note that using named parameters in PDO requires the use of an associative array. Not sure how your original code would update anything at all without that.
I have problem without any error in my code that update row ..
if(!isset($error)){
try {
$sql = "UPDATE `invoice` SET `client`='".$client."', `company`='".$company."' , `clientemail`='".$clientemail."' , `mobailclient`='".$mobailclient."' , `startdate`='".$startdate."' , `enddate`='".$enddate."' WHERE `id` ='".$id."'";
$count = $db->exec($sql);
//redirect to invoice page
header('Location: invoice.php');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
This is my code , i try to get variable $sql and go to mysql phpmyadmin and its work good ,, but in file not work and i dont get any error
==== Update ====
i try this and not work
try {
$sql = 'UPDATE invoice SET client = :client, company = :company, clientemail = :clientemail, mobailclient = :mobailclient, startdate = :startdate, enddate = :enddate WHERE id = :id';
$statement = $db->prepare($sql);
$statement->bindParam(":client", $client);
$statement->bindParam(":company", $company);
$statement->bindParam(":clientemail", $clientemail);
$statement->bindParam(":mobailclient", $mobailclient);
$statement->bindParam(":startdate", $startdate);
$statement->bindParam(":enddate", $enddate);
$statement->bindParam(":id", intval($_GET['id']) );
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "<script>alert('".$statement->rowCount()."')</script>";
}
else
{
echo "<script>alert('No record updated')</script>";
}
Your query is opened for SQL Injection. You should use parameterized query which provide a kind of protection against SQL injection but will not provide 100% of protection. Kindly visit this Post for more details.
Try the following code by replacing table and column names.
$client = "my name";
$company = "my-company";
$id= 2;//make sure your table has a record with that specific id
$sql = 'UPDATE invoice SET client = :client, company = :company WHERE id = :id'; // here i am updating only two columns
//You can add more column that you want to upate like ColumnName = :ParameterIdentifier
//Where ParameterIdentifier Is the name of parameter used in bindParam as in my example company
$statement = $db->prepare($sql);
$statement->bindParam("client", $client); //Binding parameter for client
$statement->bindParam("company", $company); //Binding parameter for company
$statement->bindParam("id", $id);
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "Record updated successfully";
}
else
{
echo "No record updated";
}
I have a variable $success set to $success = "Successfully Created" but the var $success has no value inside HTML.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
if (isset($_POST['okbutton'])) {
if (isset($_POST['clientuser'], $_POST['clientpass'])) {
$clientuser = $_POST['clientuser'];
$clientpass = $_POST['clientpass'];
$_SESSION['cuser'] = $clientuser;
$_SESSION['cpass'] = $clientpass;
header('Location: trialaccount.php');
die();
}
}
}
try {
if (isset($_SESSION['cuser'])) {
$stmt = $conn->prepare("SELECT user_id FROM user WHERE user_id=:username");
$stmt->bindParam(':username', $_SESSION['cuser']);
$stmt->execute();
$checkdup = $stmt->rowCount();
if ($checkdup == 0) {
$stmt = $conn->prepare("INSERT INTO user (user_id, user_pass, user_online, user_enable, user_start_date, user_end_date, reseller, type) VALUES (:clientuser, :clientpass,0, 1, now(), now() + interval 4 hour, :panelUSER, 'Trial')");
$stmt->bindParam(':clientuser', $_SESSION['cuser']);
$stmt->bindParam(':clientpass', $_SESSION['cpass']);
$stmt->bindParam(':panelUSER', $username);
$stmt->execute();
$success = "Trial Account Created Successfully!";
} else {
$error = "Username '" . $_SESSION['cuser'] . "' is already taken. Try to input unique username." ;
}
}
} catch (PDOException $e) {
echo "Error: Database Error";
}
Inside my HTML, I use echo!
<?php if(isset($success)){ echo $success; } ?>
var $success is returning the value on my personal smartphone,
but no value on other devices.
I dont know what is happening?
Can I use Session instead? ty
Your method does not get the total row count. Therefore, it doesn't go through (if($checkdup == 0)) to set the value for $success. You can try the code below.
Replace:
$stmt = $conn->prepare("SELECT user_id FROM user WHERE user_id=:username");
$stmt->bindParam(':username', $_SESSION['cuser']);
$stmt->execute();
$checkdup = $stmt->rowCount();
With:
$stmt = $conn->prepare("SELECT COUNT(*) FROM user WHERE user_id=:username");
$stmt->bindParam(':username', $_SESSION['cuser']);
$stmt->execute();
$checkdup = $stmt->fetchColumn();
the fragment code
if (!empty($_POST)) {
$query = "SELECT userid FROM user WHERE email = :email";
$query_params = array(':email' => $_POST['email']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error Get User ID!";
die(json_encode($response));
}
if ( false !== ($user = $stmt->fetch()))
{
$userid = $user['userid'];
}
else {
$response["success"] = 0;
$response["message"] = "Why you come here!";
die(json_encode($response));
}
I want to ask is that after that $row = $stmt->fetchAll(); How should I write the code of assigning the userid into $userid And php doesn't save the row result into a variable.
fetchAll() returns an array. so $row['userid'] will not be set. $row[0]['userid'] will.
Betterh would be to use:
if ( false !== ($user = $stmt->fetch()) )
{
$userid = $user['userid'];
} else
{
//user not found
}
What this code does, it tries to fetch a row fromt the statement. IF no row was found ->fetch() returns a boolean false. As long as it doesn't return false, we have a row from the statement that is available in the $user var now :)
$userID = isset($row['userid']);
Simply checks if $row['userid'] is set, i.e. it's a bool value.
Simply checking whether the array is empty or not will be sufficient for you to fetch the value straight away:
if(!empty($row))
{
$userId = $row['userid'];
}
You need to make your question become more precise, if this isn't what you're asking for.
I am getting "invalid parameter number:parameter undefined" exception when attempting an insert query to mysql database.
I am returning the result to my Android app as json.
if (!empty($_POST))
{
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:fromm,:too,:ccode,:stud,:rmk ) ";
$query_params = array(
':dat' => $_POST['datee'],
':from'=>$_POST['fromm'],
':to'=>$_POST['too'],
':ccode'=>$_POST['course'],
':stud'=>$_POST['sname'],
':rmk'=>$_POST['remark'],
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
$response["date"] = $_POST['datee'];
$response["from"] = $_POST['fromm'];
$response["to"] = $_POST['too'];
$response["ccode"] = $_POST['course'];
$response["stud"] = $_POST['sname'];
$response["remark"] = $_POST['remark'];
die(json_encode($response));
}
}
you lack a m in
':from'=>$_POST['fromm'],
should be
':fromm'=>$_POST['fromm'],
you must be careful when using named parameter, I myself am very prone to making such errors
that's why I more easily use the ? placeholder, this way in your exemple:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (?,?,?,?,?,?) ";
$query_params = array(
$_POST['datee'],
$_POST['fromm'],
$_POST['too'],
$_POST['course'],
$_POST['sname'],
$_POST['remark'],
);
then:
$result = $stmt->execute($query_params);
you must be sure that the params are in good order (same as in query)
In your query, you're misspelling from:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:fromm,:too,:ccode,:stud,:rmk ) ";
Replace it with:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:from,:too,:ccode,:stud,:rmk ) ";