I'm trying to convert a previous line I had where I was calling something back from the database, and insert it instead.
This is the function I have, but I can't get the INSERT INTO to work correctly
I've already debugged that: the connection to the DB is working fine, the session var for user is set and that the $avatarID is present.
if(!empty($_SESSION['user'])){
$avatarID = $_POST['avatarID'];
$avatarID = mysql_real_escape_string(trim($_POST['avatarID']));
// Insert into DB
$sql = "INSERT INTO `users` (`avatar`) VALUES ('{$avatarID}') WHERE `username` = '".$_SESSION['user']."'";
$query = mysql_query($sql);
if($query === false){
return false;
}else{
return true;
}
header('Location: profile.php');
}
I think it's an issue with the $sql line. I'm not getting any errors other than a simple blankpage/dead screen.
Attempted changing to just the following:
// Insert into DB
$query = mysql_query("INSERT INTO `user` (`avatar`) VALUES ('{$avatarID}'") or die(mysql_error());
Edit OK so I realise the mistake I have made, as this should be an UPDATE WHERE not INSERT INTO. But I am still struggling to get the query details correct even when using UPDATE and WHERE. But still no result:
<?php session_start();
require 'connect.php';
if(!empty($_SESSION['user'])){
$avatarID = $_POST['avatarID'];
$avatarID = mysql_real_escape_string(trim($_POST['avatarID']));
// Insert into DB
$sql = "UPDATE `users` SET `avatar`='{$avatarID}' WHERE `username` = '".$_SESSION['user']."'";
$query = mysql_query($sql);
if($query === false){
return false;
}else{
return true;
}
header('Location: profile.php');
}else{
header('Location: choose-avatar.php');
}
?>
Use UPDATE instead of INSERT
$sql = "UPDATE `users` SET `avatar`='{$avatarID}' WHERE `username` = '".$_SESSION['user']."'";
Related
I've seen a few posts dealing with UPDATE statements in MySQL, but none of them seem to apply to my specific situation.
I have the following code:
$result = "SELECT iso_date FROM open_lab_report WHERE iso_date = current_timestamp";
if(!mysqli_query($link, $result)) {
$sql = "INSERT INTO open_lab_report (iso_date, lab_monitor, incidentReport) VALUES (current_timestamp, '$lab_monitor', 1)";
}else{
$sql = "UPDATE open_lab_report SET incidentReport = 1 WHERE iso_date = current_timestamp";
}
if(!mysqli_query($link, $sql)) {
echo "Query failed, code: " . mysqli_errno($link);
}
Essentially, I'm trying to check to see if an entry exists. If it exists, then update it. If the entry doesn't exist, then make it.
The INSERT statement executes perfectly. However, the UPDATE statement does nothing. There is no error message, and no changes made in my table.
Any ideas?
Thanks!
As Forbs stated, your UPDATE statement will not result in any changes since you are filtering based on "current_timestamp", which will be whatever time the query executes. What you need to do instead is pass an existing timestamp into your code so that it updates whatever existing record already has that as its iso_date.
See the example below for how you can change your code.
//this is whatever your time is that you are looking for a record for
$isoDateDT = '2018-08-01 08:15:00';//human readable datetime
$isoDateTS = strtotime($isoDateDT);//unix timestamp
$result = "SELECT * FROM open_lab_report WHERE iso_date = $isoDateTS";
if(!mysqli_query($link, $result)) {
$sql = "INSERT INTO open_lab_report (iso_date, lab_monitor, incidentReport) VALUES ($isoDateTS, '$lab_monitor', 1)";
} else {
$sql = "UPDATE open_lab_report SET incidentReport = 1 WHERE iso_date = $isoDateTS";
}
if(!mysqli_query($link, $sql)) {
echo "Query failed, code: " . mysqli_errno($link);
}
You have to correct your if statement checking.
In your Case you can count number of entries with same timestamp as current timestamp.
and then
if count<1 then you can UPDATE ,otherwise INSERT.
EXAMPLE:
$result = "SELECT iso_date FROM open_lab_report WHERE iso_date = current_timestamp";
$row=mysqli_num_rows(mysqli_query($link, $result))
if($row<1){
$sql = "INSERT INTO open_lab_report (iso_date, lab_monitor, incidentReport) VALUES (current_timestamp, '$lab_monitor', 1)";
}else{
$sql = "UPDATE open_lab_report SET incidentReport = 1 WHERE iso_date = current_timestamp";
}
if(!mysqli_query($link, $sql)) {
echo "Query failed, code: " . mysqli_errno($link);
}
I want to make toefl test. I make table score_structure in database containing 4 columns (email, right, false, score). If the user has done on previous test and will perform a test again, then the user data will be updated according to the user's email pitch.
I have tried but failed, the data will not update. Please help me.
This is structure.php
<?php
$email = $_SESSION['email'];
$cek = mysql_num_rows(mysql_query("SELECT email FROM score_structure WHERE email='$email'"));
if($cek > 0 ) {
$simpan = "UPDATE score_structure SET right='$right', false='$false', score='$score' WHERE email='$email'";
if(mysql_query($simpan)) {
header("location:test_listening.php");
} else {
echo mysql_error();
} else {
$simpan = "INSERT INTO score_structure VALUES ('$email', '$right', '$false', '$score')";
if(mysql_query($simpan)) {
header("location:test_listening.php");
} else {
echo mysql_error();
}
}
?>
Update your update query & let us know the feedback:
$simpan = "UPDATE score_structure SET `right`='$right', `false`='$false', `score`='$score' WHERE email='$email'";
Also currently mysql_() are depreciated so use mysqli_()
When I change SELECT * to SELECT count(*) the script stops working altogether. How to I add a count(*) to this file and a statement if row count for $user >= 20 allow to INSERT else do nothing.
// Include needed files
include 'mysql.php';
// Connect to MySQL
connectMySQL();
//****** SECURITY CHECK *********
session_start();
if(isset($_SESSION['userid'])){
$user = mysql_real_escape_string($_SESSION['userid']);
//*******************************
// Retrieves variables through AJAX
$favid = mysql_real_escape_string($_GET['favid']);
// $favid = mysql_real_escape_string($_GET['favid']);
// Firstly, check if article is favourite or not
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
$matches = mysql_num_rows($query);
// If it is not favourited, add as favourite
if($matches == '0'){
mysql_query("INSERT INTO ajaxfavourites (user, favid, exptime) VALUES ('$user', '$favid', CURRENT_TIMESTAMP)");
echo "";
}
// Instead, if it is favourited, then remove from favourites
if($matches != '0'){
mysql_query("DELETE FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
echo "";
}
} else {
// Someone tries to directly access the file!
echo "Invalid session!";
}
Thanks!
Please do necessary steps to avoid SQL injection, also try using mysqli_* functions instead of mysql_* functions
$query = mysql_query("SELECT COUNT(*) as cnt FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
$res = mysql_fetch_array($query);
// If it is not favourited, add as favourite
if($res[cnt] == 0){
mysql_query("INSERT INTO ajaxfavourites (user, favid, exptime) VALUES ('$user', '$favid', CURRENT_TIMESTAMP)");
echo "";
}
// Instead, if it is favourited, then remove from favourites
if($res[cnt] > 0){
mysql_query("DELETE FROM ajaxfavourites WHERE user='$user' AND favid='$favid'");
echo "";
}
I got it resolved. The reason it wasn't working was it took both values into consideration ($user and $favid). As a result it was always either 0 or 1.
I had to create another mysql query with just one value in it ($user) and then I was able to get the row count. Thanks everyone!
try to use below query, using below query if requested user's session will be 20+ then only insert statement will execute else insert statement will be ignore.
INSERT INTO ajaxfavourites(USER,favid ,exptime)
SELECT 1 AS USER, 1 AS favid, NOW() AS exptime
FROM ajaxfavourites WHERE USER=1 HAVING COUNT(*) >=20;
I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.
I'm new to sql database. I'm using the update statement to modify a value in my column. All my columns are of type char, but I'm not able to modify the column. Please point out what mistake I'm making
if ($info['Patient'] === '' )
{
UPDATE guestbook SET Message = 'howdy' WHERE Name = 'mathilda';
$sql = "INSERT INTO guestbook(Name)VALUES('$patient')";
$result=mysql_query($sql);
//check if query successful
if($result){
echo "Successful";
echo "<BR />";
}
else {
echo "ERROR";
}
The rest of the code is working fine and the Insert statement is working good whereas I c an't get the update statement to modify the table.
Since you appear to be calling this from PHP you need to use the mysql_query method to execute the update statement like so:
$sql = "UPDATE guestbook SET Message = 'howdy' WHERE Name = 'mathilda'";
mysql_query($sql);
Replace
UPDATE guestbook SET Message = 'howdy' WHERE Name = 'mathilda';
$sql = "INSERT INTO guestbook(Name)VALUES('$patient')";
with
$sql = "UPDATE guestbook SET Message = 'howdy' WHERE Name = 'mathilda'";
You need to use mysql_query() for your update statement as well...
$update = "UPDATE guestbook SET Message = 'howdy' WHERE Name = 'mathilda'";
mysql_query($update);
$sql = " UPDATE guestbook SET Message = 'howdy' WHERE Name = 'mathilda' ";
if(mysql_query($sql)){
// true
}