insert images in another table with foreign key - php

I have two tables in my db, telephones(id, title, price) and images(id, tp_id, photos) I went in the images table and put a foreign key on the tp_id column to match the id in the telephones table so that every image is linked to a telephone. But the problem is my images go into the table fine but the tp_id column always has the value of 0, what I am missing here? can somebody guide me? Thanks
PS: I know about the security vulnerability of my code I am just doing some test here!
<?php
if (isset($_POST['submit'])) {
include 'dbconnect.php';
for ($i = 0; $i < count($_FILES["photo"]["name"]); $i++) {
$target = "img/"; //This is the directory where images will be saved
$target_files = $target . basename($_FILES['photo']['name'][$i]); //This gets all the other information from the form
$ad_title = $_POST['title'];
$ad_price = $_POST['price'];
$ad_photo = $target . ($_FILES['photo']['name'][$i]);
if (!move_uploaded_file($_FILES['photo']['tmp_name'][$i], $target_files)) { //Tells you if its all ok
echo "Sorry, there was a problem uploading your file.";
} else { //Gives and error if its not
$sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')";
$conn->query($sql);
$sql1 = "INSERT INTO images (photos) VALUES ('$ad_photo') ";
$conn->query($sql1);
//Writes the photo to the server
header('location: addconfirm.php');
}
}
}
?>

get the last inserted primary key value using this
$last_id = $conn->insert_id;

You need to get last insert id form telephones table using $conn->insert_id; and the insert into images table as
$sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')";
$conn->query($sql);
$tp_id=$conn->insert_id;// get last insert id
$sql1 = "INSERT INTO images (photos,tp_id) VALUES ('$ad_photo',$tp_id) ";
$conn->query($sql1);
Note:- Your script is Open for sql injection check How can I prevent SQL injection in PHP? to prevent it

Question has already been answered many times Use : MySQL: LAST_INSERT_ID()
$sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')";
$conn->query($sql);
$tp_last_insert_id = $conn->LAST_INSERT_ID;// get last insert id
you should call this function right after you insert to get the latest added id
$sql1 = "INSERT INTO images (photos,tp_id) VALUES ('$ad_photo',$tp_last_insert_id) ";
$conn->query($sql1);

Related

Why My PHP code INSERT Command is inserting duplicate data sometimes?

Here is My Code. Its all working fine. But Some Times it inserting Duplicate Data. Why? I mean i placed the code so that same quize_no and phone combination should not submitted. But Some time its Inserting the Same quize_no and phone combination. Why is this Happening?
$sql = mysqli_query($con,"SELECT * FROM user_mm WHERE phone='$phone'");
while($row = mysqli_fetch_array($sql)) {
$name = $row['name'];
}
date_default_timezone_set("Asia/Dhaka");
$date = date('Y-m-d');
$time = date('h:i:s a', time());
$result = mysqli_query($con,"SELECT id FROM score_mm WHERE phone='$phone' AND quize_no='$quize_no' ");
$count=mysqli_num_rows($result);
if($count>0)
{
echo "1";
}
else
{
// Here I am Inserting Value in to Database
$query = mysqli_query($con,"insert into score_mm(name, phone, quize_no, score, date, time) values ('$name', '$phone','$quize_no', '$score', '$date', '$time')");
echo "Score Submitted Succesfully";
mysqli_close($con);
}
If there should truly never be a situation where you end up with duplicate quize_no and phone combinations in that table, then the first thing you should do is change your table structure to add a unique key to those columns.
For example:
ALTER TABLE score_mm ADD UNIQUE (quize_no, phone);
This won't fix whatever is causing multiple insert requests to be called, but it would at least protect your data integrity by not allowing any rows with duplicate value combinations.

Stuck at this error: Incorrect integer value: '' for column '____' at row 1

