I've deleted an old, badly worded question and am reposting to not waste anyone's time.
I'm trying to query stuff from two tables, rooms and items. Then in a nested loop, create an entry in a 3rd table using info from the first two.
'For each room, insert ALL the standard items'
<?php
mysql_connect("******", "****", "******") or die(mysql_error());
mysql_select_db("MaintenanceTracking") or die(mysql_error());// Check connection
//collect standard items names
$stditemdata = 'SELECT * FROM `StandardItems`';
$itemresult = mysql_query($stditemdata) or die("Couldn't execute query. ". mysql_error());
$itemarray = mysql_fetch_array( $itemresult ));
//collect room info
$roomdata = 'SELECT * FROM `Rooms`';
$roomresult = mysql_query($roomdata) or die("Couldn't execute query. ". mysql_error());
//repeat for each room
while($room = mysql_fetch_array( $roomresult ))
{
//repeat for each item
for ($i = 0; $i <= count($itemarray); $i++)
{
mysqlquery("INSERT into Items
(ItemNumber, Name, LocationCode)
VALUES
(NULL, $itemarray['Name'], $room['LocationCode'])");
}
}
?>
I'm pretty new to php and must appologize that the syntax sometimes gets me stumped...I notoriously miss the semi-colon at the ends of rows, for example.
A million thanks in advance to anyone and everyone who can help me out.
kindest regards
mysqlquery("INSERT into Items
(ItemNumber, Name, LocationCode)
VALUES
(NULL, $itemarray['Name'], $room['LocationCode'])");
It should be
mysql_query("INSERT into `Items`
(`ItemNumber`, `Name`, `LocationCode`)
VALUES
(NULL, $itemarray['Name'], $room['LocationCode'])");
You use mysqlquery instead of mysql_query
To avoid duplication of mysql-reserved names (f.e. date, table etc) use this syntax
`column_name` or `table_name`
UPDATE
oh.. i miss! look, you try to write some strings into DB here
mysql_query("INSERT into `Items`
(`ItemNumber`, `Name`, `LocationCode`)
VALUES
(NULL, $itemarray['Name'], $room['LocationCode'])");
All strings in queries must be concluded in quotes single ' or double ", so your query should looks like
mysql_query("INSERT into `Items`
(`ItemNumber`, `Name`, `LocationCode`)
VALUES
(NULL, \"$itemarray['Name']\", \"$room['LocationCode']\")");
(i use \ symbol before " to escape quote), but i suggest you to use syntaxys like this:
mysql_query("INSERT into `Items`
(`ItemNumber`, `Name`, `LocationCode`)
VALUES
(NULL, '".$itemarray['Name']."', '".$room['LocationCode']."')");
Related
I am really new to php and I am trying to use simple insert to my mysql database from the form.
I know that this mysql connection/insertion is dangerous and not used anymore. so can anyone please help me with this simple thing? I tried to google, but nothing is working so far :/
<?
$text=$_POST['name'];
$text=$_POST['surename'];
mysql_connect("localhost", "db_name", "pass") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$result = mysql_query("INSERT INTO `table` (name, surename)
VALUES (NOW(), '".mysql_real_escape_string($name)."', '".mysql_real_escape_string($surename)."')");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Maybe change
$text=$_POST['name'];
$text=$_POST['surename'];
to
$name = $_POST['name'];
$surename = $_POST['surename'];
PS: And also your column names don't match your values. Your query, after inserting params
"INSERT INTO `table` (name, surename) VALUES (NOW(), '".mysql_real_escape_string($name)."', '".mysql_real_escape_string($surename)."')"
will probably look like this
INSERT INTO `table` (name, surename) VALUES (NOW(), 'Jhon', 'Wick')
As you can see there's name, surename (which probably should be surname) and (NOW(), 'Jhon', 'Wick'). So either add a column (if you have that column in your database):
INSERT INTO `table` (created_at, name, surename) VALUES (NOW(), 'Jhon', 'Wick')
or remove NOW() from your values
INSERT INTO `table` (name, surename) VALUES ('Jhon', 'Wick')
I need to update and insert around 1 Million data in mysql data base, when I am using the following code It takes more time. please suggest how can i update and insert the data fastly?
include('db.php');
include('functions.php');
$functions=new functions();
set_time_limit(0);
$column="rank"."_".date("Y-m-d");
$count=$functions->get_row("SELECT COUNT(id) as ct FROM alexa_filename WHERE status=1");
if($count->ct==100){
$alexas=$functions->get_result("SELECT DISTINCT (`sitename`),`$column` FROM `top-2m` WHERE `status`=0 LIMIT 100" );
if(!empty($alexas)){
foreach($alexas as $alexa){
$site_name=$alexa->sitename;
echo $site_name;
$rank=$alexa->$column;
$table=$functions->find_table_name($site_name);
$count=$functions->get_row("SELECT COUNT(site_name) as ct FROM `$table` WHERE site_name='$site_name'");
if($count->ct==0){
$functions->set_query("INSERT INTO `$table`( `site_name`, `other_id`, `response`, `category`, `updated`, `site_update`, `wot_update`, `social_update`, `google_update`, `server_update`, `alexa_update`, `backlinks_update`, `antivirus_update`, `key`, `desc`, `google_backlink`, `images_url`, `images`, `tag`, `view_count`, `title`, `api_update_time`, `table_name`, `user_added_similar`, `auto_similar`, `comments`, `status`) VALUES ('$site_name',0,0,0,0,0,0,0,0,0,$rank,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)");
$functions->set_query("UPDATE `top-2m` SET `status`=1 WHERE sitename ='$site_name'");
}else{
$functions->set_query("UPDATE `$table` SET `alexa_update`=$rank WHERE site_name='$site_name'");
$functions->set_query("UPDATE `top-2m` SET `status`=2 WHERE sitename ='$site_name'");
}
}
}else{
mail("aaa#aaa.com","Alexa_Cron_Update_Status","aaaRank Is Succes fully Updated");
}
}
You can insert/update multiple rows using INSERT ... ON DUPLICATE KEY
UPDATE.
Reindex your database.
Use Prepared Mysql Statements.
Also If you are using Linux/ubuntu try to use terminal instead of browser. It will make a lot difference.
Concatenate your INSERT and UPDATE Query to $qry and apply
$functions->set_query($qry);
once your looping done. This will take less time.
Edited:
Example:
$qry = "Insert into table values('', '', '','', '')";
$qry .= "insert into table2 values('', '', '','', '')";
$qry .= "insert into table3 values('', '', '','', '')";
$qry .= "update table3 set field = 'something' ";
and out of condition or loop.
$functions->set_query($qry);
Here's my code:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
the first time, I could see the the values were added but when I reloaded, it didn't do any more, is it supposed to be like this ?
So if I want it to run every time I reload, how can I do that?
You probably have a unique constraint against your id column (or another column in that query) and when you try to add a second row using the same ID it is rejected by MySQL.
You should be doing error checking in your code. You should be checking to see how many rows were affected by your insert (using mysqli_affected_rows()) and, if the number is zero, getting the error message from MySQL (using mysqli_error()).
$result = mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values (0,'d','cwer','73')");
if (mysqli_affected_rows() === 0) {
echo mysqli_error($con);
}
#DaveChen's comment above is a good solution to your (potential) problem. If it isn't already, make your id column auto increment and then leave it out of your query.
mysqli_query($con,"INSERT INTO 'bird' (`name`, `latin`, `number`) values ('d','cwer','73')");
If your id column is aut_increment and unique: change your code to:
$con=mysqli_connect("localhost","name","pass","bird") ;
$result = mysqli_query($con,"SELECT * FROM bird");
mysqli_query($con,"INSERT INTO 'bird' (`id`, `name`, `latin`, `number`) values ('','d','cwer','73')");
I am using to add data into DB. First i get the values from post and then insert it into table. The problem is that there are total 7 values but only 5 values added and 2 of them not inserted into the table. Here is my code
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
$degree_title = $_POST['degree_title'];
$degree_year = $_POST['degree_year'];
$uni_name = $_POST['uni_name'];
$degree_level = $_POST['degree_level'];
$major_sub = $_POST['major_sub'];
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
}
I echo the all values and all values are coming so why they all not inserted into table any idea. Thank
try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, '$eme_uid', '$degree_title', '$degree_year', '$degree_level', '$major_sub', '$uni_name')");
and i would highly recommend:
1) dont use mysql_ its deprecated, use mysqli_*
2) sanitze ALL values in _POST befor using in SQL statements.
if id is autoincrement then you dont need to insert it.
try this
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES ($eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
My guess is that $degree_title and $uni_name doesn't get inserted because they are varchars. In that case you will have to put quotes around these values.
Mysql is kind of "forgiving" in the sence that it does not throw an error when using incorrect types in the sql-statement in relation to the actual type of the column.
Try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, '$degree_title', $degree_year, $degree_level, $major_sub, '$uni_name')");
As mentioned before id doesn't have to be included (if id-column is autoincremental) in the insert-statement, and you should really learn mysqli or PDO.
i have a recipe table and ingredient table the primary key of both tables are auto increament and primary key of recipe is foreign key in ingredient. i post data from html to php.Note that my ingredient textboxes are generated dynamically and successfully post the data to php script. posted data is correct when i insert this data to table my query working fine but data is not added to mysql table. my code and output is
$sql = "insert into recipe (rec_id, Name, Overview,category, Time, Image) values ('', '$name','$overview','$category','$time','$TARGET_PATH')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
$rec_id = mysql_insert_id();
and for ingredient
$ingredient = $_POST['ingredient'];
$amount = $_POST['amount'];
$integer = 0;
while (count($ingredient)>$integer) {
if (($ingredient[$integer] <> "") && ($amount[$integer] <> "")){
$sql = "INSERT INTO `cafe`.`ingredients` (`ingredient_id`, `ingredient_name`, `ammount`, `rec_id`,)
VALUES ('', '".$ingredient[$integer]."', '".$amount[$integer]."', '$rec_id')";
mysql_query($sql);
echo $sql."";
}
else{
echo "ingredient number ".($integer+1)." is missing values and cannot be inserted.";
}
$integer = ($integer + 1);
}
when i echo the queries the out put is nsert into recipe (rec_id, Name, Overview,category, Time, Image) values ('', 'demo recipe','no overview','meal','10/12/10 : 13:02:33','http://www.localhost/cafe/pics/demo.gif')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient one', '3gm', '29')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient two', '3gm', '29')
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id,) VALUES ('', 'ingredient three', '3gm', '29')
but when i see the mysql table or retriew data from ingredient there is no data in ingredient.
You have an extra , after rec_id.
Remove it, so it looks like
INSERT INTO cafe.ingredients (ingredient_id, ingredient_name, ammount, rec_id) VALUES ('', 'ingredient one', '3gm', '29')
And you will be OK
There seems to be a syntax error in your code:
if (($ingredient[$integer] "") && ($amount[$integer] ""))
^^ ^^
Looks like you are missing a comparison operator.
You might want to verify if you are using a BEGIN call and not committing after INSERT. You can refer to http://www.devarticles.com/c/a/MySQL/Using-Transactions-with-MySQL-4.0-and-PHP/
in that scenario.
When insert doesnt throw exceptions and doesnt insert data there are I think a couple of options
1) you use transaction somewhere and rollback it
2) your select query is bad and data is there, but you just dont select it
remove cafe from the query
$sql = "INSERT INTO ingredients (`ingredient_id`, `ingredient_name`, `ammount`, `rec_id`,)
VALUES ('', '".$ingredient[$integer]."', '".$amount[$integer]."', '$rec_id')";