So, im struggling with this for 2 days, i havent seen any example on google about that it works, so i guess it doesnt work like this:
$steamusername = "xx";
$uname = $_SESSION['username'];
$sql1 = "INSERT INTO users (steamusername) VALUES ( :steamusername) WHERE :username = username";
$query = $conn->prepare( $sql1 );
$result = $query->execute( array( ':steamusername'=>$steamusername, ':username'=>$uname));
It does not give any errors, but it also does not put it into the database.
I really have no idea how i can make it it goes into the user table, i also tried to update the field:
$sql1 = "UPDATE users SET steamusername = :steamusername WHERE username = :username";
$stmt1 = $conn->prepare($sql1);
$stmt1->bindParam(':username', $uname);
$stmt1->bindValue(':steamusername', $steamusername);
$stmt1->execute();
Does anyone know the solution? Thanks in advance!
INSERT is used to create a new record, what you're looking to do is update a current record. You need to use an UPDATE query, as follows:
$query = $conn->prepare( "UPDATE users SET steamusername = :steamusername WHERE username = :username" );
$query->execute(array( ':steamusername' => $steamusername, ':username' => $uname));
Notice that we pass the parameters to the execute() function as an array.
Related
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);
}
The portion that is trying to delete duplicate entries in the database seems incorrect. So I suppose I am asking what would be the correct way to do that in this example. I am not totally new to PHP , but this is beyond me. If you could please tell me what is wrong and how to fix that would be greatly appreciated.
Now on to what I am trying to accomplish. I have a multidimensional array filled with values that is generated by a function. What I am trying to do is if there is a value in the array that already exists in the database delete it. Code:
enter code here
if(is_array($items)){
$values = array();
foreach($items as $row => $value){
$rsn = mysqli_real_escape_string($connect, $value[0]);
$rank = mysqli_real_escape_string($connect, $value[1]);
$values[] = "('', '$rsn', '$rank', '')";
$sql = "SELECT id FROM users WHERE rsn = :rsn";
$query = $conn->prepare($sql);
$query->execute(array(":rsn" => $value[0]));
$results = $query->rowCount();
while($deleted = $query->fetch(PDO::FETCH_ASSOC)){
$sql = "DELETE FROM users WHERE id = :id";
$query = $conn->prepare($sql);
foreach($deleted as $delete){
$query->execute(array(':id' => $delete));
}
}
}
//user_exists_delete($conn, $rsn);
$sql = "INSERT INTO users(id, rsn, rank, points) VALUES ";
$sql .= implode(', ', $values);
if(!empty($rank)&& !empty($rsn)){
if(mysqli_query($connect, $sql)){
echo "success";
}else{
die(mysqli_error($connect));
}
}
}
EDIT: I have got it partially working now, just need it to delete all dupes instead of only one. I edited code to reflect changes.
There are a couple problems, if you didn't strip much of your original code and if you don't need to do more than just what you shown why not just send a delete instruction to your database instead of checking validity first?
You have
//Retrieve ID according to rsn.
$sql = "SELECT id FROM users WHERE rsn = :rsn ";
//Then retrieve rsn using rsn??? Useless
$sql = "SELECT rsn FROM users WHERE rsn = :rsn ";
//Then delete using ID, retrieved by rsn.
$sql = "DELETE FROM users WHERE id = :id";
All those could simply be done with a delete using rsn...
$sql = "DELETE FROM users WHERE rsn = :rsn";
The row won't be deleted if there are no rows to delete, you don't need to check in advance. If you need to do stuff after, then you might need to fetch information before, but if not, you can use that while still checking the affected rows to see if something got deleted.
Now, we could even simplify the script by using only one query instead of one per user... We could get all rsn in an array and then pass it to the DELETE.
$sql = "DELETE FROM users WHERE rsn in :rsn";
//Sorry not exactly sure how to do that in PDO, been a while.
I fixed it I just omitted the WHERE clause in the delete statement so all records are being deleted before that insert gets ran again.
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 :)
I'm pretty much a novice when it comes to coding, so sorry for lack of knowledge here.
I'm trying to retrive a forigne key attribute from one database table (the user's ID number) so I can then make that id a variable which will be used to save the details into another database table.
From that I can view all of the saved records linked with that user's id when they are logged in.
My problem is with getting the user ID and making it a variable to save into the database, I just can't seem to make it work. The rest of the code works if I remove the user ID but I need that to save into the table.
Here's my code:
require_once( "dbconnect.php" );
try
{
$db = getConnection();
function get_id($db)
{
$username= $_SESSION['username'];
$result = $db->query(
"SELECT userID FROM users where username='$username'");
return $result;
}
$uID = get_id($db);
$userID= $uID->setFetchMode(PDO::FETCH_NUM);
$title = $Result->title;
$desp = $Result->description;
$sql = "INSERT INTO saved (userID, title, desp
VALUES ('$userID', '$title', '$desp')";
The proper way
function get_subid($db,$username)
{
$stm = $db->prepare("SELECT userID FROM users where username=?");
$stm->execute(array($username));
return $stm->fetchColumn();
}
$userID = get_subid($db,$_SESSION['username']);
try removing the quotes around userid variable in your query :
$sql = "INSERT INTO saved (userID, title, desp) VALUES ($userID, '$title', '$desp')";
Try the following:
require_once( "dbconnect.php" );
try {
/** * ** connect using the getConnection function written in myfunctions.php ** */ $db = getConnection();
function get_subid($db) {
$username= $_SESSION['username']; //variable accessed through the function
$query = $db->query("SELECT userID FROM users where username='$username'");
$row = $query->row(); //Get's the first Row
$result = $row->userID; //Get's the field userID of this first row
return $result;
}
$uID = get_subid($db);
$title = $Result->title;
$desp = $Result->description;
// insert into database
$data = array(
'userID' => $uID,
'title' => $title,
'desp' => $desp
);
$db->insert('saved', $data);
This should be what you'd like (see the comments)
I have this code to select all the fields from the 'jobseeker' table and with it it's supposed to update the 'user' table by setting the userType to 'admin' where the userID = $userID (this userID is of a user in my database). The statement is then supposed to INSERT these values form the 'jobseeker' table into the 'admin' table and then delete that user from the 'jobseeker table. The sql tables are fine and my statements are changing the userType to admin and taking the user from the 'jobseeker' table...however, when I go into the database (via phpmyadmin) the admin has been added by none of the details have. Please can anyone shed any light onto this to why the $userData is not passing the user's details from 'jobseeker' table and inserting them into 'admin' table?
Here is the code:
<?php
include ('../database_conn.php');
$userID = $_GET['userID'];
$query = "SELECT * FROM jobseeker WHERE userID = '$userID'";
$result = mysql_query($query);
$userData = mysql_fetch_array ($result, MYSQL_ASSOC);
$forename = $userData ['forename'];
$surname = $userData ['surname'];
$salt = $userData ['salt'];
$password = $userData ['password'];
$profilePicture = $userData ['profilePicture'];
$sQuery = "UPDATE user SET userType = 'admin' WHERE userID = '$userID'";
$rQuery = "INSERT INTO admin (userID, forename, surname, salt, password, profilePicture) VALUES ('$userID', '$forename', '$surname', '$salt', '$password', '$profilePicture')";
$pQuery = "DELETE FROM jobseeker WHERE userID = '$userID'";
mysql_query($sQuery) or die (mysql_error());
$queryresult = mysql_query($sQuery) or die(mysql_error());
mysql_query($rQuery) or die (mysql_error());
$queryresult = mysql_query($rQuery) or die(mysql_error());
mysql_query($pQuery) or die (mysql_error());
$queryresult = mysql_query($pQuery) or die(mysql_error());
mysql_close($conn);
header ('location: http://www.numyspace.co.uk/~unn_v002018/webCaseProject/index.php');
?>
Firstly, never use SELECT * in some code: it will bite you (or whoever has to maintain this application) if the table structure changes (never say never).
You could consider using an INSERT that takes its values from a SELECT directly:
"INSERT INTO admin(userID, forename, ..., `password`, ...)
SELECT userID, forename, ..., `password`, ...
FROM jobseeker WHERE userID = ..."
You don't have to go via PHP to do this.
(Apologies for using an example above that relied on mysql_real_escape_string in an earlier version of this answer. Using mysql_real_escape_string is not a good idea, although it's probably marginally better than putting the parameter directly into the query string.)
I'm not sure which MySQL engine you're using, but your should consider doing those statements within a single transaction too (you would need InnoDB instead of MyISAM).
In addition, I would suggest using mysqli and prepared statements to be able to bind parameters: this is a much cleaner way not to have to escape the input values (so as to avoid SQL injection attacks).
EDIT 2:
(You might want to turn off the magic quotes if they're on.)
$userID = $_GET['userID'];
// Put the right connection parameters
$mysqli = new mysqli("localhost", "user", "password", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Use InnoDB for your MySQL DB for this, not MyISAM.
$mysqli->autocommit(FALSE);
$query = "INSERT INTO admin(`userID`, `forename`, `surname`, `salt`, `password`, `profilePicture`)"
." SELECT `userID`, `forename`, `surname`, `salt`, `password`, `profilePicture` "
." FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "UPDATE user SET userType = 'admin' WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "DELETE FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$mysqli->commit();
$mysqli->close();
EDIT 3: I hadn't realised your userID was an int (but that's probably what it is since you've said it's auto-incremented in a comment): cast it to an int and/or don't use it as a string (i.e. with quotes) in WHERE userID = '$userID' (but again, don't ever insert your variable directly in a query, whether read from the DB or a request parameter).
There's nothing obviously wrong with your code (apart from it being insecure with using non-escaped values directly from $_GET).
I'd suggest you try the following in order to debug:
var_dump $userData to check that the values are as you expect
var_dump $rQuery and copy and paste it into phpMyAdmin to see if your query is not as you expect
If you don't find your problem then please post back your findings along with the structure of the tables you're dealing with