insert php array into mySql - php

I am looking for some guidance.
I have a data form field which I am inserting into a table and am looking to association the data with the id's of other relevant data. I was wondering if there was recommended way to insert an array of relevant Id's in relation to the information I am referring too.
Below is what Im thinking...
Eg. php reads
<?php
$name = $_POST['name'];
$info = $_POST['information'];
$id = $_POST['id'];
$family = array();
?>
<?php
$select = "SELECT *
FROM `names_family`
WHERE `name` LIKE '$name'
LIMIT 0 , 30";
$selected = mysql_query($select, $connection);
if(!$selected){
die("Hal 9000 says: Dave the select family name ID query failed " . mysql_error());}
while($row = mysql_fetch_array($selected)){
$familyId = $row[0];
$familyName = $row[1];
array_push($family, $familyName => $familyId);
}
$insertInfo = "INSERT INTO `family_info`.`info`
(`name`, `info`, `family`)
VALUES (
'$name', '$info', '$family');";
$insertedInfo = mysql_query($insertInfo, $connection);
if(!$insertedInfo){
die("Hal 9000 says: Dave the insert info query failed " . mysql_error());}
?>
Is this a recommended way to relate information? Or is another way to achieve the same result?

What data type is the "family" column in MySQL?
I'm pretty sure you can't straight up insert php arrays like that into MySQL.
If it's possible, guess it's one of those things I didn't know because I never even tried.
The easiest way to do this is to encode your php array into a JSON string and decode it back into a php array when you read it.
$family = array();
...
$familyJsonString = json_encode($family);
...
$insertInfo = "INSERT INTO `family_info`.`info`
(`name`, `info`, `family`)
VALUES (
'$name', '$info', '$familyJsonString');";
...
$queryString = "SELECT * FROM family_info WHERE name = '$someName'";
$query = mysql_query($queryString, $connection);
$familyData = mysql_fetch_assoc($query);
$decodedFamilyArray = json_decode($familyData['family']);
where the family column should be a varchar or text type depending on how long the family array gets.
A more robust way to do this is to create a separate table to store your family data and use a MySQL JOIN statement to get the values associated to one entry in the family_info table.
here is some info on joins
Joining two tables without returning unwanted row
http://dev.mysql.com/doc/refman/5.0/en/join.html

there is another way
$family=array()
while($row = mysql_fetch_array($selected)){
$familyId = $row[0];
$familyName = $row[1];
$family[]=$familyName.$familyId;
}
$insertInfo = "INSERT INTO `family_info`.`info`
(`name`, `info`, `family`)
VALUES (
'$name', '$info', '$family');";

Related

SQL - Insert INTO results in nothing

