I'm having a little trouble getting this query to work:
$userId = mysql_real_escape_string( $_SESSION['user_id'] );
$userPassProvided = mysql_real_escape_string( $_POST['oldPassword'] );
$query = "SELECT user_id, AES_DECRYPT( user_pass, '".$db_aes_key."' ) AS user_pass ";
$query .= "FROM users_tbl WHERE MATCH( user_id, user_pass ) ";
$query .= "AGAINST( '".$userId."', '".$userPassProvided."' IN BOOLEAN MODE ) LIMIT 1";
$result = mysql_query( $query, $mysql_db );
What I would like to do is query users_tbl for the record wherein user_id and user_pass are the same as $userId and $userPassProvided, respectively. Can someone please tell me what is wrong with my query?
Thanks. :)
The following is functionally equivalent to what you seem to want to do. (Do read "however..." below)
$query = "SELECT user_id, AES_DECRYPT( user_pass, '".$db_aes_key."' ) AS user_pass ";
$query .= "FROM users_tbl ";
$query .= "WHERE user_id = '".$userId."' ";
$query .= " AND AES_DECRYPT(user_pass, '".$db_aes_key."' ) = '".$userPassProvided."' ";
$query .= "LIMIT 1";
...however MySQL would have to AES-decript every single encoded password in the database. This will be both computationally expensive and prevent using any SQL index.
Alternatively, you may consider encrypting the supplied password, and match it to the ones stored in the database. Maybe something like that (note: untested):
$query = "SELECT user_id, AES_DECRYPT( user_pass, '".$db_aes_key."' ) AS user_pass ";
$query .= "FROM users_tbl ";
$query .= "WHERE user_id = '".$userId."' ";
$query .= " AND user_pass = AES_ENCRYPT('".$userPassProvided."', '".$db_aes_key."' ) ";
$query .= "LIMIT 1";
MATCH () AGAINST () doesn't work like you're expecting it to. What it does is attempts to match a single string in AGAINST() against each of the columns provided in MATCH(), rather than comparing value1 against column1 and value2 against column2.
Have you tried ...WHERE user_id = '".$userId."' AND user_pass = '"$userPassProvided"' LIMIT 1?
Related
I have a code, in which there are users will search for the name from MySQL.
First the mysql should search in first_name, then go to last_name for the same search option and then display results. (From both First_name and Last_name)
I tried but it showed me only the results from first name
Please help me.
Here is the code:-
try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
} elseif ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (last_name LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
}else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
$stmt->execute();
$total_count = count($stmt->fetchAll());
Try to avoid posting same question in other ways, edit the same question.
You asked the same question in MYSQL OR not working
Hope this will really help you:-
try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword OR last_name LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
}else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
$stmt->execute();
$total_count = count($stmt->fetchAll());
I have also answered your new repeated question https://stackoverflow.com/a/44859408/7678788
try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
} else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
i need to do multiple search, with first_name,last_name,middle_name,contact_no1 fields
If you want to do search with all fields add fields in WHERE with OR:
try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword OR last_name LIKE :keyword OR middle_name LIKE :keyword OR contact_no1 LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
} else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
public function search($requestArray){
$sql = "";
if( isset($requestArray['firstname']) && isset($requestArray['lastname']) ) $sql = "SELECT * FROM `tbl_contacts` WHERE AND (`first_name` LIKE '%".$requestArray['search']."%' OR `last_name` LIKE '%".$requestArray['search']."%')";
if(isset($requestArray['firstname']) && !isset($requestArray['lastname']) ) $sql = "SELECT * FROM `tbl_contacts` WHERE `first_name` LIKE '%".$requestArray['search']."%'";
if(!isset($requestArray['firstname']) && isset($requestArray['lastname']) ) $sql = "SELECT * FROM `tbl_contacts` WHERE `last_name` LIKE '%".$requestArray['search']."%'";
$STH = $this->DBH->query($sql);
$STH->setFetchMode(PDO::FETCH_OBJ);
$someData = $STH->fetchAll();
return $someData;
}
I used this method in one of my project for searching with two field hope it could help you. where $requestArray will get the data from form and 'firstname' , 'lastname' are two key of the array which you will enter your searchbox and submit to search. I just showed you here the query style and before that you have tor trim the values.
I am trying to insert/update the MySql database depending on whether a post already exists on the database (I am checking this with a unique user_id). The following works:
$select_query = "SELECT * ";
$select_query .= "FROM test ";
$select_query .= "WHERE user_id = '$user_id'";
$check_user_id = mysqli_query($connection, $select_query);
$query = "INSERT INTO test (";
$query .= " user_id, name, message";
$query .= ") VALUES (";
$query .= " '{$user_id}', '{$name}', '{$message}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
echo "Success!";
} else {
die("Database query failed. " . mysqli_error($connection));
}
However, when I use the following code with an if/else statement, it does not work anymore, although the console reports "Success!" (meaning $result has a value). Any help would be greatly appreciated. Thanks.
$select_query = "SELECT * ";
$select_query .= "FROM test ";
$select_query .= "WHERE user_id = '$user_id'";
$check_user_id = mysqli_query($connection, $select_query);
if (!$check_user_id) {
$query = "INSERT INTO test (";
$query .= " user_id, name, message";
$query .= ") VALUES (";
$query .= " '{$user_id}', '{$name}', '{$message}'";
$query .= ")";
} else {
$query = "UPDATE test SET ";
$query .= "name = '{$name}', ";
$query .= "message = '{$message}' ";
$query .= "WHERE user_id = '{$user_id}'";
}
$result = mysqli_query($connection, $query);
if ($result) {
echo "Success!";
} else {
die("Database query failed. " . mysqli_error($connection));
}
As i understand your code. you are trying to check if the user_id is existing in your database..
i made a simple code and i think its works for me..
$select_query = mysql_query("SELECT * FROM test WHERE user_id = '$user_id'") or die (mysql_error());
$result = mysql_num_rows($select_query);
if(!$result){
$query = mysql_query("INSERT INTO test (user_id, name, message) VALUES ('$user_id', '$name', '$message')");
if($query){
echo "Success!";
}
else
{
die (mysql_error());
}
}
else{
$query2 = mysql_query("UPDATE test SET name='$name', message='$message' WHERE user_id = '$user_id'")
}
mysql_query returns the operation identifier, not the actual result. This is why $check_user_id is always true, so you are always trying to update (even not existing!) rows.
you have to "read" the result ofmysql_queryby for example using
$check_user_id = mysql_num_rows( mysql_query($connection, $select_query) );
now it returns 0 (false) iff there were no results for q $select_query
This statement is giving you a resource to the result
$check_user_id = mysqli_query($connection, $select_query);
next you are checking for if(!$check_user_id) : this condition evaluates to false because of the negation !. Thus your condition goes to the else part and and never enters the if.
The $result always has value because you are calling it towards the end of the script.
Since you previously know the user_id, and assuming that is a primary key in the table, you could use "ON DUPLICATE KEY UPDATE" clause:
$query = mysql_query("INSERT INTO test (user_id, name, message)
VALUES ('$user_id', '$name', '$message')
ON DUPLICATE KEY
UPDATE name='$name', message='$message';
");
Same result with only one query.
Ref: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Use Code for data inserting in mysql.
$query = mysql_query("INSERT INTO test set user_id = '$user_id', name = '$name', message = '$message'");
if($query){
echo "Success!";
}
I have a DB table. I want to make a text input where the user can input the "uid" and the query will return the row associated with that uid.
So let's say I have something like this:
$query = "SELECT name,age FROM people WHERE uid = '2' LIMIT 0,1";
$result = mysql_query($query);
$res = mysql_fetch_assoc($result);
echo $res["age"];
how would I modify that query to something like..
SELECT name, age
FROM people
WHERE uid = $_POST['blahblah'] LIMIT 0,1
Thanks in advance for your help!
In reality...
// Read input from $_POST
$uid = (isset($_POST['uid']) ? $_POST['uid'] : '');
// Build query. Properly escape input data.
$query =
"SELECT name,age " .
"FROM people " .
"WHERE uid = '" . mysql_real_escape_string($uid) . "' " .
"LIMIT 0,1";
Its advisable to escape characters in the variable for security reasons. Take a look at this document for some of the reasons:
http://en.wikipedia.org/wiki/SQL_injection
To save from SQL injection attack, use:
$search_query = mysql_real_escape_string($_POST['blahblah']);
$query = "SELECT name, age FROM people WHERE uid = '".$search_query."' LIMIT 0 , 1";
There are so many ways to do the same
But first escape it and store it in one variable
$blahblah = mysql_real_escape_string($_POST['blahblah']);
And then There are
First:
As #Mett Lo mentioned:
$query = "SELECT name,age FROM people WHERE uid = '" . $blahblah . "' LIMIT 0,1";
Second:
$query = "SELECT name,age FROM people WHERE uid = '{$blahblah}' LIMIT 0,1";
Third:
$query = "SELECT name,age FROM people WHERE uid = '$blahblah' LIMIT 0,1";
and if blahblah is an int value in db table then Fourth:
$query = "SELECT name,age FROM people WHERE uid = $blahblah LIMIT 0,1";
You may use the sprintf function to create the query.
$query = sprintf("SELECT name,age FROM people WHERE uid = '%s' LIMIT 0,1",
$_POST['blahblah'] );
The rest will be the same. It is highly recommended that you escape the $_POST data before running the query to prevent SQL attacks. You may re phrase the query as follows.
$query = sprintf("SELECT name,age FROM people WHERE uid = '%s' LIMIT 0,1",
mysql_escape_string($_POST['blahblah']) );
I am triig to fill options list. I have 2 tables USERS and STREAMS I vant to get all streams and get names of users assigned to that streams.
Users consists of username and id
Streams consists of id, userID, streamID
I try such code:
<?php
global $connection;
$query = "SELECT *
FROM streams ";
$streams_set = mysql_query($query, $connection);
confirm_query($streams_set);
$streams_count = mysql_num_rows($streams_set);
while ($row = mysql_fetch_array($streams_set)){
$userid = $row['userID'];
global $connection;
$query2 = "SELECT email, username ";
$query2 .= "FROM users ";
$query2 .= "WHERE id = '{$userid}' ";
$qs = mysql_query($query2, $connection);
confirm_query($qs);
$found_user = mysql_fetch_array($qs);
echo ' <option value="'.$row['streamID'].'">'.$row['userID'].$found_user.'</option> ';
}
?>
But it does not return USER names from DB=( So what shall I do to this code to see usernames as "options" text?
You can do this with one query containing a JOIN on streams.userID=users.id
$query = "
SELECT
s.streamId,
s.userId,
u.username
FROM
streams as s
JOIN
users as u
ON
s.userId=u.id
";
$result = mysql_query($query, $connection);
confirm_query($result);
echo '<option value="">Debug: #rows=', mysql_num_rows($row), '"</option>';
while ( false!==($row=mysql_fetch_array($result)) ) {
sprintf('<option value="%s">id:%s name:%s</option>',
$row['streamID'], // you probably should apply htmlspecialchars()
$row['userID'], // on these two, too.
htmlspecialchars($row['username'])
);
}