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 ****/
Related
I have an auto incrementing ID called deviceID in one of my fields. I was wanting to pass this to a session in php to use later on and was planning on using scope_identity() as I understand that this is the best way to get the current Primary key ID. However anytime I have attempted to use it I have had a error message saying that it is an undefined function. Here is my code so without the scope_identity():
<?php
session_start();
include 'db.php';
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
$_SESSION["screenWidth"] = $screenWidth;
$_SESSION["screenHeight"] = $screenHeight;
if (isset($_POST['submit'])) {
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$phoneType = $_POST['phoneName'];
$HandUsed = $_POST['HandUsed'];
$_SESSION["HandUsed"] = $HandUsed;
$_SESSION["phoneName"] = $phoneType;
echo 'hello';
$sql = "
INSERT INTO DeviceInfo (DeviceID, screenWidth, phoneType, screenHeight, HandUsed)
VALUES ('$screenWidth','$phoneType', '$screenHeight', '$HandUsed')
SELECT SCOPE_IDENTITY() as DeviceID
";
if (sqlsrv_query($conn, $sql)) {
echo ($sql);
echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
}
?>
You need to fix some issues in your code:
The INSERT statement is wrong - you have five columns, but only four values in this statement. I assume, that DeviceID is an identity column, so remove this column from the column list.
Use parameteres in your statement. Function sqlsrv_query() does both statement preparation and statement execution, and can be used to execute parameterized queries.
Use SET NOCOUNT ON as first line in your statement to prevent SQL Server from passing the count of rows affected as part of the result set.
SCOPE_IDENTITY() is used correctly and it should return the expected ID. Of course, depending on the requirements, you may use IDENT_CURRENT().
The following example (based on the code in the question) is a working solution:
<?php
session_start();
include 'db.php';
if (isset($_POST['submit'])) {
$screenWidth = $_POST['screenWidth'];
$phoneType = $_POST['phoneName'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
$params = array($screenWidth, $phoneType, $screenHeight, $HandUsed);
$sql = "
SET NOCOUNT ON
INSERT INTO DeviceInfo (screenWidth, phoneType, screenHeight, HandUsed)
VALUES (?, ?, ?, ?)
SELECT SCOPE_IDENTITY() AS DeviceID
";
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
echo "Error: " . $sql . ": " . print_r(sqlsrv_errors());
exit;
}
echo "New record has been added successfully !";
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row["DeviceID"];
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
}
?>
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'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.
This is a code for a cafeteria, and this is the login.
<?php
$userna = 'root';
$paso = '';
$mach = 'localhost';
$db ='cafeteria';
session_start();
// GET PAGES RECORD FROM LOG TABLE: *********| Only the first time though:
if (isset($_SESSION['log']) != 'logging')
{
// Here, just creating a string:
$pages_record = "";
$insert_query = '';
// Get saved pages from the database:
$connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Error in log-page script: AB-1 - query: $insert_query." . mysqli_error($connection));
mysqli_select_db($connection,'cafeteria');
// Query string to pull all pages from table record:
$get_pages_query = "select * from log-page";
// Query the database, and save result:
$query_pages_result = mysqli_query($connection, $get_pages_query);
// Check number of results returned:
$num_of_results = '';
$num_of_results = mysql_num_rows($query_pages_result);
if ($num_of_results > 0)
{
// Loop through the result array: Each time, one row, and then the next one ...
for ($row = 0; $row < $num_of_results; $row++ )
{
// Getting one row:
$get_row = mysqli_fetch_array($query_pages_result);
// Extracting just the page name from the row:
$one_page = substr($get_row["page"],strripos($get_row["page"],"/") + 1);
// Adding this page name to the string created previously:
if ($row == 0)
{
$pages_record .= $one_page;
}
else
{
$pages_record .= ",".$one_page;
}
}
// Once all pages have been read and saved to the string
// now we save it to the session:
$_SESSION['logpages'] = $pages_record;
$_SESSION['log'] = 'logging'; // This just tells us, we are logging pages to the database.
}
else
{
// There are no pages in the table:
$_SESSION['logpages'] = "";
$_SESSION['log'] = 'logging'; // This just tells us, we are logging pages to the database.
}
}
// Check if page is already in session list.
$pages_array = array();
if (strlen(isset($_SESSION['logpages'])) > 0 )
{
// string variable that holds all pages separated by commas:
$pages_string = $_SESSION['logpages'];
// creating an Array to hold all pages already logged in server:
if (strstr($pages_string, ","))
{
$pages_array = explode(",", $pages_string);
}
else // just means there's only one page in the record
{
// so, we push it inside the array.
array_push($pages_array, $pages_string);
}
// current page: [ We are extracting only the page, not the entire url, Exmp: login.php ]
$current_page = substr($_SERVER['PHP_SELF'],strripos($_SERVER['PHP_SELF'],"/") + 1);
// Check if current_page is in the array already:
if (!in_array($current_page, $pages_array))
{
// IF is NOT in the array, then add it:
array_push($pages_array, $current_page);
// Add it to the Session variable too:
$pages_string = implode(",", $pages_array);
// Re-save it to SESSION:
$_SESSION['logpages'] = $pages_string;
// Now, add it to the database table "log-page""
$connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Unable to connect!");
mysqli_select_db($connection,'cafeteria');
// Query to insert page description into the table:
// [ date - time - page - user ]
$insert_query = "INSERT INTO log-page
(`date`, `time`, `page`, `user`) VALUES
('".date("Y-m-d")."', '".date("H:i:s")."', '".$_SERVER['PHP_SELF']."', '".(isset($_SESSION['SESSION_UNAME']))."')";
mysqli_select_db($connection,'cafeteria');
// INSERTING INTO DATABASE TABLE:
mysqli_query($connection, $insert_query) or die ("Error in log-page script: AB-2 - query: $insert_query." . mysqli_error($connection));
// Done!
}
else
{
// IF it IS in the list, just SKIP.
}
}
else
{
// means, that there are absolutely no pages saved in the database, basically this is the first log:
$_SESSION['logpages'] = substr($_SERVER['PHP_SELF'],strripos($_SERVER['PHP_SELF'],"/") + 1);
// Now, add it to the database table "log-page""
$connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Unable to connect!");
mysqli_select_db($connection,'cafeteria');
// Query to insert page description into the table:
// [ date - time - page - user ]
$insert_query = "INSERT INTO log-page
(date, time, page, user) VALUES
('".date("Y-m-d")."', '".date("H:i:s")."', '".$_SERVER['PHP_SELF']."', '".(isset($_SESSION['SESSION_UNAME']))."')";
mysqli_select_db($connection,'cafeteria');
// INSERTING INTO DATABASE TABLE:
mysqli_query($connection,$insert_query) or die ("Error in log-page script: AB-2 - query: $insert_query." . mysqli_error($connection));
// Done!
}
?>
But now i am getting this error:
Error in log-page script: AB-2 - query: INSERT INTO log-page (date,
time, page, user) VALUES ('2012-10-16', '16:58:44',
'/caf/pages/index.php', '').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 '-page (date, time, page, user)
VALUES ('2012-10-16', '16:58:44' at line 1
Im using Xampp 1.8.1 PHP: 5.4.7. It does not let me login neither as administrator nor as a cashier
Enclose the table name in backticks like this (rest of the query omitted):
$insert_query = "INSERT INTO `log-page` (`date`, `time`, `page`, `user`) ... ";
Otherwise MySQL will try to interpret the - as a minus sign, which fails in this case.
EDIT
IN the last insert shown, also the column names should be enclosed in backticks:
$insert_query = "INSERT INTO `log-page` (`date`, `time`, `page`, `user`) VALUES ...";
Try escaping field name
(`date`, `time`, `page`, `user`)
It's been a while since I looked at mySql docs, but it looks to be complaining about the table name "log-page". Try quoting that table name.
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
}