I'm sure this question has been asked a thousand times but after an hour of truly trying many examples on the web, I have failed to insert new data into my table. I have tried many methods as I said, the one I'm about to post is most recent. If anyone knows why my code is failing it would save so much stress. I have only so far managed to insert data via phpmyadmin. The database is called "test" and the table is called "getting". Please note that "key" is auto incremented.
Thank you
$username='****';
$password='****';
$database='test';
$con= mysql_connect("localhost",$username,$password);
mysql_select_db("test",$con);
mysql_query("INSERT INTO getting (Key, Date, amount, tax, Extra)
VALUES ('', 'sept 26 2008', '35653', '46', '454')");
You should try
put keywords between backticks
format date as YYYY-MM-DD
don't use quotes for numbers
use NULL for auto-increment keys (you could also remove it from INSERT)
perform error checking
Try this query
$res = mysql_query(
"INSERT INTO getting (`Key`, `Date`, amount, tax, Extra)
VALUES (NULL, '2008-09-26', 35653, 46, 454)");
if (!$res) {
die('Invalid query: ' . mysql_error());
} else {
// Do here what you need
}
mysql_query("INSERT INTO getting (Key, Date, amount, tax, Extra)
VALUES ('', 'sept 26 2008', '35653', '46', '454')") or die(mysql_error());
What does it say after execution? If there is an error in request - you will see it.
my guess would have been "4. use NULL for auto-increment keys" by marco too
I belive if the 'key' filed is autoincremented you may not even bother mentioning it in your insert statement.
Something like this
INSERT INTO getting (Date, amount, tax, Extra)
VALUES ('sept 26 2008', '35653', '46', '454')
Related
So, im trying insert some data into a table, I get the previous data from either GET or another SQL query (My database consists of INT and TEXT so I don't think there is an issue there).
I have a query
$sql2 = "INSERT INTO orders (USER_NAME, USER_ID, ARTIST_ID, ARTIST_NAME, PRICE, DESCRIPTION, COMMENTS)
VALUES ('$user_name','$user_id','$artist_id','$artist_name','$price','$description','$comments')";
This $sql2 echo's as follows
INSERT INTO orders (USER_NAME, USER_ID, ARTIST_ID, ARTIST_NAME, PRICE, DESCRIPTION, COMMENTS) VALUES ('myname','1',''1'','Actual Name','19.99','test','tst2')
However, when I do
if ($conn->query($sql2) === TRUE) {
$conn->close();
echo "success";
exit();
} else {
$conn->close();
echo "failed";
}
I get failed printed. But if I change the $sql2 into
VALUES ('test','test','test','test','test','test','test')";
The query is executed successfully inserted into my database (other than the int values that turn into 0). Could someone enlighten me why this would happen?
for some reason your artist_id value has a double quotation mark while other values has single quotation mark, which is probably the reason your query fails( i have bolded it):
INSERT INTO orders (USER_NAME, USER_ID, ARTIST_ID, ARTIST_NAME, PRICE, DESCRIPTION, COMMENTS) VALUES ('myname','1',''1'','Actual Name','19.99','test','tst2')
I'm pretty new to PHP code.
I have a tabel that I want to insert in to but for some reason the insert statement does not work. The tabel has an ScanID column that AUTO_INCREMENT 's. I've tried a few things like just leaving the ScanID out of the statement but that didn't work either ( I also tried swapping the NULL with ' '). I was able to insert in to other tables where there isn't an ID that AUTO_INCREMENT's so my pretty sure that my connection works.
<?php
$xml=simplexml_load_file("someFile.xml");
$con =new PDO("mysql:host=localhost;dbname=testDB",'root','');
$ScanType="someType";
$start_date=$xml ->start_datetime;
$end_date=$xml ->finish_datetime;
$TargetTargetID="1";
$stmt=$con->prepare('insert into
Scan(ScanID, ScanType, start_date, end_date, TargetTargetID) values
(:ScanID, :ScanType, :start_date, :end_date, :TargetTargetID)');
$stmt->bindValue('ScanID',NULL);
$stmt->bindValue('ScanType',$ScanType);
$stmt->bindValue('start_date',$start_date);
$stmt->bindValue('end_date',$end_date);
$stmt->bindValue('TargetTargetID',$TargetTargetID);
$stmt->execute();
$ScanID=$con->lastInsertId();
echo $ScanID;
?>
EDIT: this worked for me
$stmt=$con->prepare('insert into
Scan(ScanType, start_date, end_date, TargetTargetID) values
(:ScanType, :start_date, :end_date, :TargetTargetID)');
$stmt->bindValue('ScanType',$ScanType);
$stmt->bindValue('start_date',$start_date);
$stmt->bindValue('end_date',$end_date);
$stmt->bindValue('TargetTargetID',$TargetTargetID);
$stmt->execute();
No need to pass auto increment column value in insert query just remove from columns and values to
$stmt=$con->prepare('insert into
Scan(ScanType, start_date, end_date, TargetTargetID) values
(:ScanType, :start_date, :end_date, :TargetTargetID)');
Remove from bind values
$stmt->bindValue('ScanID',NULL);
I have a database with just over 70 million rows in. This data was originally parsed and imported from roughly 70,000 XML files. These files are updated every week so I need to scan through these XML files (via a cron on Sundays at 2AM in the morning) and update rows that have changed/insert new rows.
$operatorSQL = "INSERT IGNORE INTO `operator` (`reference`, `national_operator_code`, `operator_code`, `operator_short_name`, `operator_name_on_license`, `trading_name`) VALUES (:reference, :nationalOperatorCode, :operatorCode, :operatorShortName, :operatorNameOnLicense, :tradingName);";
$serviceSQL = "INSERT IGNORE INTO `service` (`service_code`, `private_code`, `date_start`, `date_end`, `mode`, `description`, `origin`, `destination`) VALUES (:serviceCode, :privateCode, :dateStart, :dateEnd, :mode, :description, :origin, :destination);";
$serviceOperatorSQL = "INSERT IGNORE INTO `service_operator` (`service_code`, `operator_reference`) VALUES (:serviceCode, :operatorReference);";
$journeyPatternSQL = "INSERT IGNORE INTO `journey_pattern` (`reference`, `direction`, `destination_display`, `vehicle_type_code`, `vehicle_type_description`) VALUES (:reference, :direction, :destinationDisplay, :vehicleTypeCode, :vehicleTypeDescription);";
$journeyPatternRouteSQL = "INSERT IGNORE INTO `journey_pattern_route` (`journey_pattern_reference`, `route_reference`) VALUES (:reference, :routeReference);";
$journeyPatternSectionLink = "INSERT IGNORE INTO `journey_pattern_section_link` (`journey_pattern_reference`, `journey_pattern_section_reference`) VALUES (:reference, :journeyPatternSectionReference);";
$journeyPatternSectionSQL = "INSERT IGNORE INTO `journey_pattern_section` (`reference`) VALUES (:reference);";
$lineSQL = "INSERT IGNORE INTO `service_line` (`service_code`, `name`) VALUES (:serviceCode, :name);";
$timingLinkSQL = "INSERT IGNORE INTO `journey_pattern_timing_link` (`reference`, `stop_from`, `stop_from_timing`, `stop_from_sequence_number`, `stop_from_activity`, `stop_to`, `stop_to_timing`, `stop_to_sequence`, `stop_to_activity`, `run_time`, `direction`) VALUES (:reference, :stopFrom, :stopFromTiming, :stopFromSequenceNumber, :stopFromActivity, :stopTo, :stopToTiming, :stopToSequenceNumber, :stopToActivity, :runTime, :direction)";
$timingLinkJpsSQL = "INSERT INTO `journey_pattern_timing_link_jps` (`journey_pattern_timing_link`, `journey_pattern_section_reference`) VALUES (:linkReference, :sectionReference);";
$timingLinkRouteLinkRefSQL = "INSERT INTO `journey_pattern_timing_link_rlr` (`journey_pattern_timing_link`, `route_link_reference`) VALUES (:linkReference, :routeLinkReference);";
$routeSQL = "INSERT IGNORE INTO `route` (`reference`, `private_code`, `description`) VALUES (:reference, :privateCode, :description);";
$routeSectionSQL = "INSERT IGNORE INTO `route_section` (`reference`) VALUES (:reference);";
$routeLinkSQL = "INSERT IGNORE INTO `route_link` (`reference`, `stop_from`, `stop_to`, `direction`, `distance`) VALUES (:reference, :stopFrom, :stopTo, :direction, :distance);";
$routeLinkSectionSQL = "INSERT INTO `route_link_section` (`route_link_reference`, `route_section_reference`) VALUES (:routeLinkReference, :routeSectionReference);";
$vehicleJourneySQL = "INSERT IGNORE INTO `vehicle_journey` (`reference`, `private_code`, `departure`) VALUES (:reference, :privateCode, :departure);";
$vehicleJourneyServiceSQL = "INSERT IGNORE INTO `vehicle_journey_service` (`vehicle_journey_reference`, `service_reference`) VALUES (:reference, :serviceRef);";
$vehicleJourneyLineSQL = "INSERT IGNORE INTO `vehicle_journey_line` (`vehicle_journey_reference`, `service_line_reference`) VALUES (:reference, :lineRef);";
$vehicleJourneyJpSQL = "INSERT IGNORE INTO `vehicle_journey_jp` (`vehicle_journey_reference`, `journey_pattern_reference`) VALUES (:reference, :journeyPatternRef);";
Above are all of the SQL queries that are performed. You will notice that the IGNORE clause is used in the INSERT statement, this is just to make sure that if any files have duplicate data no errors will stop the script, instead it'll just ignore it and move on.
I don't feel this is the most efficient way of doing it however as when I run the script again after doing the initial insert of all the data it's just as slow as when the original inserts are executed... surely if 99.9% of the rows are the same it should skim through? Any ideas why this is happening?
Query optimisation is normally for select, update and delete queries. The fact that you are just inserting data into table(s) means there is no query optimisation to be done; the engine does not have to work out some complicated plan to shove that data into the tables. The speed at which it will do the insert is just a function of your CPU, hard-disk speed, I/O network bandwidth, amongst other factors. The data you are inserting is not being cached in any sense so if you do the inserts again, it will be done at the same rate.
First, I would determine whether the performance issue is with the XML parsing or the database. What happens if you run the program but simply leave out the calls to the database -- does it take significantly less time than with the database calls in?
If it's the database I would do the following, if reasonably possibly given the nature of your data:
If possible, divide the task into multiple passes across the data, each pass representing a single table's worth of INSERTs.
Read and cache sufficient key information for all records in the table in a performance-oriented data structure so that you can perform the "do I have the record" check in memory.
For each record found in the input, only issue an INSERT statement if the cached-memory check indicates you don't have the record already.
This will be possible if your key information is not large (integer key values, for instance) and if you're not running on a memory-constricted box. Otherwise, the cached keys may not fit in memory. If this is the case
I'm making a search engine based on the API of Faroo.com (http://www.faroo.com/hp/api/api.html) for a school project. I would like to index the index of Faroo, so that users (in my situation, children) can vote up or vote down individual results.
What my (PHP)-script is like:
Look in the MySQL-database if the query exists.
yes => load the results from the database and show them to the user
no => load the results from Faroo, show those results to the user and store them in the database
My database looks like this:
I'm getting all the data stored in the columns from the Faroo API, except for the 'id'-column.
The last part (of storing the Faroo-data in the database) is where it goes wrong:
for($x=0; $x<$tel; $x++){
$sql = "INSERT INTO queries (`id`, `query`, `title`, `url`, `domain`, `kwic`, `votes`) VALUES (NULL, $q, $titles[$x], $urls[$x], $domains[$x], $kwics[$x], 0);";
echo '<br />'.$x.'e query: #'.$sql.'#';
if(!$resultaat = $db->query($sql)){
die('De query kon niet worden uitgevoerd: [' . $db->error . ']');
}
$resultaat = mysqli_fetch_array($resultaat);
}
$tel is a variable which counts the number of results I get from Faroo. It gets defined before this piece of code.
When I run this code, I am getting a nice MySQL-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 'States Bureau of Mines - Wikipedia, the free encyclopedia,
www.wikipedia.org' at line 1
I've searched, and searched, but I couldn't find what the SQL-error is. I think it has something to do with the strange characters in the strings, or maybe my quotation is false?
Kind regards,
Max
I think you need to use single quotes ' for varchar columns, so change as follow
$sql = "INSERT INTO queries (`id`, `query`, `title`, `url`, `domain`, `kwic`, `votes`) VALUES (NULL, '$q', '$titles[$x]', '$urls[$x]', '$domains[$x]', '$kwics[$x]', 0)";
You also have an extra double quote at the end of the query which i removed, you won't need singles quotes for columns id and votes since they are integer fields
I am getting this error here is my code
if(isset($_POST['submit']))
{
$projTit=mysql_escape_string($_POST['projecttitle']);
$projCat=mysql_escape_string($_POST['projectcategory']);
$budget=intval(mysql_escape_string($_POST['budget']));
$description=mysql_escape_string($_POST['editor1']);
$query=sprintf("insert into projects value('%s','%s','%s',%d)",
$projTit,$description,$projCat,$budget);
if (!mysql_query($query)){
die('Error: ' . mysql_error());
}
echo '<p class="record">Your Record has been Added<p>';
}
?>
I have tried to write %d in '' but still not working.
Your table has five columns. However, you are not providing a value for the Project_Id column. This gives you the error you mentioned.
I understand that you're not providing a value since it's likely a PRIMARY KEY that autoincrements. To tell MySQL that you are intentionally not passing a value for that column, you should add NULL as the first value.
value(NULL, '%s','%s','%s',%d)
However, you really should specifically name which columns you are inserting into in case you add a new column at a future date.
INSERT INTO projects (col1, col2, col3, col4) value ('%s','%s','%s',%d)
You should really specify the column names or your app will break if you add a column later, even if it has a useable default value:
INSERT INTO projects
(Project_Title, Project_Description, Project_Category, Project_Budget)
VALUES
(...)
Especially since you have an auto_increment ID column it makes sense; otherwise you'd always have to specify it as NULL in your query.
The easiest (but also ugliest) fix would thus be:
$query=sprintf("insert into projects value (null, '%s','%s','%s',%d)",
$projTit,$description,$projCat,$budget);
The good fix would be this:
$query = sprintf("
INSERT INTO projects
(Project_Title, Project_Description, Project_Category, Project_Budget)
VALUES
('%s', '%s', '%s', %d)
", $projTit,$description,$projCat,$budget);
By the way, consider using PDO - then you can use something similar to a format string but don't have to deal with escaping.
try naming the columns you want to fill like
insert into projects (col1, col2, col3) values (...)