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);
}
Related
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?
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.
please help me out and sorry for my bad English,
I have fetch data , on basis of that data I want to update the rows,
Follows my code
I fetched data to connect API parameters
<?php
$stmt = $db->stmt_init();
/* publish store for icube*/
$stmt->prepare( "SELECT id,offer_id,name,net_provider,date,visible,apikey,networkid FROM " ."affilate_offer_findall_icube WHERE visible='1' ");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result( $id, $offer_id, $name, $net_provider, $date, $visible,$apikey,$networkid);
$sql = array();
if($rows>0)
{
while($info = $stmt->fetch() ) {
$jsondataicube = file_get_contents('filename/json?NetworkId='.$networkid.'&Target=Affiliate_Offer&Method=getThumbnail&api_key='.$apikey.'&ids%5B%5D='.$offer_id.'');
$dataicube = json_decode($jsondataicube, true);
foreach($dataicube['response']['data'][0]['Thumbnail'] as $key=>$val)
{
$offer_id = $dataicube['response']['data'][0]['Thumbnail']["$key"]['offer_id'];
$display = $dataicube['response']['data'][0]['Thumbnail']["$key"]['display'];
$filename = $dataicube['response']['data'][0]['Thumbnail']["$key"]['filename'];
$url = $dataicube['response']['data'][0]['Thumbnail']["$key"]['url'];
$thumbnail = $dataicube['response']['data'][0]['Thumbnail']["$key"]['thumbnail'];
$_filename = mysqli_real_escape_string($db,$filename);
$_url = mysqli_real_escape_string($db,$url);
$_thumbnail = mysqli_real_escape_string($db,$thumbnail);
$sql[] = '("'.$offer_id.'","icube","'.$_thumbnail.'","'.$_url.'")';
}
}
As I store values which have to be inserted in 'sql'
now
$stmt->prepare( "SELECT offer_id FROM " ."affilate_offer_getthumbnail_icube ORDER BY 'offer_id' ASC");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result($offer_id);
$sqlimplode = implode(',', $sql);
if($rows>0)
{
$query = "UPDATE affilate_offer_getthumbnail_icube WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}`
`
Insert query working well,but how can I update all the data like insert query ?
My Answer is refering to a "set and forget"-strategy. I dont want to look for an existing row first - probably using PHP. I just want to create the right SQL-Command and send it.
There are several ways to update data which already had been entered (or are missing). First you should alter your table to set a problem-specific UNIQUE-Key. This is setting up a little more intelligence for your table to check on already inserted data by its own. The following change would mean there can be no second row with the same value twice in this UNIQUE-set column.
If that would occur, you would get some error or special behaviour.
Instead of using PHPMyAdmin you can use this command to set a column unique:
ALTER TABLE `TestTable` ADD UNIQUE(`tablecolumn`);
After setting up your table with this additional intelligence, you alter your Insert-Command a little bit:
Instead of Insert you can drop and overwrite your Datarow with
REPLACE:
$query= "REPLACE INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100) VALUES (".$sqlimplode.")";
See: Replace Into Query Syntax
Secondly you can do this with the "On Duplicate Key"-Commando.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$query= "INSERT INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100)
VALUES (".$sqlimplode.")
ON DUPLICATE KEY UPDATE net_provider = ".$newnetprovider.",
logo2020 = ".$newlogo2020.",
logo100 = ".$newlogo100.";";
Note: I think you missed some ( and ) around your $sqlimplode. I always put them around your implode. Maybe you are missing ' ' around strings as well.
Syntax of UPDATE query is
UPDATE table SET field1 = value1, field2 = value2 ...
So, you cannot pass your imploded array $sql to UPDATE query. You have to generate another sql-string for UPDATE query.
This is clearly incorrect:
$query = "UPDATE affilate_offer_getthumbnail_icube
WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
If the intention is to INSERT offer_id='".$offer_id."' and then UPDATE ... SET offer_id = '".$sqlimplode."'";
You have to use two separate queries, one for INSERT and then another one for UPDATE
An Example:
$query = "INSERT INTO affilate_offer_getthumbnail_icube
(col_name) VALUES('".$col_Value."')";
//(execute it first);
$query2 = "UPDATE affilate_offer_getthumbnail_icube SET
col_name= '".$col_Value."'" WHERE if_any_col = 'if_any_Value';
//(execute this next);
Try this:
$sqlimplode = implode(',', $sql);
if($rows>0)
{
/*$fields_values = explode(',',trim(array_shift($sql), "()"));
$combined_arr = array_combine(['offer_id','net_provider','logo2020','logo100'],$fields_values);
$sqlimplode = implode(', ', array_map(function ($v, $k) { return $k . '=' . $v; }, $combined_arr, array_keys($combined_arr))); */
$query = "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode." ON duplicate key update net_provider = values(net_provider),logo2020 = values(logo2020),logo100 = values(logo100)";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$sqlimplode = implode(',', $sql);
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}
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
I have almost no experience with PHP and right now I'm stuck at the total beginning, which is really frustrating. I have a code, which seems to work. From my app I can input values and put them in my PHP database. Thing is that he only inputs the very last value from my PHP code. So the app aside: If I only use the PHP code to input something in my database he always only takes the last value. Here is my code:
<?php
$DB_HostName = "localhost";
$DB_Name = "xxx";
$DB_User = "xxx";
$DB_Pass = "xxx";
$DB_Table = "contacts";
if (isset ($_GET["name"]))
$name = $_GET["name"];
else
$name = "Blade";
if (isset ($_GET["lastname"]))
$lastname = $_GET["lastname"];
else
$lastname = "Xcoder";
if (isset ($_GET["number"]))
$number = $_GET["number"];
else
$number = "111";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql = "insert into $DB_Table (Lastname) values('$lastname');";
$sql = "insert into $DB_Table (Number) values('$number');";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>
To clarify: If I only have the firstname value, he inputs it in the right place (firstname). If I have a firstname and lastname value, he only inputs the lastname value, but not the firstname value (still at the right place lastname). And the same for number. If I have a firstname, lastname and a number, he only puts the number in the right place but not the other values. In addition I can only do it once. If I want to enter another contact he always says (Duplicate entry 'myentry' for key 'PRIMARY').
You overwrite your query, 2 ways to solve. Either 3 different variables, or 1 variable with 3 queries in it. I would prefer the 2nd option
$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql .= "insert into $DB_Table (Lastname) values('$lastname');";
$sql .= "insert into $DB_Table (Number) values('$number');";
$res = mysql_query($sql,$con) or die(mysql_error());
Or if it can be 1 row in the table, as it is the same table anyways:
$sql = "insert into $DB_Table (Firtname,Lastname,Number) values('$name','$lastname','$number');";
$res = mysql_query($sql,$con) or die(mysql_error());
Because you are overwriting $sql on the next 2 lines, so the final sql line is what is inserted.
Your sql is wrong if you want them all in the same row.
$sql = "insert into $DB_Table (Firtname,lastname,number) values('$name','$lastname','$number');";
You are overwriting your $sql statements. You have to execute them. By doing:
$sql = "Insert INTO..."
you merely set a a variable. You need to ru each query using mysql_query().
I'm also guessing that you want to do this:
$sql = "INSERT INTO $DB_TABLE (Firstname, Lastname, Number) VALUES ('$name', '$lastname', '$number')
Finally, it is crucial that you sanitise your inputs:
$name = mysql_real_escape_string($_GET["name"]);
Thanks to this you avoid an SQL Injection attack.
You are overwriting $sql string each time.
Perhaps you meant to use the .= to append all three queries together. What is the structure for database tables?
$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql .= "insert into $DB_Table (Lastname) values('$lastname');";
$sql .= "insert into $DB_Table (Number) values('$number');";
That is because you use the same variable name ($sql) for all 3 queries. Use $sql1, $sql2 and $sql3 instead. Also, call mysql_query for each one (but only if you've set it).
Like this:
$sql1 = "insert into $DB_Table (Firtname) values('$name');";
$sql2 = "insert into $DB_Table (Lastname) values('$lastname');";
$sql3 = "insert into $DB_Table (Number) values('$number');";
if (isset ($sql1))
{
$res1 = mysql_query($sql1,$con) or die(mysql_error());
}
if (isset ($sql2))
{
$res2 = mysql_query($sql2,$con) or die(mysql_error());
}
if (isset ($sql3))
{
$res3 = mysql_query($sql3,$con) or die(mysql_error());
}