Better way of inserting multiple strings in a mysql database - php

So, I've got a few txt files, each container around 400,000 lines.
Each line is a word, I need to add to my database, if it isn't in there already.
Currently my code for checking/adding every word is
$sql = mysql_sql("SELECT `id` FROM `word_list` WHERE `word`='{$word}' LIMIT 1");
$num = mysql_num($sql);
if($num == '0'){
$length = strlen($word);
$timestamp = time();
#mysql_sql("INSERT INTO `word_list` (`word`, `length`, `timestamp`) VALUES ('{$word}', '{$length}', '{$timestamp}')");
}
and the functions being called are:
function mysql_sql($sql){
global $db;
$result = $db->query($sql);
return $result;
}
function mysql_num($result){
return $result->num_rows;
}
I'm looking for a better way to insert each word into the database.
Any ideas would be greatly appreciated.

I can think of some ways to do this.
First, if you have access to the MySQL server's file system you can use LOAD DATA INFILE to create a new table, then do an insert from that new table into your word_list table. This will most likely be your fastest option.
Second (if you don't have access to the MySQL server's file system), put a primary key or unique index on word_list.word. Then get rid of your SELECT query and use INSERT IGNORE INTO word_list .... That will allow MySQL automatically to skip the duplicate items without any need for you to do it with a query/insert operation.
Third, if your table uses an access method that handles transactions (InnoDB, not MyISAM), issue a BEGIN; statement before you start your insert loop. Then every couple of hundred rows issue COMMIT;BEGIN; . Then at the end issue COMMIT;. This will wrap your operations in multirow transactions so will speed things up a lot.

Try out this code. It will first create query with all your values and you will run query only ONCE ... Not again and again for ever row
$values = array();
$sql = mysql_sql("SELECT `id` FROM `word_list` WHERE `word`='{$word}' LIMIT 1");
$num = mysql_num($sql);
$insert_query = "INSERT INTO `word_list` (`word`, `length`, `timestamp`) VALUES ";
if ($num == '0') {
$length = strlen($word);
$timestamp = time();
$values[] = "('$word', '$length', '$timestamp')";
}
$insert_query .= implode(', ', $values);
#mysql_sql($insert_query);

Related

How to compare input from a user php post to a MySQL

I am teaching myself php and MySQL, and right now I have a problem with MySQL.
I want to compare the phone number that the user put in with the phone number in MYSQL, and if it is in MYSQL to not register it again.
My code:
<?php
require_once 'connection/connection.php';
// Variables from HTML to php
$worker_Name = $_POST['workerNameFromHtml']; // worker Name
$worker_City = $_POST['workerCityFromHtml']; // workerCity
$worker_career = $_POST['workerCareerFromHtml']; // worker career
$worker_PhoneNumber = $_POST['workerPhonNumberFromHtml']; // worker Phone Number
$worker_SecondPhoneNumber = $_POST['workerSecondPhoneNumberFromHtml']; // worker Second Phone Number
$submt=$_POST['submitFromHtml'];
if($submt){
$qry = ( "SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'") or die(mysql_error());
$result = $connect->query($qry);
$num = $result->num_rows;
if ($num == 1) {
$here = "INSERT INTO workersTable VALUES('','$worker_Name','$worker_City','$worker_career','$worker_PhoneNumber','$worker_SecondPhoneNumber')";
$query = $connect->query($here);
print "Successfully added!";
}
else {print "This number has already been entered Thank you for your cooperation!";}}
$connect->close();
So far I have not found a solution to this problem.
your biggest problem here is that you are trying to include variables inside of a string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'"
If you want to do it this way, you need to concatenate your variables with your string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '".$worker_PhoneNumber."'"
Keep in mind if you do this you will want to sanitize your variables first to prevent SQL injections. Also, when you INSERT variables, you will actually want to use a prepared statement like this:
"INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"
where the 1st set of values are the names of your columns in the database and the second set are your PHP variables you are putting into it.

Inserting multiple values of an array into database

