I am attempting with no success to return a Boolean Value from the following PHP/PDO call back to jQuery/AJAX:
$db = new PDO('mysql:host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
$sql = "SELECT COUNT(*)" .
"FROM bu_users" .
"WHERE user_email = :email";
$stmt = $db->prepare($sql);
$stmt->execute(array(':email' => $_GET[reg_email]));
if(!$stmt){
$result = $stmt->errorInfo();
} else {
$result = $stmt->fetchColumn();
}
print_r($result);
I am outputting my results via console.log but am only receiving empty responses whether the email matches a database row or not. Any help would be appreciated. Thanks.
SQL syntax problems:
$sql = "SELECT COUNT(*)" .
"FROM bu_users" .
^---
"WHERE user_email = :email";
^---
You're lacking spaces at the indicated spots, and your query ends up looking like:
SELECT COUNT(*)FROM bu_usersWHERE user_email = :email;
^^-- ^^--
Don't generate multiline strings like that. It's far too easy to make silly mistakes like this. At least use a HEREDOC:
$sql = <<<EOL
SELECT COUNT(*)
FROM bu_users
WHERE user_email = :email
EOL;
No need for concatentation, automatic multi-line usage, and you can nicely format your SQL as well.
$stmt = $db->prepare("SELECT 1 FROM bu_users WHERE user_email = ?");
$stmt->execute(array($_GET['reg_email']));
echo json_encode((bool)$stmt->fetchColumn());
Related
//Positional Params
$emailToken = $_GET['token'];
$sql = 'SELECT * FROM signup WHERE token = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$emailToken]);
$message = $stmt->fetchAll();
Basically I have a email token i parse from the url and want to check whether in the database does it exist or not. No matter what it won't valid even though i checked and echo the emailToken is the exact same.
I tested with another variable
$sql = 'SELECT * FROM signup WHERE email = ?';
$stmt->execute(['asd#gmail.com']);
And it works. Any idea?
It might just be personal preference, but I like being more specific with the bind variables and the syntax never seems to fail me.
$emailToken = $_GET['token'];
$sql = 'SELECT * FROM signup WHERE token = :token';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':token', $emailToken, PDO::PARAM_STR);
$stmt->execute();
$message = $stmt->fetchAll();
building a string with the syntax (never keep code like this, it is only a test)
$sql = "SELECT * FROM signup WHERE token = '" . $_GET['token'] . "'";
var_dump( $sql );
$stmt = $pdo->prepare($sql);
$stmt->execute();
$message = $stmt->fetchAll();
then you can test this outputted code in a query tool to make sure it is syntactically correct.
I am trying to use prepared statements to select data from a table as the following. This method does not work.
$sql = "SELECT * FROM `usrs` WHERE `username` = ? ";
$statement = $this->conn->prepare($sql);
if (!statement)
{
throw new Exception($statement->error);
}
$statement->bind_param("s",$username);
$returnValue = $statement->execute();
return $returnValue;
$sql should be in the following format.
$sql = "SELECT * FROM `usrs` WHERE `username` = 'username' ";
however the above code does not place single quotes ' ' around username
I need to place username between two single quotes ' ' as shown. if I use just
$sql = "SELECT * FROM `usrs` WHERE `username` = username "
it does not work.
any suggesstions how to do that.
Read this carefully:
bool mysqli_stmt::execute ( void )
it means it returns boolean - that is not a usable object or an array.
You've to fetch the statement.
Here's the fix:
$sql = "SELECT * FROM `usrs` WHERE `username` = ? LIMIT 1";
$statement = $this->conn->prepare($sql);
$statement->bind_param("s",$username);
if ($statement->execute()) {
$result = $statement->get_result();
return $result->fetch_assoc();
}
return null;
P.S. Thank You #Phil for fixing my mistakes in my answer
How do I query from a MySQL database when I have a period (.) in string using PHP.
$variable = "my.email#email.com";
$variable = mysqli_real_escape_string($conn, $variable);
$query = "Select * from table WHERE email = '$variable' ";
Apparently this works when I ran it in PhpMyAdmin SQl tab. But when I run it In my code it does not work. Other strings that don't have a period using the same code are working perfectly. What could be the issue
for those who are asking for my original code here it is
//I get the emails from the url
$notit = mysqli_real_escape_string($conn, $_GET['username']);
//I pass my variable in the query
$sql = "SELECT * ";
$sql.=" FROM ordrs ";
$sql.=" WHERE client_email = '$notit' ";
$query=mysqli_query($conn, $sql) or die("try again");
Try this code it works for me try using PDO.
try{
$pdo = new PDO("mysql:host={$db_host};dbname={$db_name}", $db_username, $db_password);
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$email = "code.sample#mail.co.ke";
$stmt = $pdo->prepare('SELECT email FROM user WHERE email = ?');
$stmt->bindParam(1, $email);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
Sample output by eg: echo '<h2>'. $user['email'] . '</h2>';
You should use prepared statements. Otherwise, possible of sql injection vulnerability.
Example:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("Select * from table WHERE email = ?");
$stmt->bind_param("s", $email);
// set parameters and execute
$email = "john.doe#example.com";
$stmt->execute();
I figured where the issue was the query was fine the error was coming from json_encode which I din't expect . I hope this question helps others in the future who are facing the problem questioned. Thanks for the help
thanks for the help. Cheers
I've having some troubles with the PDO bindValue() function. Whenever I seem to use it, my queries always return 0 results. However it works fine if I put $user and $pass straight into the sql without the use of bindValue()
$user is a string
$password is a sha1() hash
public function login($user, $pass) {
global $CMS;
$sql = "SELECT `username,`password` FROM `" . TB_PREFIX . "users` WHERE `username` = ':user' AND `password` = ':pass'";
$query = $CMS->prepare_query($sql);
$query->bindValue(':user', $user, PDO::PARAM_STR);
$query->bindValue(':pass', $pass, PDO::PARAM_STR);
$query->execute();
# User successfully authenticated
if ($query->rowCount() == 1) {
# Get all data from DB and populate class variables
self::populate_user_data($user);
session_register($user . "-" . base64_encode($_SERVER['REMOTE_ADDR']));
return true;
}
# User failed authentication
return false;
}
You should not put the quotes around the values yourself, they will be added (if needed, such as in the case of strings - this case):
$sql = "SELECT `username,`password` FROM `" . TB_PREFIX . "users`
WHERE `username` = :user AND `password` = :pass";
The placeholders in a prepared statement must not be quoted; PDO is already doing all the quoting. You want:
$sql = "SELECT `username,`password` FROM `" . TB_PREFIX . "users` " .
"WHERE `username` = :user AND `password` = :pass";
When using prepared statements, the values get escaped automagically.
This means, that you don't have to set quotes around the arguments.
try:
$sql = "SELECT `username,`password` ".
"FROM `" . TB_PREFIX . "users` ".
"WHERE `username` = :user AND `password` = :pass";
and you should be fine.
As a side note though: you should NEVER store user passwords literally. Check this excellent article: You're Probably Storing Passwords Incorrectly
I'm sure this is something very basic but I can't seem to find my error.
I'm trying to execute the following...
$c = db_connect();
$email = addslashes($email);
$sql = "SELECT * FROM RUSER WHERE email LIKE '" . $email . "';";
$query = oci_parse($c, $sql) or die(oci_error($c));
$response = oci_execute($query) or die(oci_error($c));
but I get oci8 statement Warning: oci_execute(): ORA-00911: invalid character in /path/to/file.php on line 67 where line 67 is where $response is assigned.
So that means there is something wrong with $query right? But I can't seem to find what that would be. The raw sql executes fine from the command line. echoing get_resource_type($query) gives a resource id...
What am I doing wrong?
Do NOT include the ; in your SQL. The ; is not part of SQL itself, its used by various SQL clients (e.g. sql*plus) as a delimiter to mark the end of commands to be sent to the server.
The first error is
$c = oci_connect("user","password","host/dbname") // db_connect() is not true
second error is there should not be ";" in the statement
$sql = "SELECT * FROM RUSER WHERE email LIKE '" . $email . "';";
it should be
$sql = "SELECT * FROM RUSER WHERE email LIKE '" . $email . "'";
if you want to compare better user "=" than LIKE
Yes, the semicolon is an issue, but not the only one.
the query is directly injecting the variable string into the sql -- this is a potential point of vulnerability/insecurity.
there is no need for the LIKE comparison if you aren't using any wildcard characters (e.g. %, _) in your value.
Suggested Code:
$stmt = oci_parse($conn, "SELECT * FROM RUSER WHERE email = :email");
oci_bind_by_name($stmt, ":email", $email);
oci_execute($stmt);
$count = oci_fetch_all($stmt, $resultSet, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
// hypothetical outputs:
// $count = 1
// $resultSet = [['id => 3, 'email' => 'example#example.com', ...]]