Update row if there is a value or insert if not - php

I have a form where the user inserts data but they can go back to the same page to edit their information. My table structure is:
id (auto int index),
user id (links to other tables),
Doc_Name,
Abstract
I have an insert query:
$user_id = intval($_SESSION['user_id']);
$Doc_Name = mysql_real_escape_string($_POST['Doc_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
$the_query = sprintf("INSERT INTO `document` (`user_id`,`Doc_Name`,`abstract`) VALUES
('%d','%s','%s')", $user_id, $Doc_Name, $abstract);
However, if their is already a row for this user_id then I want the update query instead:
mysql_query("UPDATE document SET `Doc_Name` = '$Doc_Name', 'abstract='$abstract'
WHERE id='$_SESSION[user_id]'") or die(mysql_error());
Also, so the user knows what they entered, I tried to use this echo in the text box but that didn't work either,
<textarea name="Doc_Name" style="width:500px; height:150px" type="text" id="Doc_Name"
value="<? echo $row_settings['Doc_Name']; ?>" size="300"> </textarea>

You can use INSERT ... ON DUPLICATE KEY UPDATE Syntax
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE
c=c+1;

You want the INSERT ... ON DUPLICATE UPDATE syntax

for the textarea you can use
<textarea name="Doc_Name" style="width:500px; height:150px" type="text" id="Doc_Name" size="300"><? echo $row_settings['Doc_Name']; ?></textarea>
everything between the tags is displayed and editable
EDIT: to the other posters: nice, did not know INSERT ON DUPLICATE

the query:
SELECT * FROM document WHERE id='{$SESSION['user_id']}'
php:
if(mysql_num_rows(mysql_query($query)) > 0) {
//code to be executed if id exists
}

Related

Problem with query to update foreign key column

I am working on a cms for properties/ads in oop php for learning purposes. I have three tables that are connected with pivot table.
photos (id, name, extension),
property_photo (id, property_id, photo_id),
properties (id, title, description, main_photo_id)
I have a gallery of photos for every property and I am trying to be able to insert main photo (one of existing photos in gallery) for each property through foreign key (main_photo_id) and display that photo on a different page. I am having trouble writing function (query) in model. Any help is much appreciated. Here is some of my code:
AdModel:
public function MainPhotoInsert($id)
{
$this->db->query('INSERT INTO properties (main_photo_id) VALUES (:main_photo_id) SELECT id FROM PHOTOS WHERE id = :id LIMIT 1');
$this->db->bind(':id', $id);
$row = $this->db->single();
return $row;
}
AdsController:
public function galleryAction()
{
if (!isset($_GET['id'])) {
$photo_id = $_SESSION['photo_id'];
} else {
$photo_id = $_GET['id'];
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if(isset($_POST['radio']))
{
$this->AdModel->MainPhotoInsert($photo_id);
redirect('ads/index');
}
}
$data = $this->AdModel->getPhotosForProperty($photo_id);
$data1 = $this->AdModel->MainPhotoData($photo_id);
$this->view->render('ads/gallery', $data, $data1);
}
gallery.php:
<form action="/ads/gallery?id=<?php echo $_GET['id']; ?>" method="POST">
<?php foreach ($data as $key => $value) : ?>
<img src="<?php echo '/public/photos/'.$value->name.'.'.$value->extension ?>" class="img-fluid img-thumbnail" width="250" height="250">
<input type="radio" name="radio" value="<?php echo $value->photo_id; ?>" >Make main
<br>
<?php endforeach; ?>
<br>
<br>
<button type="submit" name="submit" value="submit" class="btn btn-success form-control">Submit</button>
</form>
You shouldn't have a select clause in your insert statement (at least not for what you are trying to do). IF you only ever need to set it once then you need to tweak the query to include the other two values (title and description) or they will always be blank. It should end up looking something like this:
INSERT INTO properties (main_photo_id, title, description) VALUES (:main_photo_id, : title, : description)
More likely, you want an upsert (update if a relevant row already exists, insert if one doesn't). In MySQL the syntax is insert ... on duplicate key update. This means you are going to need a primary key on the properties table (it's unclear if you already have one). The syntax is pretty similar to the insert above but without knowing the exact structure of the table I can't give you the exact query.
Update:
The on duplicate key syntax would look something like this (it depends on how you have your primary key set up on the table, e.g. if main_photo_id is the primary key then this likely won't work):
INSERT INTO properties
(id, main_photo_id, title, description)
VALUES
(:id, :main_photo_id, : title, : description)
ON DUPLICATE KEY UPDATE
main_photo_id = :main_photo_id,
title = :title,
description = :description
Side note:
gallery.php is also going to produce a separate HTML form for each image with one radio button on the form which isn't really what you want. You should move the form to wrap around the entire foreach loop so that you have one form. Then you should put the image ID as the value for the radio button.

How to insert row id to another table field using php mysql?

I have first table name is conference.
I want to insert table conference row id (81) to another second table name conf_dates
and that have field conf_id use for save conference row id
The issue is that value is empty insert in second table conf_dates as shown in second table image
Here is php code
<?php
$id = $_GET["id"];
$trans = array("strtdate"=>$strtdate,"enddate"=>$enddate,"conf_id"=>$id);
$query = $db->insert($trans,PREFIX."conf_dates");
?>
Here is html code
<p>
<label>Conference ID</label>
<input name="conf_id" class="text-input medium-input" type="text" id="conf_id" value="" />
</p>
Please tell me how to insert row id to another table field?
what are the values of $strtdate, $enddate
Also please share the table structure of "conf_dates" .
$id = intval($_GET["id"]);
check you are getting correct types, and values for variables you trying to insert
You named the input field conf_id while you try to insert $_GET['id'].
You should insert $_GET['conf_id']` instead.

prevent insert data to database if specific atribute already exist

I want to prevent duplicate values into a database table from a form using PHP.
I have a table data on database that have atribute dataid(auto increment as primary key), data1, data2.
And I have a simple form like this
<h2>Enter your data</h2>
<form action="script.php" method="post">
Data 1:<input type="text" name="data1" /></p>
Data 2:<textarea name="data2"></textarea></p>
<input type="submit" name="submit" value="Add Data" />
</form>
It's script.php for inserting data to database
<?php
if(isset($_POST['submit']))
{
//connect to the database
$conn = mysql_connect('host', 'username', 'password', 'dbname') or die(mysql_error());
//insert results from the form input
$query = "INSERT INTO data(data1, data2) VALUES('$_POST[data1]', '$_POST[data2]')";
$result = mysql_query($conn, $query) or die(mysql_error());
}
?>
but it will insert any data from the form to database.
How can I prevent insert data to database if data1 already exist?
The solution to your problem is to make the column unique so the database takes care of enforcing this constraint. You can do this by creating a unique index or constraint:
alter table data add constraint unq_data_data1 unique (data1);
You can then use this in an insert to ignore duplicates by using on duplicate key update:
INSERT INTO data(data1, data2)
VALUES('$_POST[data1]', '$_POST[data2]')
ON DUPLICATE KEY UPDATE data1 = VALUES(data1);
The ON DUPLICATE KEY part doesn't really do anything. It is a no-op.
Also, you should parameterize your queries, so you are not subject to SQL injection and so the query plans can be cached. But that is another matter.
make column data1 unique
ALTER TABLE `data` ADD UNIQUE (`data1`);
change your query like this to ignore insert when data exist
$query = "INSERT IGNORE INTO data(data1, data2) VALUES('$_POST[data1]', '$_POST[data2]')";

how to i make a form update page to update database table records, but with multiple records at the same time?

i have a table like this:
id product_category product_name product_range discount_amt
---------------------------------------------------------------------------
1 Post Card 4x6 5M to 9,999 0.007
2 Post Card 4x6 10M to 14,999 0.01
3 Post Card 4x6 15M to 19,999 0.013
4 Post Card 4x6 20M to 24,999 0.015
5 Post Card 4x6 Over 25M 0.019
i'm calling just the discount_amt column into page like this:
$pricediscountquery = mysql_query("SELECT * FROM pricing_discount") or die(mysql_error());
$i=0;
while($pricingdiscountrow = mysql_fetch_array( $pricediscountquery )) {
$pricingdiscountarray[$i++]=$pricingdiscountrow['discount_amt'];
}
i'm displaying form fields and discount amounts prefilled in the values of the form fields like this:
<p>5M to 9,999: <input type="text" name="pc_4x6_5m_to_9999" value="<?php echo $pricingdiscountarray[0]; ?>" /></p>
<p>10M to 14,999: <input type="text" name="pc_4x6_10m_to_14999" value="<?php echo $pricingdiscountarray[1]; ?>" /></p>
<p>15M to 19,999: <input type="text" name="pc_4x6_15m_to_19999" value="<?php echo $pricingdiscountarray[2]; ?>" /></p>
<p>20M to 24,999: <input type="text" name="pc_4x6_20m_to_24999" value="<?php echo $pricingdiscountarray[3]; ?>" /></p>
<p>Over 25M: <input type="text" name="pc_4x6_over_25m" value="<?php echo $pricingdiscountarray[4]; ?>" /></p>
i'm creating my post variables like this:
$pc_4x6_5m_to_9999 = mysql_real_escape_string(htmlspecialchars($_POST['pc_4x6_5m_to_9999']));
$pc_4x6_10m_to_14999 = mysql_real_escape_string(htmlspecialchars($_POST['pc_4x6_10m_to_14999']));
$pc_4x6_15m_to_19999 = mysql_real_escape_string(htmlspecialchars($_POST['pc_4x6_15m_to_19999']));
$pc_4x6_20m_to_24999 = mysql_real_escape_string(htmlspecialchars($_POST['pc_4x6_20m_to_24999']));
$pc_4x6_over_25m = mysql_real_escape_string(htmlspecialchars($_POST['pc_4x6_over_25m']));
i'm trying to update multiple rows/records at the same time, just in the discount_amt column like this:
mysql_query("INSERT INTO pricing_discount (id,discount_amt) VALUES (1,$pc_4x6_5m_to_9999),(2,$pc_4x6_10m_to_14999),(3,$pc_4x6_15m_to_19999),(4,$pc_4x6_20m_to_24999),(5,$pc_4x6_over_25m) ON DUPLICATE KEY UPDATE discount_amt=VALUES(discount_amt); ") or die(mysql_error());
the one above doesn't create error in code, but it creates error on web page: 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 '),(2,),(3,),(4,),(5,) ON DUPLICATE KEY UPDATE discount_amt=VALUES(discount_amt)' at line 1
also tried this:
mysql_query("INSERT INTO pricing_discount (id,discount_amt) VALUES (1,'$pc_4x6_5m_to_9999'),(2,'$pc_4x6_10m_to_14999'),(3,'$pc_4x6_15m_to_19999'),(4,'$pc_4x6_20m_to_24999'),(5,'$pc_4x6_over_25m') ON DUPLICATE KEY UPDATE discount_amt=VALUES(discount_amt); ") or die(mysql_error());
this gave an error in code so i didn't even save it and try to run it:
mysql_query("INSERT INTO pricing_discount (id,discount_amt) VALUES (1,"$pc_4x6_5m_to_9999"),(2,"$pc_4x6_10m_to_14999"),(3,"$pc_4x6_15m_to_19999"),(4,"$pc_4x6_20m_to_24999"),(5,"$pc_4x6_over_25m") ON DUPLICATE KEY UPDATE discount_amt=VALUES(discount_amt); ") or die(mysql_error());
this also gave error in code:
mysql_query("INSERT INTO pricing_discount (id,"discount_amt") VALUES (1,"$pc_4x6_5m_to_9999"),(2,"$pc_4x6_10m_to_14999"),(3,"$pc_4x6_15m_to_19999"),(4,"$pc_4x6_20m_to_24999"),(5,"$pc_4x6_over_25m") ON DUPLICATE KEY UPDATE discount_amt=VALUES(discount_amt); ") or die(mysql_error());
if you hard code values like this it works, but i'm doing variables:
mysql_query("INSERT INTO pricing_discount (id,discount_amt) VALUES (1,1),(2,3),(3,3),(4,12),(5,12) ON DUPLICATE KEY UPDATE discount_amt=VALUES(discount_amt); ") or die(mysql_error());
what's the correct way to do this?
if you're wondering why i didn't do UPDATE instead of INSERT when trying to update records, it's because i was following this stackoverflow:
Multiple Updates in MySQL
I am assuming, in your table discount_amt will be float or double datatype. then below sql query qill work. for int, float, decimal or double datatype no need to add value between single quote'.
$query = "
INSERT INTO pricing_discount
(id
,discount_amt
) VALUES
(1,".$pc_4x6_5m_to_9999."),
(2,".$pc_4x6_10m_to_14999."),
(3,".$pc_4x6_15m_to_19999."),
(4,".$pc_4x6_20m_to_24999."),
(5,".$pc_4x6_over_25m.")
ON DUPLICATE KEY UPDATE discount_amt = VALUES(discount_amt);
";
mysql_query($query) or die(mysql_error());
Just to recap, what's wrong with this...
$query = "
INSERT INTO pricing_discount
(id
,discount_amt
) VALUES
(1,'$pc_4x6_5m_to_9999'),
(2,'$pc_4x6_10m_to_14999'),
(3,'$pc_4x6_15m_to_19999'),
(4,'$pc_4x6_20m_to_24999'),
(5,'$pc_4x6_over_25m')
ON DUPLICATE KEY UPDATE discount_amt = VALUES(discount_amt);
";
mysql_query($query) or die(mysql_error());

Get the id of current mysql insert

is there anyway to get the ID of the current record I am INSERTING into the database table using php with Mysql without having to do an extra select to get the last ID?
FOr example, if my table has these columns, id, url, name
and if url consists of the domain name and current id as the query variable ex:
domainname.com/page.php?id=current_id
$sql="INSERT INTO Persons (id, url, name )
VALUES
('domainname.com/page.php?id=".**whats_the_current_id**."','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
as far as I know, there is no 'clean' way to find the ID you are about to insert (from what I understand from your question, this is what you want to know).
Two options in my opinion, starting with the ugly one: select max(id) from Persons, increment it with one, and hope that no insert's will mess this up for you. Like I said, its ugly, and -not- reliable.
A better option would be to first insert the record with a dummy value for url, and then retrieving the just inserted row's ID with mysql_insert_id(). Then update that record with the correct url value.
You asked for a way to retrieve the id without a select query following the insert query, but like I said, I don't think this is possible.
i use mysql_insert_id() for that. it works fine.
// pseudo-ish code
$query = "INSERT something .... "
$updated = $db->run_query($query);
$id = mysql_insert_id();
your table should be like this
ID AUTO_INCREMENT
person_id VARCHAR
person_url ...
person_name ...
your post form something like
<form method="post">
<input type="hidden" name="id" value="<?php echo uniqid() ?>" />
...
</form>
the query should be like this:
$person_id = intval($_POST['id']);
$person_url = mysql_real_escape_string($_POST['url']);
$person_name = mysql_real_escape_string($_POST['name']);
mysql_query("INSERT INTO Persons (person_id, persno_url, person_name) VALUES ( {$person_id} , {$person_url}, {$person_name} )");
$ID = mysql_insert_id();
The current ID is in $_GET['id']. You should sanitize it before inserting it into your query:
$id = intval($_GET['id']);
Then, use $id in your query.
If you add classes around the first insert and then the second select. The select will work then.
<?php
class insert1{
function inserthere(){
***insert***
}
}
class select1{
function selecthere(){
***select***
}
}
$a = new insert1;
$a->inserthere();
$b = new select1;
$b->selecthere();
?>

Categories