I am trying to read a file of data and insert into a table in mySQL. I have tried building an array and imploding, as well as a foreach loop like this one but only get back the first row of the table.
<?php
$str = file_get_contents('-');
$con = mysqli_connect('-', '-', '-','-');
$dataArray = explode("|",$str);
$blahArray = array();
foreach($dataArray as $info){
$pD = unserialize($info);
$pD->*->*->*;
$pL = $pD->*->*->*[0];
$blah = $pL->BLAH;
array_push($blahArray,$blah);
}
foreach($blahArray as $val){
$sql = "INSERT INTO table (BLAH)
VALUES('$val')";
mysqli_query($con,$sql);
}
?>
I have a lot more datafields to enter but for debugging am just trying the one. Any help or suggestions would be greatly appreciated!
I can't say for certain what is wrong with your code, but here is a modification you can make which might tell you what is going on:
foreach($apnArray as $val) {
$sql = "INSERT INTO property (APN) VALUES('$val')";
$result = mysqli_query($con, $sql);
if (false===$result) {
printf("error: %s\n", mysqli_error($con));
}
}
Check for two things. First, make sure that you are in fact looping 90 times. Second, see if each INSERT query be executing with or without error.
Update:
Based on your comment, it appears that you have a primary key with a unique constraint, which is not set to autoincrement. In your INSERT query, you are only setting a value for the APN column and nothing else. This means that MySQL is using a default value (0) for this primary key. The solution to your problem is to pass in a unique value for the primary key or to set that primary key column to autoincrement.
Try this:
$sql = "INSERT INTO property (APN)
VALUES";
foreach ($apnArray as $val) {
$sql .= "('$val'),";
}
$sql = trim($sql, ",");
mysqli_query($con, $sql);

php multiple record insert to sql not working

