I was trying to make an API of post method that and take one value from the database from my post method.
<?php
if($_SERVER['REQUEST_METHOD']=='POST') {
$response = array();
//get data
$username = $_POST['username'];
$password = $_POST['password'];
$key_check = $_POST['key_check'];
require_once('Connection.php');
$check_key = "SELECT key_check FROM testing1 WHERE username =? AND password =?";
$insert_key= "UPDATE testing1 SET key_check =? WHERE username =? AND password = ?";
// $insert_key = "INSERT INTO MyGuests (username, password, key_check) VALUES (?, ?, ?)"
if ($result_p = mysqli_prepare($connection,$check_key)){
mysqli_stmt_bind_param($result_p,"ss",$username,$password);
mysqli_stmt_execute($result_p);
$row = $result_p ->get_result();
while ($row1 = $row -> fetch_assoc()){
if(isset($row1["key_check"])){
if($result_p2 = mysqli_prepare($connection,$insert_key)){
mysqli_stmt_bind_param($result_p2,"sss",$username,$password,$key_check);
mysqli_stmt_execute($result_p2);
mysqli_stmt_close($result_p2);
}
}else{
//do something
}
}
}
else{
//do something
}'''
As you can see in the code above, The code will take the key_check value from the first query and then then based on the result if it's null or not, the program will run the second query to add the data from the from the post method. I already checked that the value is null but for some reason the second query did not want to run, is there any thing that I could do or does my logic is wrong in the first place?
Related
I want to run two queries at a time in a function to verify the username and email separately when registering. If one of them already exists in the database, it will return the correct error message on the form.
I investigate them separately so that they can be linked to two separate messages based on a query.
If the username already exists in the database, display the corresponding message. If I put them in a single query, then the separate investigation cannot be done.
My error is: It does not allow you to run two queries at the same time and throws the following error: there is a problem with the preceding parameter. Or it returns an incorrect value.
function pl($connection) {
$query = "SELECT username FROM users WHERE username = ?";
$query2 = "SELECT email FROM users WHERE email = ?";
if ($statment = mysqli_prepare($connection, $query) && $statment2 = mysqli_prepare($connection, $query2)) {
mysqli_stmt_bind_param($statment, "s", $_POST['usern']);
mysqli_stmt_execute($statment);
$result = mysqli_stmt_get_result($statment);
$record = mysqli_fetch_assoc($result);
mysqli_stmt_bind_param($statment2, "s", $_POST['email']);
mysqli_stmt_execute($statment2);
$result2 = mysqli_stmt_get_result($statment2);
$record2 = mysqli_fetch_assoc($result2);
}
if ($result != null) {
echo "succes";
//it will enter even if there is an error
}
}
How it could be solved to execute two mysqli_prepare() at a time?
Why you do not use one query?
Something like:
$query = "SELECT username, email FROM users WHERE username = ? and email = ?";
$statment = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($statment, "ss", $_POST['usern'], $_POST['email']);
mysqli_stmt_execute($statment);
$result = mysqli_stmt_get_result($statment);
$record = mysqli_fetch_assoc($result);
if (!$record) {
echo "succes";
//it will enter even if there is an error
}
also you miss the } at end of your first if
I have created a table in my database where a user can store daily information about themselves, the data saves successfully to the table but there is an error if I try to update data already in the table (this needs to happen if the user has already entered information on that day, instead of creating a new row).
$sql = "SELECT * FROM $username WHERE day=?;";
// Here we initialize a new statement by connecting to the database (dbh.php file)
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error the user is sent to the enter data page again
header("Location: ../enterTodaysData.php?error=sqlerror");
exit();
}
else { //if there are no errors...
mysqli_stmt_bind_param($stmt, "s", $day); //binds the parameters to the statement
mysqli_stmt_execute($stmt); //executes the statement
$result = mysqli_stmt_get_result($stmt); //saves the result of the statement into the result variable
if ($row = mysqli_fetch_assoc($result)) { //if the user HAS already made an entry that day
$sql = "UPDATE $username (SET peakflow1 = $peakflow1 WHERE day=$day);";
$sql = "UPDATE $username (SET peakflow2 = $peakflow2 WHERE day=$day);";
$sql = "UPDATE $username (SET coughing = $coughing WHERE day=$day);";
$sql = "UPDATE $username (SET tightChest = $tightChest WHERE day=$day);";
$sql = "UPDATE $username (SET shortBreath = $shortBreath WHERE day=$day);";
$sql = "UPDATE $username (SET wheezing = $wheezing WHERE day=$day);";
$sql = "UPDATE $username (SET symptomOne = $symptomOne WHERE day=$day);";
$sql = "UPDATE $username (SET symptomTwo = $symptomTwo WHERE day=$day);";
$sql = "UPDATE $username (SET medication = $medication WHERE day=$day);";
$sql = "UPDATE $username (SET mood = $mood WHERE day=$day);";
$sql = "UPDATE $username (SET comments = $comments WHERE day=$day);";
$sql = "UPDATE $username (SET overall = $overall WHERE day=$day);";
header("Location: ../home.php?sql=success");
exit();
}
else{ //if the user has not
$sql = "INSERT INTO $username (day, peakflow1, peakflow2, medication, mood, coughing, tightChest, shortBreath, wheezing, symptomOne, symptomTwo, overall, comments) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; //the question marks are placeholders
$stmt = mysqli_stmt_init($conn);
//an sql statement is prepared and the database is connected to
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error the user is sent back to the signup page
header("Location: ../enterTodaysdata.php?error=sqlerror");
exit();
}
else {
//binds the paramaters and data to the statement
mysqli_stmt_bind_param($stmt, "siisiiiiiiiis", $day, $peakflow1, $peakflow2, $medication, $mood, $coughing, $tightChest, $shortBreath, $wheezing, $symptomOne, $symptomTwo, $overall, $comments);
//this executes the prepared statement and send it to the database, this registers the user.
mysqli_stmt_execute($stmt);
//sends the user back to the signup page, with a message confirming that it was a success
header("Location: ../home.php?sql=success");
exit();
}
}
}
}
The part of the code causing the problem starts at the line $sql = "UPDATE $username (SET peakflow1 = $peakflow1 WHERE day=$day);";.
There are no results appearing on the screen, other than the "sqlerror" error message at the top of the screen, but the table does not update.
I see a few problems with the updates. (There may be other problems at runtime, but this is just what I see in the code you posted.)
In this part:
if ($row = mysqli_fetch_assoc($result)) { //if the user HAS already made an entry that day
$sql = "UPDATE $username (SET peakflow1 = $peakflow1 WHERE day=$day);";
$sql = "UPDATE $username (SET peakflow2 = $peakflow2 WHERE day=$day);";
...
each of those $sql = "UPDATE ... expressions is overwriting the $sql variable, so at the end of that section $sql will only hold the last query.
The parentheses around SET peakflow1 ... etc. are unnecessary at best, and I think they'll cause SQL syntax errors.
There are no quotes around any of the variables in those SQL strings, and some of them contain strings. This will cause SQL syntax errors. (See When to use single quotes, double quotes, and backticks in MySQL.) You should avoid this problem by executing the update the same way you are doing the insert, by binding the variables to placeholders in a prepared statement. By the way, you can do all of the updating with a single query, like:
"UPDATE $username SET peakflow1 = ?, peakflow2 = ?, ... WHERE day = ?"
You aren't executing that SQL. You assign the SQL string to the $sql variable, then immediately exit() without doing anything with it.
With what you're doing here, you may be able to simplify your code by doing an "UPSERT", basically instead of running three queries, (check if exists, insert if not, update if so) you can run one query that will either insert or update. In MySQL you could use the INSERT... ON DUPLICATE KEY UPDATE syntax, provided the day column is defined as unique.
I'm learning to create conditional event where sql checkout data where is exists before inserting data so they don't conflicted.
i've tried using mysql row check in php then check if query empty before i tried to validate the query executed properly.
also trying to close db connection when conditional satisfied but it worthless anyway.
$user = addslashes(strtolower($usr));
$mail = addslashes(strtolower($mail));
$pass = md5(addslashes($pwd));
$check = $db->query("SELECT EXISTS(SELECT *
FROM `users`
WHERE LOWER(`username`) = LOWER('$user')
OR LOWER(`email`) = LOWER('$mail'))");
if (!$check) {
$db->close();
return false;
} else {
$sql = "INSERT IGNORE INTO `users` (`username`, `password`, `email`)
VALUES ('$user', '$pass', '$mail')";
$query = $db->query($sql);
$db->close();
return true;
}
I'm expecting it execute my queries while data was empty and return false while data has been existed.
Your main issue is that $check will always be a truthy value, so long as the query never fails. If the query returns 0 rows, it is still a true object.
You should instead check if there were any values returned. You can also simplify the query quite a bit, given that MySQL is case-insensitive, and you don't need to check if the result exists. Using a prepared statement, the code would look like this
$stmt = $db->prepare("SELECT username FROM users WHERE username = ? OR email = ?");
$stmt->bind_param("ss", $usr, $mail);
$stmt->execute();
$check = $stmt->fetch();
$stmt->close();
// True if the user exists
if ($check) {
return false;
} else {
$stmt = $db->prepare(" INSERT INTO users (username, password, email) VALUES (?, ?, LOWER(?))");
$stmt->bind_param("sss", $usr, $pass, $mail);
$stmt->execute();
$stmt->close();
}
That said, you should not use md5() for passwords - use password_hash() with password_verify() instead.
you can change your code like this
$check = $db->query("SELECT EXISTS(SELECT * FROM `users`
WHERE LOWER(`username`) = LOWER('$user')
OR LOWER(`email`) = LOWER('$mail'))");
$check = $conn->query($sql);
$value = $check->fetch_row()[0];
if($value > 0 ){
echo "existed".$value; // you can change accordingly
}else{
echo "doesn't exist"; // this also
}
Because database respond the query in 1 for exist and 0 for non-exist so the num_row will be always 1 thats why we cant determine the existence with num_row so we have to fetch the value.
I did 3 queries (SELECT, INSERT, UPDATE) it works but at the current state looks ugly and not safe.
Is there any way to make these SELECT, INSERT, UPDATE queries more readable and safer than this with the prepared statement?
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES ('".$_POST["commentID"]."', '".$_POST["comment"]."', '$username', '$id')";
mysqli_query($connect, $sql) or die("ERROR: ". mysqli_error($connect));
/// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$sql1 = "UPDATE user_comments SET id = id +1 WHERE custom_id = '$id'";
mysqli_query($connect, $sql1) or die("ERROR: ". mysqli_error($connect));
Give this a try. You can use $ex->insert_id to get the last entered ID. This may come in handy when mass inserting into a DB. I generally use PDO as I find the code looks cleaner but it's all preference I suppose. Keep in mind for the ->bind_param line that "isii" is referring to the type(s) of data which you are entering. So, in this case, its Integer, String, Integer, Integer (I may have got this wrong).
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$commentID = $_POST["commentID"];
$comment = $_POST["comment"];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES (?, ?, ?, ?)";
$ex = $connect->prepare($sql);
$ex->bind_param("isii", $commentID, $comment, $username, $id);
if($ex->execute()){
// query success
// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$lastInsertID = $ex->insert_id;
$sql1 = "UPDATE user_comments SET id = id + 1 WHERE custom_id = ?";
$ex1 = $connect->prepare($sql1);
$ex1->bind_param("i",$lastInsertID);
if($ex1->execute()){
// query success
}else{
// query failed
error_log($connect->error);
}
}else{
//query failed
error_log($connect->error);
}
Im creating a webpage for a game server that only had a registration page. All the users has registred and for some dum reason, it saved the password as username:password, so if the username is Meko and password is 1234, the actually password is "Meko:1234" Im now trying to make a login but im not sure how I should check that password. I have this sql query and tried to add $user_username: in front, but it didnt seem to work:
$query = "SELECT * FROM account
WHERE username = '$user_username'
AND sha_pass_hash = '$user_password'";
It needs to be $user_username:$user_password
I hope you can help me :)
If what you have stored in the database is an SHA1 checksum, then that's what you will need to compare.
The details are pretty sketchy.
Assuming that the row was saved into the database as
INSERT INTO `account` (`username`, `sha_pass_hash`, ...
VALUES ('Meko', SHA1('Meko:1234'), ...
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
if those are the values you want to pass into the database query, then
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = SHA1( CONCAT( ? ,':', ? )';
$sth = $dbh->prepare($sql);
$sth->bindValue(1,$user_username, PDO::PARAM_STR);
$sth->bindValue(2,$user_username, PDO::PARAM_STR);
$sth->bindValue(3,$user_password, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
// matching row found
} else {
// no matching row found
}
$sth->closeCursor();
If you didn't use the MySQL SHA1 function and used some other function to calculcate the hash, then use that same function when you do the check.
That is, if the row was inserted by a statement of a form more like
INSERT INTO account (username, sha_pass_hash, ... )
VALUES ('Meko','7c4d046a92c441c426ce86f15fa9ecd1fc1fd5f1', ... )
Then to check for the existence of that row, given:
$user_username = 'Meko' ;
$user_password = '1234' ;
Then your query to check for the existence of the row would be something like this:
$sql = 'SELECT ...
FROM account a
WHERE a.username = ?
AND a.sha_pass_hash = ?';
calculate the password hash, the same way as when it was originally done
$user_sha_hash = sha1( $user_username . ':' . $user_password) ;
And prepare and execute the query, passing in the SHA checksum string
$sth = $dbh->prepare($sql);
$sth->bindValue(1, $user_username, PDO::PARAM_STR);
$sth->bindValue(2, $user_sha_hash, PDO::PARAM_STR);
$sth->execute();
if( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
//
} else {
//
)
$sth->closeCursor();
I think you on php ?
$username = 'Meko';
$user_password = '1234';
$altered_pass = $user_username.':'.$user_password;
if($stmt = mysqli_prepare($con,"select * from account where username = ? and sha_pass_hash = ?") ){
mysqli_stmt_bind_param($stmt,'ss',$user_username,sha1($altered_pass));
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt)){
//"yup";
}
else{
//"nope";
}
mysqli_stmt_close($stmt);
}
mysqli_close($con);
You do not specify explicitly but assuming that your sha_pass_hash contains a hashed value of the following format: hash(username:password) then hash '$user_username' + ":" + '$user_password' first and then compare it to your password.
$search = $username.":".$password;
$query = "SELECT * FROM account WHERE password = ".$search;
IMPORTANT:
I very much hope you are preparing your statements and binding your parameters to prevent SQL injection attacks. If you are not, let me know and I can help you out in more detail so that your database is secure.
Also, I recommend that you create another table and fill it in with the values inside this account table. The previous answer is a quick fix so that your users can login meanwhile, but by no means should the previous table stay as it is.
Let me know if you need any more help :)