php mysql update non-existent record - php

I use this piece of php to insert/update mysql db. Please see my question in the comment part at corresponding lines. Thanks.
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db($dbname);
arr = array();
if (strcasecmp($actionIn, 'insert') == 0) {
$query = "INSERT INTO $usertable (id, fname, lname) VALUES ('$id', '$fname', 'lname'";
$result = mysql_query($query) or die(mysql_error()); //AT THIS STEP, I would get error message if I insert a duplicated id into table, no following json_encode would not print out, that's what I want.
if ($result) {
$arr['inserted'] = 'true';
}
exit(json_encode($arr));
}
if (strcasecmp($actionIn, 'update') == 0) {
$query = "UPDATE $usertable SET id = '$id', fname = '$fname', lname = '$lname' WHERE id = '$id'";
$result = mysql_query($query) or die(mysql_error()); //AT THIS STEP, if I update a non-existent id, I don't get error, and the following steps continue to execute. I want the error info or return me a false.
if ($result) {
$arr['updated'] = 'true';
}
exit(json_encode($arr));
}
I also tried these, but both num_rows and affected_rows return 0. why?
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
$aff_cnt = $result->affected_rows;
printf("Result set aff %d rows.\n", $aff_cnt);
Thanks for your help!

If UPDATE doesn't match anything to update it will simply return. This is not an error. To find out whether it's updated anything use mysql_affected_rows().
Note: mysql_*() doesn't support the OOP form, so you should use mysql_affected_rows(), which should work for your second case above.
This will give you:
if (strcasecmp($actionIn, 'update') == 0) {
$query = "UPDATE $usertable SET id = '$id', fname = '$fname', lname = '$lname' WHERE id = '$id'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_affected_rows() !== 0) {
$arr['updated'] = 'true';
}
Side note: mysql_*() is deprecated and will be removed. You should use mysqli or PDO for new code.

Related

How to insert or update foreign key values using PHP

I did 2 tables in mysql database
user_details
bank_details
In user_details am create following entity
user_id as a Primary Key
username
password
address
In bank_details am create following entity
id as a Primary Key
user_id as a Foreign Key
bank_name
ac_no
First am insert user details using following code
<?php
$un = $_POST['un'];
$ps = $_POST['ps'];
$adr = $_POST['adr'];
$sql = mysql_query("insert into user_details username='$un', password='$ps', address='$adr'");
?>
Now i need to insert Bank Details in bank_details table
<?php
$bn = $_POST['bn'];
$ac_no = $_POST['ac'];
$sql = mysql_query("insert into bank_details user_id= ?? bank_name='$bn', ac_no='$ac_no'");
?>
How can i define that foreign key values here ?
Your query omits the MYSQL SET keyword. Anyway, you can do this, as per your code convention:
<?php
$mysql = mysql_connect([...]
$un = mysql_real_escape_string($_POST['un'], $mysql);
$ps = mysql_real_escape_string($_POST['ps'], $mysql);
$adr = mysql_real_escape_string($_POST['adr'], $mysql);
$sql = mysql_query("insert into user_details SET username='$un', password='$ps', address='$adr'", $mysql);
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
else
{
$user_id = mysql_insert_id(); //get the id of the last inserted query/user
$bn = mysql_real_escape_string($_POST['bn'], $mysql);
$ac_no = mysql_real_escape_string($_POST['ac'], $mysql);
$sql = mysql_query("insert into bank_details SET user_id = $user_id, bank_name='$bn', ac_no='$ac_no'", $mysql);
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
}
?>
I must point out, however, that using the mysql_* family of functions is deprecated, and you should seriously start using mysqli_* functions instead.
UPDATE:
As Per CodeGodie's suggestion, here's the re-written code using mysqli_* functions:
<?php
$mysqli = mysqli_connect(SERVER_NAME, USER_NAME, PASSWORD, DB_NAME);
$un = mysqli_real_escape_string($_POST['un']);
$ps = mysqli_real_escape_string($_POST['ps']);
$adr = mysqli_real_escape_string($_POST['adr']);
$sql = mysqli_query($mysqli, "insert into user_details SET username='$un', password='$ps', address='$adr'");
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
else
{
$user_id = mysqli_insert_id($mysqli); //get the id of the last inserted query/user
$bn = mysqli_real_escape_string($_POST['bn']);
$ac_no = mysqli_real_escape_string($_POST['ac']);
$sql = mysqli_query($mysqli, "insert into bank_details SET user_id = $user_id, bank_name='$bn', ac_no='$ac_no'");
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
}
?>

PHP MySQL inserting information from one form into multiple tables

So I have form1 that contains information from multiple tables in a database. I've got listboxes and textboxes within this form that have that information. So all I'm trying to do is insert whatever information the user submits back into the database and have it outputted on form2. I've got my INSERT INTOs on my output page. I know you can't use one INSERT INTO query, so I was wondering how to use multiple INSERTS and submit that information back into the database.
The variables created below come from the previous page and all of the values are there.
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
echo "New record created successfully";
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query = "select status_id from ostatus where status_type = '$ostatus'";
$result = mysqli_query($db, $query) or die("Error in SQL statement:" .mysqli_error());
$row = mysqli_fetch_array($result);
$statusid = $row[0];
$query1 = "insert into cust ('c_fname', 'c_lname') values ('$cfname', $clname)";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed ('e_fname', e_lname) values ('$efname', '$elname')";
$result2 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('{$oid}', '{$odate}', '{$statusid}')";
$result3 = mysqli_query($db, $query3);
}
First of all your query is vulnerable to SQL injection. I am not going to fix that.
Second, you should Google how to handle forms properly. And you should consider starting SQL transaction if you really care about the data to go into all the tables for sure.
Third, you should be able to use multiple inserts like you are doing in your code. but you need to correct your syntax errors.
Try this code (I also removed the select code are based on your question it is not needed)
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query1 = "insert into cust (c_fname, c_lname) values ('".$cfname."', '".$clname."')";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed (e_fname, e_lname) values ('".$efname."', '".$elname."')";
$result2 = mysqli_query($db, $query2) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('".$oid."', '".$odate."', '".$statusid."')";
$result3 = mysqli_query($db, $query3);
if($result1 && $result2 && $result3)
echo 'New record created successfully';
else
echo 'something did not work';
}