Hi all I have a form where I'm entering students marks for exams, what I am trying to do is enter multiple marks in at once...but it just is not working, could someone help please? It is adding only ONE result, doesn't enter all that I write in.
FORM Code:
The script does not know what is $i in this case.
Use for loop:
$mark=$_POST['mark'];
$time=$_POST['time'];
$meID=$_POST['meID'];
$sID=$_POST['sID'];
for($i = 0; $i < count($_POST['mark']); $i++) {
$_mark = mysql_escape_string($mark[$i]);
$_time = mysql_escape_string($time[$i]);
$_meID = mysql_escape_string($meID[$i]);
$_sID = mysql_escape_string($sID[$i]);
$sql = "INSERT INTO Marks (mark, time, meID, sID) VALUES ($_mark, $_time, $_meID, $_sID)";
$result = mysql_query($sql);
}
Additionally you will add each mark twice, because of two mysql_query() invocations. I've already deleted one from $sql variable in my answer. Also you have wrong variable names in the insert query.
I think the problem is with the variable names:
Following line:
$sql = "SELECT * FROM ModuleExamStudent WHERE mesID = '$mesID'";
But there is no $mesID. It should be $mes:
$sql = "SELECT * FROM ModuleExamStudent WHERE mesID = '$mes'";
Again:
$sql = mysql_query("INSERT INTO Marks (mark, time, meID, sID) VALUES ('$mark', '$time', '$meID', '$sID')");
Should be:
$sql = mysql_query("INSERT INTO Marks (mark, time, meID, sID) VALUES ('$_mark', '$_time', '$_meID', '$_sID')");
there is no mysql_escape_string . try replace this;
$_mark = mysql_escape_string($mark[$i]);
to
$_mark = mysql_real_escape_string($mark[$i]);
and put $_mark in the query instead of $mark
and replace all others also.
Yeah, a lot of mistakes in you're code.
Fuse michal.hubczyk and Ambrish answer to obtain wath you want.
If i can suggest another way to do it, i'll prefer to make only one query instead an elevated number of query succession inside a loop.
Try this method
Inserting multiple rows in a single SQL query?
and build your query in a way like this:
$sql = "INSERT INTO XX VALUES";
for($i=0;$i < count($_POST['mark']); $i++){
$_mark = mysql_escape_string($mark[$i]);
$_time = mysql_escape_string($time[$i]);
$_meID = mysql_escape_string($meID[$i]);
$_sID = mysql_escape_string($sID[$i]);
$sql .= "(".$_mark.",".$_time",".$_meID.",".$sID.")";
if($i<(count($_POST['mark']-1))){
$sql .= ",";
}
$result = mysql_query($sql);
Another suggestion is to use mysqli libray instead mysql ( http://php.net/mysqli)

How to INSERT in one table and UPDATE in another in single QUERY?

I'm currently creating some sort of inventory system.
I have master_tbl where in I save the items. In master_tbl, I have column qty_left or the available stock left.
I also have the table issuance_tbl where in I save all the transaction in issuing items.
In this table there is issued_qty.
My problem is how can I INSERT a row into issuance_tbl at the same time UPDATE the master_tbl.qty_left. (master_tbl.qty_left - issuance_tbl.issued_qty).
Is it possible?
I think the best way is using Stored Procedure. You can have bunch of SQL statements with error handling and ACID transactions in one place. This is because if your first query executes and the second fails, you may need to rollback transactions. Stored procedures allow all this fancy but reliable stuff.
You can start here: http://forums.mysql.com/read.php?98,358569
I'm not completely confident that 'If there's any way to do such thing':
You need to do it in steps, LIKE THIS:
$result = $this->db->insert($table);//Example function to insert inventory item
$insert_id = $this->db->insert_id();//Example function to get the id of inserted item
if($result)
$res = $this->db->update($id,$data,$table);//Example function to update data of quantity table
if(!$res)
{
$this->db->delete($insert_id,$table);s
$result = '-1';
}
return $result;
Hope this might help
here is the example:
<form method="post">
QTY:<input type="text" name="qty_left"></input>
<input type="submit" name="submit" value="update"></form>
<?php
////////your config db
$qty = $_POST['qty_left'];
if(isset($_POST['submit']);
$sql = mysql_query("insert into issuance_tbl (issued_qty) values (".$qty.") ");
$sql1 = mysql_query("update master_table set qty_left= ".$qty."");
?>
$con = mysqli_connect($host, $user, $password, $database);
...
$issued_qty = '10'; //some value
$insert_query = "insert into issuance_table (issued_qty, ...) values ('$issued_qty', ... ) ;";
$update_query = "update master_tbl set qty_left = (qty_left - ".$issued_qty.") where ....";
mysqli_multi_query($con, $insert_query.$update_query);

Can I do multiple update SQL with php?

I want to edit a table from my database.That table have many data.
I will show sample.Do I need to write many mysql update statement?Have other method to write a only one statement? I am beginner for php? Thank all my friend.Sorry for my english.
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle1',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext1',
WHERE `id` ='$id1';");
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle2',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext2',
WHERE `id` ='$id2';");
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle3',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext3',
WHERE `id` ='$id3';");
etc.............
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle30',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext30',
WHERE `id` ='$id30';");
You want to update multiple rows from one table with specific data, so bad news you have to do it one by one.... but you can improve your code. If I where you I will create a function and I just call it, something like
function update_my_data($movilefilltex1,$id1){
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle1',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext1',
WHERE `id` ='$id1';");
.......
}
So to make the multiple insert you can call update_my_data(value1,valu2) the times that you need. for example in a loop or just whenever you need it.
If there is a UNIQUE index on id (and there will be if it's your PRIMARY KEY), you could use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO mytablename (id, mobiletitle, mobilepublished, mobiletext) VALUES
('$id1', '$mobiletitle1', 1, '$mobilefulltext1'),
('$id2', '$mobiletitle2', 1, '$mobilefulltext2'),
-- etc.
ON DUPLICATE KEY UPDATE
mobiletitle = VALUES(mobiletitle),
mobilepublished = VALUES(mobilepublished)
mobiletext = VALUES(mobiletext);
Note that this will, of course, insert new records if they don't already exist; whereas your multiple-UPDATE command approach will not (it would raise an error instead).
In either case, you could build/execute the SQL dynamically from within a loop in PHP.
I would also caution that you would be well advised to consider passing your variables to MySQL as parameters to a prepared statement, especially if the content of those variables is outside of your control (as you might be vulnerable to SQL injection). If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
Putting it all together (using PDO instead of the deprecated MySQL extension that you were using):
for ($i = 1; $i <= 30; $i++) {
$sqls[] = '(?, ?, 1, ?)';
$arr[] = ${"id$i"};
$arr[] = ${"mobiletitle$i"};
$arr[] = ${"mobilefulltext$i"};
}
$sql = 'INSERT INTO mytablename (id, mobiletitle, mobilepublished, mobiletext)
VALUES
' . implode(',', $sqls)
. 'ON DUPLICATE KEY UPDATE
mobiletitle = VALUES(mobiletitle),
mobilepublished = VALUES(mobilepublished)
mobiletext = VALUES(mobiletext)';
$db = new PDO("mysql:dbname=$db", $user, $password);
$qry = $db->prepare($sql);
$qry->execute($arr);
Note that you might also consider storing your 1..30 variables in arrays.
update table1,table2 SET table1.column1 = 'valueX',table2.coulumn2 = 'valueX' where table1.column = table2.coulumn2 ;

Categories