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
}
Related
in there i want to make update and create on one condition,so when I create a new record, automatically update my Data if have i success make new.
here my PHP :
<?php
require "dbconnection.php";
$a = array();
$a['transidmerchant'] = $_POST['TRANSIDMERCHANT'];
$a['totalamount'] =$_POST['AMOUNT'];
$a['words'] = $_POST['WORDS'];
$a['payment_channel'] = $_POST['PAYMENTCHANNEL'];
$a['session_id'] = $_POST['SESSIONID'];
$a['payment_date_time'] = $_POST['REQUESTDATETIME'];
$a['trxstatus'] = 'Requested';
$query = "INSERT INTO doku (transidmerchant,totalamount,words,payment_channel,session_id,payment_date_time,trxstatus)
VALUES ('$_POST[TRANSIDMERCHANT]','$_POST[AMOUNT]','$_POST[WORDS]','$_POST[PAYMENTCHANNEL]','$_POST[SESSIONID]','$_POST[REQUESTDATETIME]','Requested')";
$sql = "UPDATE orders SET status='Paid' where id='$_POST[TRANSIDMERCHANT]'";
if(mysqli_query($con,$query)) {
mysqli_connect($con,$sql);
echo 1;
}else{
echo("Error description: " . mysqli_error($con));
}
my query : $query and $sql
i want my $sql its update when $query is success create
if (mysqli_query($con, $query) === true) {
mysqli_query($con, $sql);
echo 1;
} else {
echo('Error description: ' . mysqli_error($con));
}
Create a stored procedure for insert then update. You may want to do something like this to get you away from issuing regular queries checking sub-queries and move you to creating a stored procedure.
Create your procedure to something similar below and run it in your sql dialog. Once you're done, run it:
DELIMITER //
CREATE PROCEDURE Payment
(
a_transidmerchant int,
a_atotalamount float,
a_words varchar(200),
a_payment_channel varchar(200),
a_session_id int,
a_payment_date_time datetime,
etc...
)
BEGIN
insert into doku(field_name1, field_name2, field_name3, field_name4) values(a_field1, a_field2, a_field3, a_field4);
END //
DELIMITER;
Now, in your php file, do the following:
if(isset($_POST[transidmerchantid])) /**** start a post check ****/
//before you touch the db
{
$con = mysqli_connect("localhost","user","pass","database");
//start defining variables
$transidmerchantid = $_POST[name];
$totalamount = $_POST[course];
$words = $_POST[words];
//calling stored procedure - call values for parameters in stored procedure
$sql = "CALL Payment('$transidmerchantid','$totalamount','$words')"; // <----
//in the order of operation, meaning once you have inserted the data,
//you can update the table. you're automatically updating the table row
//based on a successful insert, which is after calling the insert row
//stored procedure.
$result = mysqli_query($con,$sql);
if($result) //insert successful.
echo "Record Added Successfully!";
$sql = "UPDATE orders SET status='Paid' where id='$_POST[TRANSIDMERCHANT]'";
mysqli_query($con,$query);
}else{
echo("Error description: " . mysqli_error($con));
}else{
echo "Record Not added!"; //insert unsuccessful.
}
} /**** end post check ****/
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 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']."'";
simply put my code doesn't seem to be working probably the variables work and echo out its simply the code for insert im doing wrong no error just doesnt insert into the table.. the idea is that it inserts in to a table and replaces the data already in the id selected
if(($_REQUEST['questionbox']=="" )||($_REQUEST['boxA']=="")|| ($_REQUEST['boxB']=="")|| ($_REQUEST['boxC']=="")|| ($_REQUEST['boxD']=="")|| ($_REQUEST['correctbox']==""))
{
echo "must enter data";
}else{
$sql2 = "INSERT INTO `tblas`(`id`, `question`, `A`, `B`, `C`, `D`, `correct`) VALUES ([".$idbox."],[".$questionbox."],[".$boxA."],[".$boxB."],[".$boxC."],[".$boxD."],[".$correctbox."])";
$editquery= mysql_query($sql2, $db);
echo $editquery;
try this query instead of insert query
if(($_REQUEST['questionbox']=="" )||($_REQUEST['boxA']=="")|| ($_REQUEST['boxB']=="")|| ($_REQUEST['boxC']=="")|| ($_REQUEST['boxD']=="")|| ($_REQUEST['correctbox']==""))
{
echo "must enter data";
}else{
$sql2 = "UPDATE tblas SET id='".$idbox."', question = '".$questionbox."', A = '".$boxA."', B = '".$boxB."' ,C = '".$boxC."', D= '".$boxD."' , correct= '".$correctbox."'";
}
echo $editquery;
I'm trying to create a function for my forum that will increment my user's "Posts" attribute by 1. For whatever reason, the following PHP does not work.
function postCountIncrease($username) {
//get the connection variable
global $con;
//change to the users database (this function works correctly)
sqlconnect_users();
//get current post number (this is also working)
$getCurrentPosts = "SELECT Posts\n"
. "FROM users\n"
. "WHERE Username='".$username."'";
$query1 = mysqli_query($con, $getCurrentPosts) or die(mysqli_error($con));
$currentPosts = mysqli_fetch_array($query1);
//here is the problematic post. Assume that $username is a valid value, and that I've already done mysqli_real_escape_string() on it
$incrementPostsQuery = "UPDATE users.users SET Posts=". $currentPosts[0]+1 ." WHERE Username='". $username ."'";
$query2 = mysqli_query($con, $incrementPostsQuery) or die(mysqli_error($con));
//return the result
$result = mysqli_fetch_array($query2);
return $result;
}
I honestly don't see what I'm doing wrong, because the SQL works fine. If I use UPDATE users.users SET Posts=1 WHERE Username='Lampitosgames' in the console, it works with no errors. Help is much appriciated. Also, here is the error it is throwing at me:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 WHERE Username='Lampitosgames''
You can not concatenate that way "toto ".$var+1, you have to surround with brackets "toto ".($var+1)
In your case, this is declaration of var $incrementPostsQuery which fails
Look at your errors, your syntax is off
$getCurrentPosts = "SELECT Posts
FROM users
WHERE Username='$username'";
The error is in the building of your query.
$incrementPostsQuery = "UPDATE users.users SET Posts=". $currentPosts[0]+1 ." WHERE Username='". $username ."'";
I'll suggest you some tips to create query like this:
"update table set field = value"; // you can write the value directly
"update table set field = ". $value; // easy
"update table set field = ". ($a+$b); // ...
"update table set field = {$value}"; // you can add a variable with curly braces
"update table set field = {$va[3]}"; // more compless way
"update table set field = {$a->b}"; // an object field