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);
Related
The portion that is trying to delete duplicate entries in the database seems incorrect. So I suppose I am asking what would be the correct way to do that in this example. I am not totally new to PHP , but this is beyond me. If you could please tell me what is wrong and how to fix that would be greatly appreciated.
Now on to what I am trying to accomplish. I have a multidimensional array filled with values that is generated by a function. What I am trying to do is if there is a value in the array that already exists in the database delete it. Code:
enter code here
if(is_array($items)){
$values = array();
foreach($items as $row => $value){
$rsn = mysqli_real_escape_string($connect, $value[0]);
$rank = mysqli_real_escape_string($connect, $value[1]);
$values[] = "('', '$rsn', '$rank', '')";
$sql = "SELECT id FROM users WHERE rsn = :rsn";
$query = $conn->prepare($sql);
$query->execute(array(":rsn" => $value[0]));
$results = $query->rowCount();
while($deleted = $query->fetch(PDO::FETCH_ASSOC)){
$sql = "DELETE FROM users WHERE id = :id";
$query = $conn->prepare($sql);
foreach($deleted as $delete){
$query->execute(array(':id' => $delete));
}
}
}
//user_exists_delete($conn, $rsn);
$sql = "INSERT INTO users(id, rsn, rank, points) VALUES ";
$sql .= implode(', ', $values);
if(!empty($rank)&& !empty($rsn)){
if(mysqli_query($connect, $sql)){
echo "success";
}else{
die(mysqli_error($connect));
}
}
}
EDIT: I have got it partially working now, just need it to delete all dupes instead of only one. I edited code to reflect changes.
There are a couple problems, if you didn't strip much of your original code and if you don't need to do more than just what you shown why not just send a delete instruction to your database instead of checking validity first?
You have
//Retrieve ID according to rsn.
$sql = "SELECT id FROM users WHERE rsn = :rsn ";
//Then retrieve rsn using rsn??? Useless
$sql = "SELECT rsn FROM users WHERE rsn = :rsn ";
//Then delete using ID, retrieved by rsn.
$sql = "DELETE FROM users WHERE id = :id";
All those could simply be done with a delete using rsn...
$sql = "DELETE FROM users WHERE rsn = :rsn";
The row won't be deleted if there are no rows to delete, you don't need to check in advance. If you need to do stuff after, then you might need to fetch information before, but if not, you can use that while still checking the affected rows to see if something got deleted.
Now, we could even simplify the script by using only one query instead of one per user... We could get all rsn in an array and then pass it to the DELETE.
$sql = "DELETE FROM users WHERE rsn in :rsn";
//Sorry not exactly sure how to do that in PDO, been a while.
I fixed it I just omitted the WHERE clause in the delete statement so all records are being deleted before that insert gets ran again.
Sorry, I'm new to php / mysql. I'm trying to change an existing script to take the results and then insert the value into the database.
This is what I've tried. I'm guessing I'm missing something or the syntax is wrong:
// unique reference number is generated.
// check if it exists or not
$query = "SELECT `ID_UNIQUE` FROM `tbl_referrals`
WHERE `ID_UNIQUE`='".$unique_ref."'";
$result = mysql_query($query) or die(mysql_error().' '.$query);
if (mysql_num_rows($result)==0) {
// We've found a unique number. Lets set the $unique_ref_found
// variable to true and exit the while loop
$unique_ref_found = true;
$sql = "INSERT INTO `tbl_referrals` (`ID_UNIQUE`)
VALUES
(`ID_UNIQUE`)";
}
}
echo 'Your reference number is: '.$unique_ref;
Ticks are for identifiers, single quotes are for string values:
$sql = "INSERT INTO `tbl_referrals` (`ID_UNIQUE`)
VALUES
('ID_UNIQUE')";
}
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);
Basically, I wanna go through the entire table from top to bottom. If the item already exists, update the row with new data. If not, append the data to the table. How do I go about implementing this? Thank you
Update: That would be simple in raw query, however, Im using it on a MVC architecture.
Here i can suggest to use magento inbuilt function insertOnDuplicate
$bind = array(
'product_link_attribute_id' => $attributeInfo['id'],
'link_id' => $linkId,
'value' => $value
);
$adapter->insertOnDuplicate($attributeTable, $bind, array('value'));
where $bind is the array or row value you want to insert and third argument in function should be array('value') and this would be list of column you want to check if value is already exist in table with same value.
Also you can find implementaion of this method in below file
lib\Varien\Db\Adapter\Pdo\Mysql.php
hope this will sure help you.
the REPLACE command will delete the row if the key exists, and insert the same info afterwards.
This means that any auto incremental key will be changed after performing the operation because it's not the same row. It's a new one with the exact info from the previosly deleted row.
Please check this code :
function sendtodb($data) {
$invoiceid = $data['invoiceid'];
if($invoiceid != "") {
$checkinvoice = mysql_query("SELECT * FROM `paypal_ajustment_data_pure` WHERE `InvoiceID`='$invoiceid'") or die(mysql_error());
if(mysql_num_rows($checkinvoice) > 0) {
$paypalreferenceid = $data['paypalreferenceid'];
$checkpreferenceid = mysql_query("SELECT * FROM `paypal_ajustment_data_pure` WHERE `InvoiceID`='$invoiceid' AND `PayPalReferenceID`='$paypalreferenceid'") or die(mysql_error());
if(mysql_num_rows($checkpreferenceid) == 0)
$updatereferncceid = mysql_query("UPDATE `paypal_ajustment_data_pure` SET `PayPalReferenceID`='$paypalreferenceid' WHERE `InvoiceID`='$invoiceid'") or die(mysql_error());
}
else {
mysql_query("INSERT INTO `nume_mage`.`paypal_ajustment_data_pure` (`id`, `TransactionID`, `InvoiceID`, `PayPalReferenceID`, `TransactionInitiationDate`, `TransactionCompletionDate`, `status`) VALUES (NULL, '$data[TransactionID]', '$data[invoiceid]', '$data[paypalreferenceid]', '$data[transactionintiationdate]', '$data[transactioncompletedate]', '1')") or die(mysql_error());
}
mysql_query("update `paypal_ajustment_data` set status=2 where id= '$data[id]'") or die(mysql_error());
}
else {
mysql_query("update `paypal_ajustment_data` set status=3 where id= '$data[id]'") or die(mysql_error());
}
}
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