When I submit the form and use this script to insert the data in the db i get the error mentioned above...any ideas?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proCode = $_POST["code"];
$proDescr = $_POST["description"];
$proManu = $_POST["manufacturer"];
$proCPU = $_POST["cost_per_unit"];
$proWPU = $_POST["weight_per_unit"];
$proBarCode = $_POST["bar_code"];
$proIngredients = $_POST["ingredients_list"];
$proAllergens = $_POST["allergens_contains"];
$proMayAllergens = $_POST["allergens_may_contain"];
//Insert users data in database
$sql = "INSERT INTO prodb.simplex_list
code, description, manufacturer,
cost_per_unit, weight_per_unit, bar_code,
ingredients_list, allergens_contains,
allergens_may_contain)
VALUES
( '$proCode', '$proDescr' , '$proManu',
'$proCPU' , '$proWPU' , '$proBarCode',
'$proIngredients' , '$proAllergens',
'$proMayAllergens')";
//Run the insert query
if (!mysql_query($sql)) {
echo mysql_error();
}
?>
UPDATE: I removed id inserts as they are auto-increment and i learned from your answers that a null does not need to be coded and mysql looks after AI. Thanks guys!
Query need to be like:-
$sql = "INSERT INTO prodb.simplex_list
(code, description, manufacturer,
cost_per_unit, weight_per_unit,
bar_code, ingredients_list, allergens_contains,
allergens_may_contain)
VALUES ('$proCode', '$proDescr', '$proManu',
'$proCPU','$proWPU', '$proBarCode',
'$proIngredients', '$proAllergens',
'$proMayAllergens')";
Note:- please stop using mysql_*. Use mysqli_* or PDO. Also this will work only when id field must be auto incremented.

INSERT mysql_num_rows as a variable

I am creating a CMS in in which when you ADD NEW PAGE, a display_order will automatically grab the next highest number according to the number of rows already present. Here's what I currently have:
<?php
if(isset($_POST['updateContent'])){
require ("connection.php");
$sql = "SELECT * FROM pages";
$result = $conn->query($sql) or die(mysqli_error());
$content = $_POST['content'];
$title = $_POST['title'];
$id = $_POST['id'];
$order = mysqli_num_rows($result);
if (empty($id)){
/** ADD NEW SLIDE*/
$sql = "INSERT INTO pages (title, content, display_order, visible) VALUES ('".$title."', '".$content.", '".$order.", 0)";
}else{
/** UPDATE SLIDE*/
$sql = "UPDATE pages SET content = '".$content."', title = '".$title."' WHERE id = '".$id."'";
}
if ($result){
header("Location: admin.php");
}
}
?>
What this code is doing is taking the HTML form that I'm using in a page called edit.php and determining if it is new page or simply a page that is being updated. The error that I am getting is that NOTHING is posting to the database at all. If I remove the $sql, $result and $order lines.. the script works fine, but the display_order variable will not be set to the next highest number.
There is an error in your query:
INSERT INTO pages (title, content, display_order, visible)
VALUES ('".$title."', '".$content.", '".$order.", 0)";
^-- here
Should be:
INSERT INTO pages (title, content, display_order, visible)
VALUES ('".$title."', '".$content."', ".$order.", 0)";
^-- quote goes here
Also, using mysqli doesn't magically protect you from SQL-insertion. Escape dat input!
The common way to solve the situation is to use AUTO_INCREMENT field in pages table.
Sequentially insert and then ask for LAST_INSERT_ID
php way: http://php.net/manual/en/function.mysql-insert-id.php
native mysql way: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

How do I reference the row I had just inserted into a MySQL table?

I have this function in a Code Igniter model that creates a new "video."
// Creates a new video.
public function newVideo($title, $description) {
$this->db->query("INSERT INTO videos VALUES (NULL, '$title', '$description')");
return // id of this new row
}
How do I obtain the ID of this new row in my MySQL table? I could get the last row and add 1, but there could be concurrency bugs I believe.
Very simple answer doesn't really need more than 30 chars does it?
$this->db->insert_id();
maybe you need something like this
$this->db->insert_id();
Try something like that :
$lastID = -1; //That's where it'll be stored
$query = "SELECT LAST_INSERT_ID()";
$result = mysql_query($query);
if ($result)
{
$row = mysql_fetch_row($result);
$lastID = $row[0];
}
Code for an insert is:
$sql = "INSERT INTO videos (title) VALUES(NULL, '$title', '$description')";
$this->db->query($sql);
More information on queries available at: http://codeigniter.com/user_guide/database/queries.html
Another workaround is that you can have a look into videos table in your database, and make you video id as autonumber, this will automatically generate an id for your video and then you can try this:
//on your model
$sql = "INSERT INTO videos (title,description) VALUES('$title', '$description')";
$this->db->query($sql);
//retrieve new video id
$this->db->insert_id()

