So how do I get single values in each seperate $stmt->bindColumn(3, $username);? What I am trying to do is set values in text fields in a form: name, username, and so on.
I pull the sandbox data from a table with:
SELECT * FROM users WHERE namn = 'sven' AND lösenord = ' ' ORDER BY datetime LIMIT 1
try {
$sql = "SELECT namn FROM user_view";
$stmt = $dbh->getInstance()->prepare($sql);
$stmt->execute();
$results=$stmt->fetchAll();
$stmt->bindColumn(1, $email);
$stmt->bindColumn(2, $name);
$stmt->bindColumn(3, $username);
$stmt->bindColumn(4, $password);
}
catch(PDOException $e) {
echo ($e->getMessage());
}
<input id="text" name="text" value="<?php echo $username ?>" type="text" class="form-control">
Assuming that your table structure is something like...
user_view
> id
> name
> email
> username
> password
And that you want to loop though all users (as you don't have a WHERE clause)...
$pdo = $dbh->getInstance(); // Get PDO instance
$sql = "
SELECT *
FROM user_view
WHERE name = ?
";
$query = $pdo->prepare($sql); // Prepare query
$query->execute([$_POST["name"]]); // Execute query and bind value to place holder (I've assumed it's coming from POST user input)
// Loop through result set
$user = $stmt->fetchObject();
// Access the columns like
# echo $user->name;
# echo $user->email;
# echo $user->username;
# echo $user->password;
// For example
echo "<input id='user_name' name='user_name' value='{$user->name}' type='text' class='form-control'>";
N.B.
You shouldn't be storing passwords in plain text - it's a major security risk.
You can use the following to hash a password on registration...
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);
And to verify...
if( password_verify($_POST["password"], $db_password) ){
// Success, do something...
}
Related
im fairly new to PHP/MySQL but i found no answers in the net for my problem:
I've got a form with 4 textfields
<form method="post" action="updateuserdatatest.php">
<input type="text" value="Hans" name="username">
<input type="text" value="1234" name="password">
<input type="text" value="desired cell" name="desiredcell">
<input type="text" value="desired value" name="desiredvalue">
<input type="submit">
</form>
I want to update the named "desired cell" with the "desired value".
So i have to type in the username, his password, a column name (i.e. "streetname","postcode" or "city") and after that the stringvalue which shall be submitted to the database.
I use this code:
$pdo = new PDO(everything is OK here! - Checked this out many times);
$sql = 'UPDATE user SET :desiredcell = :desiredvalue WHERE username = :username AND password = :password';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":desiredcell", $_POST['desiredcell'], PDO::PARAM_STR);
$stmt->bindValue(":desiredvalue", $_POST['desiredvalue'], PDO::PARAM_STR);
$stmt->bindValue(":username", $_POST['username'], PDO::PARAM_STR);
$stmt->bindValue(":password", $_POST['password'], PDO::PARAM_STR);
$stmt->execute();
if ($stmt->errno) { echo "FAILURE!!! " . $stmt->error;
}
else echo "Updated {$stmt->affected_rows} rows";
$response = array();
$response['success'] = true;
echo json_encode($response);
?>
This does not work!
But when i change the sql query to a specific columnname like 'UPDATE user SET streetname = :desiredvalue WHERE username = :username AND password = :password';
then it works! why?
i want to type in the cellname which has to be updated manually!
i tried this with mysqli queries before like UPDATE user SET ?=? WHERE password=? AND username=? same problem there
What am i doing wrong?
Thanks in advance.
EDIT:
seems that i cant post images in a comment, so i make another answer:
this is my dummy table,
when i try to insert the column variable like your example nothing happens inside the table, but i still get the success response.
$column = in_array($_POST['desiredcell'], ['streetname', 'postcode','state']) ? $_POST['desiredcell'] : 'streetname';
$sql = 'UPDATE user SET $column = :desiredvalue WHERE username = :username AND password = :password';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":desiredvalue", $_POST['desiredvalue'], PDO::PARAM_STR);
$stmt->bindValue(":username", $_POST['username'], PDO::PARAM_STR);
$stmt->bindValue(":password", $_POST['password'], PDO::PARAM_STR);
$stmt->execute();
any tips? =/
EDIT:
Found the solution:
$sql = 'UPDATE user SET '.$column.' = :desiredvalue WHERE username = :username AND password = :password';
thank you guys.
As it mentioned it the comments, you can't bind column names. You should use a variable and make sure the input is a real column name (for security reasons)
Example:
<?php
$column = in_array($_POST['desiredcell'], ["column1", "column2"]) ? $_POST['desiredcell'] : "column1";
$sql = "UPDATE user SET $column = :desiredvalue WHERE username = :username AND password = :password'";
Also bear in mind that storing a plain text passwords in a database is a real bad idea. Check password_hash function.
I am trying to see if a code stored in my database is the same as the one the user provides, currently
user would provide the vCode via POST but i have it set to what it actually is for testing purposes
$vCode = "69582";
Now i'm using a PDO query to get the vCode that's in the database.
$dsn1 = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};";
$conn1 = new PDO($dsn1, $this->user, $this->password);
$conn1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql1 = "SELECT * FROM `accinfo` WHERE Email = :email AND vCode = :vCode";
$stmt1 = $conn1->prepare($sql1);
$stmt1->bindParam(':email', $email, PDO::PARAM_STR);
$stmt1->bindParam(':vCode', $vCode, PDO::PARAM_STR);
$stmt1->execute();
if( $stmt1->rowCount() > 0 ) {
$result = $stmt1->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt1->fetchAll())) as $k=>$v) {
$actualVCode = $v;
}
Then i see if the vCode i got from the database ($actualVCode) is equal to the $vCode
if ( $actualVCode == $vCode ){
echo "match";
}
The value stored in my database is a string and is 69582, but whenever i compare them like i do above, the if statement never comes back as true. But when i echo both $vCode and $actualVCode, they both are 69582.
Instead of getting the result from the first query and checking the result with the vCode, i've modified the query to select the whole row only if the email AND the vCode matches
$sql1 = "SELECT * FROM `accinfo` WHERE Email = '$email' AND vCode = '$vCode'";
$stmt1 = $conn1->prepare($sql1);
$stmt1->execute();
if( $stmt1->rowCount() > 0 ) {
//found match
echo "found match";
}
I want to store a name in the mySQL database. When I click the submit button, PHP should check if the name already exists in the database. If yes then do not submit and print an error message:
Name already exists in database.
<?php
if ( !empty($_POST)) {
$name = $_POST['name'];
$valid = true;
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO people (name) values(?) ";
$q = $pdo->prepare($sql);
$q->execute(array($name));
}
}
?>
<form action="form.php" method="post">
<input name="name" type="text" value="<?php echo !empty($name)?$name:'';?>">
<button type="submit" >Submit</button>
</form>
Try following query to check if a value already exists in mySQL database?
$q = $pdo->prepare("SELECT name FROM people WHERE name = :name LIMIT 1");
$q->bindValue(':name', '$name');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row = $check['name'];
// Do Something If name Already Exist
} else {
// Do Something If name Doesn't Exist
}
you could declare the column as unique and check if the query executes or not, for example:
$query = $pdo->prepare("SELECT name FROM table WHERE name = :name");
$query->bindValue(':name', '$name');
if ($query->execute()){
//no duplicate
}
else {
//error, check the error code.
echo "$stmt->errorCode()";
}
$query-> execute will retun true on success and false other wise, and the database will return an error when the input is a duplicate in a unique coulmn.
I think Making the duplication check in the database is safer.
I am converting to PDO and I'm having a problem converting at the section where it checks to see if the username and email is taken or not.
below is the code:
<?php
session_start();
$host = "localhost";
$username = "root";
$password = "123";
$dbname = "test";
$conn = new PDO("mysql:host=$host;dbname=$dbname",$username,$password);
?>
<?php
if(isset($_POST['register'])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$usernamecheck = $conn->query("SELECT `id` FROM `user` WHERE username='$username'");
$emailcheck = $conn->query("SELECT `id` FROM `user` WHERE email='$email'");
if(mysql_num_rows($usernamecheck) > 0){
echo "That username is already taken";
}elseif(mysql_num_rows($emailcheck) > 0){
echo "That e-mail address is already in use";
}
?>
The errors I get are at the two following lines:
if(mysql_num_rows($usernamecheck) > 0){
}elseif(mysql_num_rows($emailcheck) > 0){
Thanks in Advance.
You're using mysql_num_rows() for a PDO query. You can't mix these APIs.
You're also interpolating $_POST variables directly into your SQL, which is a no-no for security. The benefit of using PDO is that you can easily use SQL query parameters instead, which is much easier and more secure.
Here's how I'd code this task:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT COUNT(*) AS count FROM `user` WHERE username=?");
$stmt->execute(array($username));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$username_count = $row["count"];
}
if ($username_count > 0) {
echo "That username is already taken";
}
$stmt = $conn->prepare("SELECT COUNT(*) AS count FROM `user` WHERE email=?");
$stmt->execute(array($email));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$email_count = $row["count"];
}
if ($email_count > 0) {
echo "That email address is already in use";
}
Also keep in mind that even if you check first, you should assume that someday two people may be trying to create the same username simultaneously, and if the code for their respective requests executes in just the wrong sequence, they could both be told the username does not exist, go ahead and INSERT it. So you should define a UNIQUE KEY on the columns that must be unique. Only the first one to INSERT will succeed, the other will get an error. So you must check for errors.
First of all, the entire task is rather pointless. Making a username unique makes no sense. Given email is used to identify a user, the username - or, rather - display name could be anything and allow duplicates, just like it is done right here, on Stack Overflow.
But if you want the username to be unique, obviously it can be done in one query, without any num rows functionality which being essentially useless
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT username, email AS count FROM `user` WHERE username=? OR email=?";
$stmt = $conn->prepare($sql);
$stmt->execute([$username, $email]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($row['username'] === $username) {
$errors[] = "Username is taken";
}
if ($row['email'] === $email) {
$errors[] = "Email is taken";
}
}
I have a database of a schedule where volunteers can check their shifts. I'm going to email them a link to the page where they enter their email addresses into an HTML form to access this information.
Is there a way I can track which emails are queried so I can resend the schedule link to those who haven't accessed the database?
If necessary, I could add an additional 'confirmed' check box to the results and have that update the database. I like that idea, but I'm not sure how to implement (or the terminology for what that action would be).
Edit: Here's the code I'm using to implement. However I'm not getting results in the confirmed column.
$db = new mysqli("host", "user", "pass", "db");
$stmt = $db->prepare('UPDATE volConfirm SET confirmed = TRUE WHERE email = ?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$stmt = $db->prepare('SELECT * from volConfirm WHERE email = ?');
$stmt->bind_param('s', $_POST['email']);
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
// construct your output here using $row to access database record
echo "<h2>" . $row['agreeName'] . "</h2>";
echo "<p> You have been assigned as a volunteer for:" . $row['position'] . "</p>";
echo "<p>Your shift times are scheduled for:" . $row['shift_times'] . "</p>";
echo "<p>Your shift has been confirmed:" . $row['confirmed'] . "</p>";
}
You need to do something along the lines of:
Add a new column to your volunteers table
ALTER TABLE Volunteers ADD COLUMN Confirmed BOOLEAN NOT NULL DEFAULT FALSE;
Have the PHP in the submission page update that column:
UPDATE Volunteers SET Confirmed = TRUE WHERE Email = 'foo#bar.com';
In your code snippet:
$db = new mysqli("dbhostname", "username", "password", "dbschema");
$stmt = $db->prepare('UPDATE volConfirm SET confirmed = TRUE WHERE email = ?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$stmt = $db->prepare('SELECT * from volConfirm WHERE email = ?');
$stmt->bind_param('s', $_POST['email']);
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
// construct your output here using $row to access database record
}
At some point in the future, get a list of all users who have not yet accessed the page:
SELECT Email FROM Volunteers WHERE Confirmed = FALSE;