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
Related
so i have a table of data in web ui
as soon as I click the button. all of the field data in "Status Email" changed. not just selected field that i meant.
this is the sintaks sql
if($mail->Send())
{
$query = "UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE EmailSent = 'Belum Kirim Email'";
$update = $con->prepare($query);
$update->execute();
}
how can i get the "update" only the data that I click on the button??
Get specific field
In order to get the specific field from a MYSQL database
Select column FROM databse WHERE x = y
Example:
SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'
The issue
It's best to get a unique identifier, which no other user has used. For example a 10 digit user id code. Check that this code doesn't exist, for it to be unique.
UPDATE:
Easily use the UNIQUE SQL tag to resolve this issue.
CREATE TABLE X (
ID INT UNIQUE
)
Example:
SELECT id, firstname, lastname FROM MyGuests WHERE id=ryan9273__2
Update a specific field
Now that we have fixed the issue we can easily
UPDATE x SET y=z WHERE id=b
Lets fix your code:
UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE EmailSent = 'Belum Kirim Email'
Lets make it more dynamic
UPDATE nearly_inactive SET :email = :emailaddr WHERE EmailSent = :id
final code:
$query = $con->prepare("UPDATE nearly_inactive SET :email = :emailaddr WHERE EmailSent = :id");
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':emailaddr', $emailaddr, PDO::PARAM_STR);
$query->bindParam(':id', $id, PDO::PARAM_STR);
$update->execute();
Security Matters
You are using PDO, so use bindParam aswell. Secret code enthusiast answer isn't as secure as the current code i provided!
Practice Makes Perfect
Please don't copy my code right away. learn from it and code it again ! Make it better. Also check the official PHP documentation for more info on these topics
Stay safe !
Regards,
Ryan
you need to determine which record need to be changed based on their unique ID. usually it's the primary key of the table. so, If your primary key is enroller_id, then pass the value of enroller_id, and put it inside your sql.
if($mail->Send())
{
//prepare your query
$statement = $this->mysqli->prepare("UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE enroller_id = ?");
//check for statement preparation
if ($statement === false) {
trigger_error($this->mysqli->error, E_USER_ERROR);
return;
}
//bind the value
$statement->bindParam("i", $id);
//get id for the query
$id = your_field_enroller_id;
//execute the statement
$statement->execute();
}
where enroller_id is your table primary key, and $id is the value of that field primary key.
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="demon";
//CREATE CONNECTION
$conn=new mysqli($servername,$username,$password,$dbname);
//CHECK CONNECTION
if ($conn->connect_error)
{
die("connection failed:".$conn->connect_error);
}
$sql="UPDATE student set NAME='JohnRambo' where STUDENT_ID=1000";
$result=$conn->query($sql);
if ($result===TRUE)
{
echo"NEW RECORD CREATED SUCCESSFULLY";
}
else
{
echo "ERROR:".$sql."<br>".$conn->error;
}
$conn->close();
?>
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);
}
This is my code, we have database called "our_new_database".
The connection is fine, as well as the HTML Form and credentials and I still cannot insert information into the database.
Table is created, I can see the columns and lines in XAMPP / phpMyAdmin.
The only error I'm getting is the last echo of the If/Else Statement - "Could not register".
Tried everything I can and still cannot make this insertion to work normally.
Can someone advise me something?
<?php
include "app".DIRECTORY_SEPARATOR."config.php";
include "app".DIRECTORY_SEPARATOR."db-connection.php";
include "app".DIRECTORY_SEPARATOR."form.php";
$foo_connection = db_connect($host, $user_name, $user_password, $dbname);
$sql = "CREATE TABLE user_info(
user_name_one VARCHAR(30) NOT NULL,
user_name_two VARCHAR(30) NOT NULL,
user_email VARCHAR(70) NOT NULL UNIQUE
)";
if(mysqli_query($foo_connection, $sql)){
echo "Table created successfully";
}
else {
echo "Error creating table - table already exist.".mysqli_connect_error($foo_connection);
}
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$user_name_one = $_POST["userOne"];
$user_name_two = $_POST["userTwo"];
$user_email = $_POST["userEmail"];
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."',('".$_POST['userTwo']."',('".$_POST['userEmail']."')";
if(mysqli_query($foo_connection,$sql))
{
echo "Successfully Registered";
}
else
{
echo "Could not register";
}
}
$foo_connection->close();
You should avoid the direct use of variables in SQL statements, instead, you should use parameterized queries.
This also should avoid the need to string concatenation and manipulation problems.
$stmt = $foo_connection->prepare("INSERT INTO user_info
(user_name_one,user_name_two,user_email))
VALUES(?,?,?)");
$stmt->bind_param('sss', $user_name_one, $user_name_two, $user_email );
$stmt->execute();
You need to change
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."',('".$_POST['userTwo']."',('".$_POST['userEmail']."')";
To
$sql = "INSERT INTO `user_info`(`user_name_one`,`user_name_two`,`user_emai`l) VALUES ('$user_name_one','$user_name_two','$user_email')";
remember you should use prepared query
$sql= $foo_connection->prepare("INSERT INTO user_info
(user_name_one,user_name_two,user_email))
VALUES(?,?,?)");
$sql->bind_param('sss', $user_name_one, $user_name_two, $user_email );
$sql->execute();
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."','".$_POST['userTwo']."','".$_POST['userEmail']."')";
I reckon your parentheses on this line:
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."',('".$_POST['userTwo']."',('".$_POST['userEmail']."')";
Do not match, it should look like something like this:
$sql = "INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('".$_POST['userOne']."','".$_POST['userTwo']."','".$_POST['userEmail']."')";
Cause for know your query is:
"INSERT INTO user_info (userOne,userTwo,userEmail) VALUES('value',('value1',('value2')"
As said above you might use:
echo $foo_connection->error
To see some errors displayed
From here: PHP $_SESSION is server side or local? I understand that session is server side only and client can't tinker with it.
So I assume it is a safe approach to set id from database to client session id and use it as identification to insert into database?
For example I'm doing like this right now for identification on all my page: login.php
$result = mysqli_query($con, "SELECT id, name, password FROM user_data WHERE email_address = '$email' AND status = '1'") or die(mysqli_error($con));
$row = mysqli_fetch_assoc($result);
if (password_verify($password, $row["password"])) {
$userinfo = array();
$userinfo['id'] = $row["id"];
$userinfo['name'] = $row["name"];
$_SESSION['userinfo'] = $userinfo;
header ("Location: insert.php");
}
and on insert.php page
$result = mysqli_query($con,"INSERT INTO client_data (`data`, `id`) VALUES ('$value', ".$_SESSION['userinfo']['id'].")");
$_SESSION['userinfo']['id'] is only as safe as you make it.
Trusting whatever is in it means trusting all the publicly accessible PHP scripts to work correctly, with no possibility to abuse them to set $_SESSION['userinfo']['id'] to something nasty.
That's really a lot of trust.
I don't think that's affordable.
Especially when this can be done more securely using prepared statements quite easily.
if ($stmt = $mysqli->prepare("INSERT INTO client_data (`data`, `id`) VALUES (?, ?)")) {
/* bind parameters for markers */
$stmt->bind_param("s", $value);
$stmt->bind_param("s", $_SESSION['userinfo']['id']);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($result);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
Using prepared statements will also have the additional benefit of the RDBMS optimizing the queries, making repeated queries faster.
Some code starts with selecting data then check if row numbers are 0 to insert then continue the normal process. The problem is that the normal process is depending on the select statement which does not exist because it was stored before the insert. How can I refresh data request inside PHP without ajax or anything related to html? Here's an example to explain:
$user = $_GET['user']; // not stored user
$select = mysql_query("SELECT * FROM `table` WHERE username = ".$user);
$row = mysql_fetch_array($select);
$rownum = mysql_num_rows($select);
if(!$rownum){
mysql_query("INSERT INTO table (username, something) VALUES ('$user', 1)");
}
/* Here comes the problem */
if($row['something'] == 0){
die("Not found !"); // THIS if returns true since it was not found at first place before inserting
// i want it to refresh the $select data so it could be read as 1
}
How I solved it so far is by repeatedly using the $select and $row code below the insert statement
if(!$rownum){
mysql_query("INSERT INTO table (username, something) VALUES ('$user', 1)");
}
$select = mysql_query("SELECT * FROM `table` WHERE username = ".$user);
$row = mysql_fetch_array($select);
[..]
I want a simpler way to do this
If you know whats in the newly created record, you could just create a new array $row=array('username'->'bob', ...);
BUT if you have default values in the table, or add other things later, you going to have to do a second select.
$user=urldecode($_GET['user']);
$result=mysql_query("SELECT * FROM `table` WHERE username='".mysql_real_escape_string($user)."'");
if(!$result) die("SQL ERROR");
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_array($select);
}
else
{
mysql_query("INSERT INTO table (username, something) VALUES ('".mysql_real_escape_string($user)."', 1)");
$result=mysql_query("SELECT * FROM `table` WHERE username='".mysql_real_escape_string($user)."'");
if(!$result) die("SQL ERROR");
if(mysql_num_rows($result)==0) die("MAJOR ERRORS IN SQL");
$row = mysql_fetch_array($result);
}
I prefer to use $result as this is the result of you running the query.