Problem with syntax error

Hi guys am fighting with a syntax error of my sql, saying exactly:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax"
Even though the code is working and doing what I wanted I still get the syntax error info!
and here is the code:
$person_id =mysql_query("SELECT person_id FROM person WHERE firstname='$array[0]' AND lastname='$array[1]' AND city='$array[2]' ")
or die(mysql_error());
if (mysql_num_rows($person_id) )
{
print 'user is already in table';
}
else
{
mysql_query ("INSERT INTO person VALUES (NULL, '$array[0]' ,'$array[1]' , '$array[2]' ")
or die(mysql_error());
$person_id = mysql_insert_id();
}
$address_id =mysql_query("SELECT address_id FROM address WHERE street='$array[3]' AND city='$array[4]' AND region='$array[5]'")
or die(mysql_error());
if (mysql_num_rows($address_id) )
{
print ' already in table';
}
else
{
mysql_query ("INSERT INTO address VALUES (NULL, '$array[3]', '$array[4]', '$array[5]'")
or die(mysql_error());
$address_id = mysql_insert_id();
}
mysql_query ("INSERT INTO person_address VALUES($person_id, $address_id)")
or die(mysql_error());
Thanks for any suggestions
It's probably because you haven't escaped your values...
Try:
$query = "SELECT age FROM person WHERE name='".mysql_real_escape_string($array[0])."' AND lastname='".mysql_real_escape_string($array[1])."' AND city='".mysql_real_escape_string($array[2])."'";
And read up on SQL injection.
EDIT
I think your problem is that you are trying to pass mysql result resources directly into a string, without fetching the actual values first.
Try this:
// Create an array of escaped values to use with DB queries
$escapedArray = array();
foreach ($array as $k => $v) $escapedArray[$k] = mysql_real_escape_string($v);
// See if the person already exists in the database, INSERT if not
$query = "SELECT person_id FROM person WHERE firstname='$escapedArray[0]' AND lastname='$escapedArray[1]' AND city='$escapedArray[2]' LIMIT 1";
$person = mysql_query($query) or die(mysql_error());
if ( mysql_num_rows($person) ) {
print 'user is already in table';
$person = mysql_fetch_assoc($person);
$person_id = $person['person_id'];
} else {
$query = "INSERT INTO person VALUES (NULL, '$escapedArray[0]', '$escapedArray[1]', '$escapedArray[2]')";
mysql_query($query) or die(mysql_error());
$person_id = mysql_insert_id();
}
// See if the address already exists in the database, INSERT if not
$query = "SELECT address_id FROM address WHERE street='$escapedArray[3]' AND city='$escapedArray[4]' AND region='$escapedArray[5]'";
$address = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($address) ) {
print 'address already in table';
$address = mysql_fetch_assoc($address);
$address_id = $person['address_id'];
} else {
$query = "INSERT INTO address VALUES (NULL, '$escapedArray[3]', '$escapedArray[4]', '$escapedArray[5]')";
mysql_query ($query) or die(mysql_error());
$address_id = mysql_insert_id();
}
// INSERT a record linking person and address
mysql_query ("INSERT INTO person_address VALUES($person_id, $address_id)") or die(mysql_error());
ANOTHER EDIT
Firstly, I have modified the code above - added a couple of comments, corrected a couple of small errors where the wrong variable was referenced and re-spaced it to make it more readable.
Secondly...
You are getting that additional error because you are trying to insert a new row into your person_address table, which doesn't seem to have a sensibly configured primary key. The easy work around to the problem you currently have is to run a SELECT against this table to see if you have already got a record for that user, then if you have you can do an UPDATE instead of the INSERT to alter the existing record.
However, if I understand what your doing here correctly, you don't actually need the person_address table, you just need to add another integer column to the person table to hold the ID of the corresponding row in the address table. Doing this would make many of your future queries potentially much simpler and more efficient as it will be much easier to SELECT data from both tables at once (you could do it with your current structure but it would be much more confusing and inefficient).
The following code example could be used if you add another integer column on the end of your person, and call that column address_id. You will notice it's very similar to the above, but there are two key differences:
We do the address stuff first, since we will keep track of the relation in the person record
We do an UPDATE only if we find a person, otherwise we just INSERT a new person as before
// Create an array of escaped values to use with DB queries
$escapedArray = array();
foreach ($array as $k => $v) $escapedArray[$k] = mysql_real_escape_string($v);
// See if the address already exists in the database, INSERT if not
$query = "SELECT address_id FROM address WHERE street='$escapedArray[3]' AND city='$escapedArray[4]' AND region='$escapedArray[5]'";
$address = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($address) ) {
print 'address already in table';
$address = mysql_fetch_assoc($address);
$address_id = $person['address_id'];
} else {
$query = "INSERT INTO address VALUES (NULL, '$escapedArray[3]', '$escapedArray[4]', '$escapedArray[5]')";
mysql_query ($query) or die(mysql_error());
$address_id = mysql_insert_id();
}
// See if the person already exists in the database, UPDATE if he does, INSERT if not
$query = "SELECT person_id FROM person WHERE firstname='$escapedArray[0]' AND lastname='$escapedArray[1]' AND city='$escapedArray[2]' LIMIT 1";
$person = mysql_query($query) or die(mysql_error());
if ( mysql_num_rows($person) ) {
print 'user is already in table';
$person = mysql_fetch_assoc($person);
$person_id = $person['person_id'];
$query = "UPDATE person SET address_id = '$address_id' WHERE person_id = '$person_id'";
mysql_query($query) or die(mysql_error());
} else {
$query = "INSERT INTO person VALUES (NULL, '$escapedArray[0]', '$escapedArray[1]', '$escapedArray[2]', '$address_id')";
mysql_query($query) or die(mysql_error());
}
If we structure the database in this way, it allows us to do this:
SELECT person.*, address.* FROM person, address WHERE person.address_id = address.address_id AND [some other set of conditions]
Which will return the person record, and the address record, in the same result set, all nicely matched up for you by the database.
YET ANOTHER EDIT
You need to add an auto-increment primary key to the person_address table, and perform a SELECT on it to make sure you are not adding duplicate records.
You should replace the final INSERT statement with the following code segment. This code assumes that you have a primary key in the person_address table called relation_id. It also assumes that the id field names in this table are named in the same way as they are in the other two tables.
// See if a relation record already exists for this user
// If it does, UPDATE it if the address is different
// If it doesn't, INSERT an new relation record
$query = "SELECT relation_id, address_id FROM person_address WHERE person_id = '$person_id' LIMIT 1";
$relation = mysql_query($query);
if ( mysql_num_rows($relation) ) {
$relation = mysql_fetch_assoc($relation);
if ($relation['address_id'] == $address_id) {
print 'The record is identical to an existing record and was not changed';
} else {
$relation_id = $relation['relation_id'];
$query = "UPDATE person_address SET address_id = '$address_id' WHERE relation_id = '$relation_id'";
mysql_query($query) or die(mysql_error());
}
} else {
$query = "INSERT INTO person_address VALUES(NULL, '$person_id', '$address_id')";
mysql_query($query) or die(mysql_error());
}
EVEN MORE EDITING
Try this to replace the code from above:
// See if a relation record already exists for this user
// If it doesn't, INSERT an new relation record
$query = "SELECT person_id FROM person_address WHERE person_id = '$person_id' AND address_id = '$address_id' LIMIT 1";
$relation = mysql_query($query);
if ( !mysql_num_rows($relation) ) {
$query = "INSERT INTO person_address VALUES('$person_id', '$address_id')";
mysql_query($query) or die(mysql_error());
}
You cannot use array values like that inside of quotes - instead you could, for example, separate the values from the query using dots.
$query = "SELECT age FROM person WHERE name='".$array[0]."' AND lastname='".$array[1]."' AND city='".$array[2]."'";
the second and fourth query do not have an ending ')' at the end of the values

Categories