I am trying to insert rows of data in an array into a table in mysql database. I am a beginner in php, mysql and have very little knowledge about it. I just want to learn more. If you can give this a try It would be great.
The code which i want to insert is below:
for($x=0; $x<2; $x++)
{
$data[$x]['title'] = $titleQuery->item($x)->nodeValue;
$data[$x]['titleHrefQuery'] = $titleHrefQuery->item($x)->nodeValue;
$data[$x]['food'] = $foodQuery->item($x)->nodeValue;
$data[$x]['locality'] = $localityQuery->item($x)->nodeValue;
$data[$x]['rating'] = $ratingQuery->item($x)->nodeValue;
$data[$x]['cost'] = $costQuery->item($x)->nodeValue;
}
I am tring to insert using the code given below:
$query = "INSERT INTO table (`title`, `link`, `food`, `locality`, `rating`, `cost`) VALUES
('" . $titleQuery->item($x)->nodeValue . "',
'".$titleHrefQuery->item($x)->nodeValue."',
'".$foodQuery->item($x)->nodeValue."',
'".$localityQuery->item($x)->nodeValue."',
'".$ratingQuery->item($x)->nodeValue."',
'".$costQuery->item($x)->nodeValue."')";
$result = mysql_query($query);
if($result)
{
echo ("Success");
}
else
{
echo ("Not added");
}
But every time it shows not added. please help!!
Change
INSERT INTO table
to
INSERT INTO `table`
Because table is a reserved keyword.And if you are using reserved keywords as table name or column name then you must enclose them in back-ticks (`).And its better not to use any reserve keyword.So if you can change the name then it will be the best choice.You can check for more in these questions
How do I escape reserved words used as column names? MySQL/Create Table
Can we have the table name as "option" in MySQL?
H2 database column name "GROUP" is a reserved word
"INSERT INTO table...." should be "INSERT INTO `table`..."
Try to avoid mysql key names as table name or field name it would help you in writing better sql queries.
Use following line to see mysql error so can you easily track the reason why you are getting error -
if($result)
{
echo ("Success");
}
else
{
echo ("Not added");
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
}
Related
I've tried to follow several answers on this question but can't seem to get it to work for my specific problem.
I want to insert data but only if the flight_number doesn't exists already. How can I do that?
$sql = mysqli_query($con,
"INSERT INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Rob since you saying flight_number is a unique then you can use INSERT IGNORE
<?php
$sql = "INSERT IGNORE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`) VALUES (?,?,?,?)";
$stmt = $con->prepare($sql);
$stmt->bind_param('isss',$flight_number,$mission_name,$core_serial,$payload_id);
if($stmt->execute()){
echo 'data inserted';
// INSERT YOUR DATA
}else{
echo $con->error;
}
?>
OR you could select any row from your database that equal to the provided flight number then if u getting results don't insert.
$sql = "SELECT mission_name WHERE flight_number = ? ";
$stmt = $con->prepare($sql);
$stmt->bind_param('i',$flight_number);
if(mysqli_num_rows($stmt) === 0){
// INSERT YOUR DATA
}
A unique index on flight number should do the trick.
CREATE UNIQUE INDEX flight_number_index
ON space (flight_number);
If you want to replace the existing row with the new one use the following:
$sql = mysqli_query($con,
"REPLACE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Make note that I just copied your code and changed INSERT to REPLACE to make it easy to understand. PLEASE PLEASE PLEASE do not use this code in production because it is vulnerable to injection.
If you don't want to replace the existing row, run an insert and check for errors. If there is an error related to the index, the row already exists.
Disclaimer: I haven't tested any of this code, so there may be typos.
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.
I'm getting a mysql error saying "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..."
Here's the basics of my code:
First I'm populating the select menu options with rows from the categories table. This is working fine:
<select id="dropdown-select" name="Name">
<option value="" id="dropdown-option">Please select a category.</option>
<?php
$query_categories = "SELECT * FROM categories";
$result_categories = mysql_query($query_categories) or die(mysql_error());
while($categories_row = mysql_fetch_array($result_categories)) {
echo '<option id="dropdown-option" value="' . $categories_row['cat_name'] . '">' . $categories_row['cat_name'] . '</option>';
}
?>
</select>
Later, when I go submit the form to the transactions table (the above table I pulled data from was the categories table, could this be a problem?) is when I get the error. I think its related to the above code bc if I remove this element from my form submission, it writes the rest of the values to the database without any errors.
if(!isset($_POST['Name'])) {
die('You must select an income or expense from the drop down menu.');
} else {
$Name = $_POST['Name'];
}
//create query
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month', '$Name', $Budgeted', '$Actual')";
$result = mysql_query($query) or die("Error in query: $query. " . mysql_error());
Thanks for any help you can provide.
You are missing a single quote in your insert statement before $Budgeted
INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month', '$Name', '$Budgeted', '$Actual')"
If you have some fields which are defined in Database as VARCHAR, CHAR.
Also, if you are inserting a string value in Database from a PHP script, you need to add an enclosing single quote (') around it.
In your case, you are inserting a string without semicolons, so, it showing error in MySQL.
Your statement should be corrected by adding a single quote around $budget as:
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual) VALUES ('$Month',
'$Name', '$Budgeted', '$Actual')";
------^
The error "You have an error in your SQL syntax" is exactly correct!
$query = "INSERT INTO transaction (month, trans_name, budgeted, actual)
VALUES ('$Month', '$Name', $Budgeted', '$Actual')";
Look here, you missed something ----^
There is a ' missing from your statement causing the syntax error. Put the single quote in and you should be good to go!
I have been given a task to convert the hardcoded fields into dynamic fields.I have changed it partially to dynamic
Let me explain you the situation ,
We have a lot of databases and each database has a table by name Surveys
By using the DESCRIBE statement we will retrieve the fields in the Surveys table regardless of the database .
I need to know the way where we can loop again and again till all the fields in the survey table appears.
In the below code I have left the for loop blank .
Please let me know the changes that neeeds to be done to get this working
I would really appreciate any kind of help
function insertIntoUserUploadFileds() {
$describe="DESCRIBE surveys";
$sql = "INSERT INTO `userUploadFields` (`fieldName`, `inUse`, `mandatory`, `type`, `mapTo`) VALUES";
$inUse="0";
$type="";
//for(){
if($field=='type'){
$type="N";
}elseif(($field=='fname') || ($field=='lname') || ($field=='phone')){
$inUse="1";
$type="T";
}elseif($field=='email'){
$inUse="1";
$type="E";
}
//$sql .= "('".$field."', '".$inUse."', '0', '
$result1 = mysql_query ($describe);
$result = mysql_query ($sql);
//}
}
$result1 = mysql_query ('DESCRIBE surveys');
//here is how you retieve all field and check
while($row = mysql_fetch_array($result1)) {
$sql = "INSERT INTO `userUploadFields` (`fieldName`, `inUse`, `mandatory`, `type`, `mapTo`) VALUES";
//here you can do if else to check the column name
if($row['field']=='type')
{
$type="N";
}
else if(($row['field']=='fname') || ($row['field']=='lname') || ($row['type']=='phone'))
{
$inUse="1";
$type="T";
}
else ($row['field']=='email')
{
$inUse="1"
$type="E";
}
//build your query
$sql .= "('".$field."', '".$inUse."', '0', '......)
//execute your complete query
$result = mysql_query ($sql);
}//end of while
Instead of using DESCRIBE, if you are trying to retrieve the default type of a particular column you might look into this. It describes how to break down the information from a particular table. Codex
I'm learning PHP right now and I'm trying to insert data into a MySQL database called "pumpl2" The table is set up like this.
create table product
( productid int unsigned not null auto_increment primary key,
price int(9) not null,
value int(9) not null,
description text
);
I have a form and want to insert the fields from the form in the database. Here is what the php file looks like.
<?php
// create short variable names
$price = $_POST['price'];
$value = $_POST['value'];
$description = $_POST['description'];
if (!$price || !$value || !$description) {
echo "You have not entered all the required details.<br />"
."Please go back and try again.";
exit;
}
# $db = new mysqli('localhost', 'pumpl', '********', 'pumpl2');
if (mysqli_connect_errno()) {
echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "insert into pumpl2 values
('".$price."', '".$value."', '".$description."')";
$result = $db->query($query);
if ($result) {
echo $db->affected_rows." product inserted into database.";
} else {
echo "An error has occurred. The item was not added.";
}
$db->close();
?>
When I submit the form, I get an error message "An error has occurred. The item was not added."
Does anyone know what the problem is? Thank you!
This should give you more information:
echo "An error has occurred: " . $db->error();
You are trying to insert into the table called pumpl2, but the CREATE TABLE statement created a table called product.
In addition, as ZeissS noted, you have to consider the following:
CREATE TABLE product (
productid int unsigned not null auto_increment primary key,
price int(9) not null,
value int(9) not null,
description text
);
Query OK, 0 rows affected (0.09 sec)
INSERT INTO product VALUES (1, 1, 'test');
ERROR 1136 (21S01): Column count doesn't match value count at row 1
To solve that error, you need to explicitly specify the list of the columns:
INSERT INTO product (price, value, description) VALUES (1, 1, 'test');
Query OK, 1 row affected (0.03 sec)
You only insert three columns but have four defined in your table. Thus you have to name the columns explicitly:
INSERT INTO tableName (ColumnA, ColumnB, ColumnC) VALUES ('A', 'B', 'C')
$query = "insert into pumpl2.product (price, value, description) values('" .
$db->read_escape_string($price) . "', '".
$db->read_escape_string($value) . "', '" .
$db->read_escape_string($description) . "')";
$result = $db->query($query);
And an obligatory XKCD cartoon:
Your query is wrong, you didn't have the columns specified.
Try it with:
"INSERT INTO pumpl2 (price, value, description) VALUES ('".$price."', '".$value."', '".$description."')"
Besides that, do not use the $_POST values to enter them directly into the database. Search for SQL Injection on this one. Use mysql_real_escape_string on the $_POST data first, or even better use prepared statements.
It could be several reasons.
Try
echo "Errormessage: ".$db->error;
to get more details, why the Insert didn't work.
Your table is called products not pumpl2. Furthermore you should do:
insert into product (price, value, description) values ( ...