verifying and inserting details into db

I need to insert the details (name, id , number )of many documents into database if they are not already existing and if they exist i just need to do a update for any changed information. I have arrived at the following code but it doesn't work. I am new to this and need help on this.
foreach($A->Documents -> Document as $Document)
{
$query = "SELECT * from table where id = '".$Document->id."'";
$outcome = mysql_query($query) or die(mysql_error());
if(($outcome)&&(mysql_num_rows($result)>0)){
echo "Document already available" ;
while($row = mysql_fetch_object($outcome)){
if(!($outcome->name == $document->name)){
$update= "UPDATE table SET name= '.$Document->Name.'";
mysql_query($update) or die(mysql_error());
}
else
{
$insert= "INSERT table SET name= '.$Document->Name.'";
mysql_query($update) or die(mysql_error());
}
}
}
}
Use $row->name instead of $outcome->name. and your INSERT statement is wrong.
while($row = mysql_fetch_object($outcome)){
if(!($row->name == $document->name)){
$update = "UPDATE table SET name ='".$Document->Name."' WHERE id = ".$Document->id;
mysql_query($update) or die(mysql_error());
}
else {
$insert = "INSERT INTO table (name) VALUES('".$Document->Name."')";
mysql_query($insert) or die(mysql_error()); // $insert not $update
}
}
Note: Stop using mysql_* functions! Use PDO or mysqli_* instead. And use prepared statements
Change the
mysql_query($update) or die(mysql_error());
To:
$insert = INSERT into table_name values(" values");
mysql_query($insert) or die(mysql_error());
in the else condition
Issue is with $result variable with in if statement
( if(($outcome)&&(mysql_num_rows($result)>0)){)
It should be $outcome because you initialized query output to $outcome variable
First of, dont yse mysql_ functions. Read the docs (read the warning).
use mysqli or PDO instead.
Then, your INSERT statement is wrong.
INSERT INTO table (col1) VALUES (value_for_col1);

PHP mysql refresh select data

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.

php mysql query not executing correctly

I have a weird problem with my sql script.
I have a string
$query = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message)
VALUES ('93361357', '2162', '27761144734', 'Hoekom');";
But when I execute that string it inserts it to the table but eventid stays 0, if I run that exact command in cmd it works perfectly?
Any ideas why this is not inserting all the values?
Edit Full code
<?php session_start();
$link = mysql_connect("localhost", "username", "password"); //removed u and p for posting
if (!$link)
die("Couldn't connect to MySQL");
mysql_select_db("db", $link) //removed db name for posting
or die ("Couldn't open smss:" . mysql_error());
$id = $_SESSION['id'];
$message = $_REQUEST['promo_message'];
$timeToSend = $_REQUEST['timeToSend'];
$dateToSend = $_REQUEST['dateToSend'];
if(isset($_REQUEST['input_cell']))
{
$receiver = $_REQUEST['input_cell'];
if($receiver != '')
{
$response_string = sendSMSPortalSchedule($message, $receiver, $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
$query1 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message');";
mysql_query($query1);
echo mysql_error();
}
}
if(isset($_REQUEST['single_cell']))
{
$receiver = $_REQUEST['single_cell'];
if($receiver != 'none')
{
$response_string = sendSMSPortalSchedule($message, $receiver, $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
$query2 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message');";
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
mysql_query($query2);
echo mysql_error();
}
}
if(isset($_REQUEST['sento_group']))
{
$array = $_REQUEST['sento_group'];
foreach($array as $receiver)
{
if($receiver != 'none')
{
$query = 'SELECT cell_number FROM cell_groups WHERE group_id ="'.$receiver.'"';
$result2 = mysql_query($query) or die('Fail');
while($row=mysql_fetch_array($result2))
{
$response_string = sendSMSPortalSchedule($message, $row['cell_number'], $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
$to = $row['cell_number'];
$query3 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$to', '$message');";
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
mysql_query($query3);
echo mysql_error();
}
}
}
}
}
This is the table
id = INT
eventid = BIGINT(20)
bus_id = INT
cell_num = VARCHAR
sms_message = VARCHAR
The SQL command itself is correct. The problem must be elsewhere.
Firstly, are you sure that the values of your parameters are correct? Try outputting the query after variable interpolation to see if it is correct:
$query1 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message')";
echo $query1;
Seondly I notice that in you have INSERTs in multiple places. Make sure all of them work as expected. Remember that the one you think is executing may be different from the one that is actually executing.
I found the problem, the service I was using got changed to return XML where it usually just returned an integer, this caused me to try and insert XML into my BIGINT field, which is not possible. So in the end the problem was caused by an updated service that didn't notify clients about changes.

Categories