I've been trying to get this INSERT to work correctly, so I worked through the undefined variable and index problems and now I think I am nearly there.
Below is the code:
<?php
session_start();
require "../dbconn.php";
$username = $_SESSION['username'];
$query1 = "SELECT user_table.user_id FROM user_table WHERE user_table.username ='".$username."'";
$query2 = "SELECT department.department_id FROM department, user_table, inventory
WHERE user_table.user_id = department.user_id
AND department.department_id = inventory.department_id";
//Copy the variables that the form placed in the URL
//into these three variables
$item_id = NULL;
$category = $_GET['category'];
$item_name = $_GET['item_name'];
$item_description = $_GET['item_description'];
$item_quantity = $_GET['quantity'];
$item_quality = $_GET['quality'];
$item_status = NULL;
$order_date = $_GET['order_date'];
$invoice_attachment = NULL;
$edit_url = 'Edit';
$ordered_by = $username;
$user_id = mysql_query($query1) or die(mysql_error());
$department_id = mysql_query($query2) or die(mysql_error());
$price = $_GET['price'];
$vat = $_GET['vat%'];
$vat_amount = $_GET['vat_amount'];
$create_date = date("D M d, Y G:i");
$change_date = NULL;
//set up the query using the values that were passed via the URL from the form
$query2 = mysql_query("INSERT INTO inventory (item_id, category, item_name, item_description, item_quantity, item_quality, item_status, order_date,
invoice_attachment, edit_url, ordered_by, user_id, department_id, price, vat, vat_amount, create_date, change_date VALUES(
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$item_quantity."',
'".$item_quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$user_id."',
'".$department_id."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
header( 'Location:../myorders.php');
?>
Error:
Error: 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 'VALUES( '', 'adasd', 'dsadsa', 'dsad', 'sadsad', '' at line 2
Could anyone please let me know where I am going wrong? :(
Been staring at this for 3-5 hours already :(
You are not actually trying to insert any data into your table. You only craft and assign the query in string form to a variable. You need to use the function mysql_query to actually run the code.
As pointed out you will also have to specify the columns you are inserting data into in the MySQL query if you don't supply data for every column (in the correct order). Here you can look at the MySQL insert syntax.
I would also urge you to look into using the MySQLi or the MySQL PDO extensions for communicating with your MySQL database since the MySQL extension is deprecated. Look here for additional information and comparisons.
Here, you only assign the values to the $query var:
$query = "INSERT INTO inventory VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')"
or die("Error: ".mysql_error());
You do not actually run the query.
try:
$query = mysql_query("INSERT INTO inventory (column_name1, column_name 2, column_name3 ... the column name for each field you insert) VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
Also, you should use mysqli_* or any other PDO as the mysql_* functions are deprecated
If you are not inserting in all columns you need to specify the columns you are going to insert. Like this:
INSERT INTO Table(Column1, Column6) VALUES (Value1, Value6)
You are missing the column names in your INSERT

doing an update or an insert with sql

I have a website for fantasy golf. I use php to read an xml file and update the sql database using the following
foreach($field->field->children() as $player){
$lastname = ($player['last_name']);
$firstname = ($player['first_name']);
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$sSQL = "UPDATE `Sheet1` Set InField= 1 WHERE LastName = '$lastname' AND Firstname = '$firstname'";
$result = mysql_query($sSQL, $conn) or die(mysql_error());
This updates the database INFIELD column with the players on the xml file. My question is how would I go about adding that player to the database if he isn't in it already? So almost like doing and if not in the database--insert new record?
any help would be appreciated.
Make sure you have a unique key on (LastName, FirstName), then use:
INSERT INTO Sheet1 (LastName, FirstName, InField)
VALUES ('$lastname', '$firstname', 1)
ON DUPLICATE KEY UPDATE InField = 1
Documentation
I suggest you condition it.
player =mysql_query(select player_in_table from players_table where player_in_table = playerx)
if(mysql_num_row(player) = 1){
//update
} else {
//update
}

Add data into php mysql with single quotes

This is my code:
$q=mysql_query("SELECT * FROM `table1` WHERE name like '%$searchText%'");
while($e=mysql_fetch_assoc($q))
//$output[]=$e;
//echo $e['NAME'];
{
$name = $e['NAME'];
$brand = $e['BRAND'];
$category = $e['CATEGORY'];
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
$result = mysql_query($query) or die("Unable to insert because : " . mysql_error());
}
Since in "BRAND", there may be some data like "First's Choice".
In this case, I cannot insert to database due to error.
How can I insert data that contain single quotes?
Thx
you need to use mysql_real_escape_string on the value, which you should be doing anyway. That should properly escape your value for insertion.
$name = mysql_real_escape_string($e['NAME']);
$brand = mysql_real_escape_string($e['BRAND']);
$category = mysql_real_escape_string($e['CATEGORY']);
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
Use mysql_real_escape_string
You must use :
$brand = mysql_real_escape_string($brand)
See PHP Documentation.
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )
Escapes special characters in
the unescaped_string, taking into account the current character set of
the connection so that it is safe to place it in a mysql_query(). If
binary data is to be inserted, this function must be used. (..)
Try below code
$q=mysql_query("SELECT * FROM `table1` WHERE name like '%$searchText%'");
while($e=mysql_fetch_assoc($q))
//$output[]=$e;
//echo $e['NAME'];
{
$name = $e['NAME'];
$brand = mysql_real_escape_string($e['BRAND']);
$category = $e['CATEGORY'];
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
$result = mysql_query($query) or die("Unable to insert because : " . mysql_error());
}
There are two ways of accomplishing that. You can first run an escape string on it:
$newbrand = mysql_real_escape_string($brand);
and insert $newbrand. When you call it, you have to do strpslashes($newbrand);
OR you could do:
$search = array("'");
$newbrand = str_replace($search,'',$brand);
I was pulling my hair to solve this, finally i am ok with this solution. Try this

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

help with multiple queries (PHP/MySQL)

PLease note I am a beginner.
My situation is thus:
I am trying to run multiple queries, off the back of a dynamic form. So the data is going to end up in two different tables.
I am currently successfully storing in to my item_bank, which has an auto_increment itemId.
I then want to grab the ItemId just created on that last query and insert it into my next query of which I am also inserting an array. (I hope you can follow this)
first off, is it even possible for me to run multiple queries like this on a single page?
Below is my attempt at the queries. Currently the first query works, however I cannot get the ItemId generated from that query.
$answers is an array.
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$query = "INSERT INTO answers_tb (item_id, text_value)VALUES('$itemid',' . implode(',', $answers) . ')";
mysql_query($query) or die(mysql_error());
this is the error i get now: "Column count doesn't match value count at row 1"
To get the ID generated by an auto-increment field in PHP/MySQL just use the mysql_insert_id() function.
Edit:
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$answers = mysql_real_escape_string(implode(',', $answers));
$query = "INSERT INTO answers_tb (item_id, text_value) VALUES('$itemid','$answers')";
mysql_query($query) or die(mysql_error());
Have a look at mysql_insert_id():
// store item structure info into item_bank_tb
mysql_query($query);
$itemid = mysql_insert_id();
// now store different answers

Categories