PDO Query Check for Duplicate Username Upon Submission
ERROR: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING on line 7
Trying to use PDO
to make this connection and form the query that checks for a username if it exists or not upon input into field after submit is pressed.
HTML:
<form action="inc/check_regUsr.php" method="post" id="userLogon">
<div class="field required">
Username: <input type="text" name="regduser" tabindex="1" /><br />
</div>
<div class="field required">
Password: <input type="password" name="re开发者_StackOverflow中文版gdpass" tabindex="2" /><br />
</div>
<input type="submit" name="submitUser" />
</form>
PHP
<?php
#Login Details
require_once('dbcred.php');
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
#Check for Existing User
$q = $conn->query("SELECT uname FROM Student WHERE $_POST['regduser'] = uname");
$stmt = $conn->prepare($q);
$r->execute($q);
if($q($r)>= 1){ #if there are 1 or more users with enter username, deny.
echo "Sorry, username already exists";
}
else{
echo "Success";
}
?>
Enclose your complex variables in {}
inside a double-quoted string:
$q = $conn->query("SELECT uname FROM Student WHERE {$_POST['regduser']} = uname");
// -----------------------------------------------^^^^^^^^^^^^^^^^^^^^^
It looks like your SQL WHERE clause is backward though, and missing quotes. Should be
WHERE uname = '{$_POST['regduser']}'
You have another problem, where you are first calling $conn->query()
and then attempting to create a prepared statement.
The call to query()
is unnecessary and actually dangerous. Instead create a proper prepared statement with ?
placeholders:
$stmt = $conn->prepare("SELECT uname FROM Student WHERE uname = ?");
$stmt->bindParam(1, $_POST['regduser'], PDO::PARAM_STR);
$stmt->execute();
Since you're already using PDO, you might as well take advantage of the parameters feature which provides great protection against SQL injection attacks.
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$stmt = $conn->prepare("SELECT uname FROM Student WHERE ? = uname");
$params = array($_POST['regduser']);
$stmt->execute($params);
if ($stmt->rowCount() > 0) {
echo "Sorry, username already exists";
}
else{
echo "Success";
}
精彩评论