CSV Import to Mysql data not being added to table - mysql

Hi I have the following piece of code which is supposed to upload a csv file and add the information to the database. even though it gets to the echo import complete no data is being added to the table.
copy($_FILES["fileCSV"]["tmp_name"],"shotdev/".$_FILES["fileCSV"]["name"]); // Copy/Upload CSV
$objCSV = fopen("shotdev/".$_FILES["fileCSV"]["name"], "r");
while (($objArr = fgetcsv($objCSV, 1000, ",")) !== FALSE) {
$strSQL = "INSERT INTO customer_list ";
$strSQL .="(company_name,website,owner,email_addredd,client_id) ";
$strSQL .="VALUES ";
$strSQL .="('".$objArr[0]."','".$objArr[1]."','".$objArr[2]."' ";
$strSQL .=",'".$objArr[3]."','".$objArr[4]."','".$objArr[5]."') ";
$objQuery = mysql_query($strSQL);
}
fclose($objCSV);
echo "Import completed.";
This is my table structure
customer_list` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`company_name` varchar(100) NOT NULL,
`website` varchar(100) NOT NULL,
`owner` varchar(100) NOT NULL,
`email_addredd` varchar(200) NOT NULL,
`client_id` int(10) NOT NULL,
PRIMARY KEY (`id`)
)

I am not exactly sure what is wrong, but you should be testing the value of $objQuery. If it is false, you should echo mysql_error() and die. That is the standard way to call mysql_query().

Related

SQL query is not inserting records in table when column values are equal

I am trying to execute this query but it is not working. whenever i try to put same equal values to any two or more input variables out of total 8, the SQL query does not execute.
php file:
include './config.php';
$counter = 0;
// these are my total 8 input variables
$INDEX_NUMBER = "43385";
$STATION_NAME = "NA";
$YEAR = "2020";
$MONTH = "12";
$DATE = "18";
$Ir = "3";
$RAIN_24HOURS_ACTUAL = "NA";
$RTRTRTRT = "NA";
$sql_rain_2 ="INSERT INTO `only_rainfall_2020` (`INDEX_NUMBER`, `STATION_NAME`, `YEAR`, `MONTH`, `DATE`, `Ir`, `DAILY`, `SEASONALLY_SYNOP`) SELECT * FROM (SELECT '$INDEX_NUMBER', '$STATION_NAME', '$YEAR', '$MONTH', '$DATE', '$Ir', '$RAIN_24HOURS_ACTUAL', '$RTRTRTRT') AS tmp WHERE NOT EXISTS (SELECT `INDEX_NUMBER`, `STATION_NAME`, `YEAR`, `MONTH`, `DATE`, `Ir`, `DAILY`, `SEASONALLY_SYNOP` FROM `only_rainfall_2020` WHERE `INDEX_NUMBER` = '$INDEX_NUMBER' AND `STATION_NAME` = '$STATION_NAME' AND `YEAR` = '$YEAR' AND `MONTH` = '$MONTH' AND `DATE` = '$DATE' AND `Ir` = '$Ir' AND `DAILY` = '$RAIN_24HOURS_ACTUAL' AND `SEASONALLY_SYNOP` = '$RTRTRTRT') LIMIT 1";
if (mysqli_query($conn, $sql_rain_2)) {
$counter++;
}
$array = array("rain1"=>$counter, "rain2"=>"yogi");
echo json_encode($array);
mysql table:
CREATE TABLE `only_rainfall_2020` (
`SERIAL` int(11) NOT NULL,
`SUB_DIVISION_NUMBER` varchar(2) NOT NULL,
`SUB_DIVISION_NAME` varchar(20) NOT NULL,
`INDEX_NUMBER` varchar(5) NOT NULL,
`STATION_NAME` varchar(30) NOT NULL,
`YEAR` varchar(4) NOT NULL,
`MONTH` varchar(2) NOT NULL,
`DATE` varchar(2) NOT NULL,
`Ir` varchar(2) NOT NULL,
`DAILY` varchar(7) NOT NULL,
`MONTHLY` varchar(7) NOT NULL,
`SEASONALLY_SYNOP` varchar(7) NOT NULL,
`SEASONALLY_CALCULATE` varchar(7) NOT NULL,
`ANNUALLY` varchar(7) NOT NULL,
`COMMENT` varchar(50) NOT NULL,
`MANUALLY_EDIT_VALUE` varchar(14) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `only_rainfall_2020`
ADD PRIMARY KEY (`SERIAL`);
ALTER TABLE `only_rainfall_2020`
MODIFY `SERIAL` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
Please point out my mistake.
After many attempts i could not find my mistake.
let me clear it again:
I am trying to insert data for 8 columns into a table which has total 16 columns. In my table, one column is for serial number which is auto incremental, seven are blank columns and eight are the columns in which i am inserting data. I am leaving seven blank column for future work with no default values. the condition for inserting data for these eight column: any row should not exist with same data for these eight columns which i am going to insert. when i give different values for these eight columns than query is successful and data inserted but when i put same values for any two or more columns than query does not execute.
this is successful:
$INDEX_NUMBER = "43385";
$STATION_NAME = "DELHI";
$YEAR = "2020";
$MONTH = "12";
$DATE = "18";
$Ir = "3";
$RAIN_24HOURS_ACTUAL = "NA";
$RTRTRTRT = "20";
But when i put any two values same the query does not execute.
Failed with error: (#1060 - Duplicate column name 'NA')
$INDEX_NUMBER = "43385";
$STATION_NAME = "NA";
$YEAR = "2020";
$MONTH = "12";
$DATE = "18";
$Ir = "3";
$RAIN_24HOURS_ACTUAL = "NA";
$RTRTRTRT = "NA";
And yes there are warnings for like:
Warning: #1364 Field 'SUB_DIVISION_NUMBER' doesn't have a default value
But i will add values in these columns later.

How to copy multiple row from a table and insert those to another table in MySql DB with PHP?

<?php
$conn = mysqli_connect('hostname','username','passwd','dbname');
$query = 'SELECT name,mobileno FROM test';
$result = mysqli_query($conn,$query);
while($row = $result->fetch_array()) {
$name = $row['name'];
$monileno = $row['mobileno'];
$query2 = "INSERT INTO test2(name2,mobileno2) VALUES('$name','$monileno')";
mysqli_query($conn,$query2);
}
?>
CREATE TABLE `test` (
`id` INT(9) AUTO_INCREMENT PRIMARY KEY,
`name` varchar(128) NOT NULL,
`mobileno` varchar(128) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `test` (`id`, `name`, `mobileno`) VALUES
(1, 'Omar Faruq', '01911775477'),
(2, 'omar Al Faruq', '01911775477'),
(3, 'Helal Uddin', '01914351075');
CREATE TABLE `test2` (
`id` INT(9) AUTO_INCREMENT PRIMARY KEY,
`name` varchar(128) NOT NULL,
`mobileno` varchar(128) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
This code works on Xampp/wamp but when I upload this script to RHEL7.2 web server it does not works.
<?php
$conn = mysqli_connect('hostname','username','passwd','dbname');
$query = 'SELECT name,mobileno FROM test';
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($result)) {
$name = mysqli_escape_string($conn, $row['name']);
$monileno = mysqli_escape_string($conn, $row['mobileno']);
$query2 = "INSERT INTO test2(name2,mobileno2) VALUES('$name','$monileno')";
mysqli_query($conn,$query2);
?>
and change on Database :
CREATE TABLE test2 (
id INT(9) AUTO_INCREMENT PRIMARY KEY,
name2 varchar(128) DEFAULT NULL,
mobileno2 varchar(128) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Finally it works on RHEL7. I am really happy...... Thanks All
try replacing
while($row = $result->fetch_array()) {
with
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// OR
while ($row = mysqli_fetch_assoc($result)) {
It seem's like you we're mixing between the object-oriented usage style and the procedural style.
I'm surprised this worked for you. probably might be due to different php versions.
same thing can apply to
VALUES('$name','$monileno')";
//replace with
VALUES('" . mysqli_escape_string($conn, $name) . "', '" . mysqli_escape_string($conn, $monileno) . "')";

Plugin not creating 2nd table on activation

I created the first table for my plugin, and after working on adding more features I realized I needed to add a second table for an additional type of data.
Troubleshooting efforts so far have resolved the issue with dbDelta() not using the same variable name for the sql data, running dbDelta() both as a combined sql var ($setup_sql .= '...' instead of $setup_sql = '...'), and also running the code as a simple function rather than a class.
I even tried running a single table creation with a different name, just to check the code worked, and it still didn't create another table.
I have had no errors running through all these tests, and for all intents and purposes it seems that Wordpress doesn't allow a plugin to create more than one table - but I know that's not the case.
class activation_setup {
public static function wpd_activate() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
$wpd_table_trig = $wpdb->prefix . 'wpd_triggers';
$setup_sql_trig = "CREATE TABLE $wpd_table_trig (
id int(11 ) NOT NULL AUTO_INCREMENT,
trigger varchar(255) DEFAULT NULL,
popup varchar(255) DEFAULT NULL,
notify varchar(255) DEFAULT NULL,
UNIQUE KEY id (id)
) $charset_collate;";
dbDelta( $setup_sql_trig );
$wpd_table_sel = $wpdb->prefix . 'wpd_selections';
$setup_sql_sel = "CREATE TABLE $wpd_table_sel (
id int(11 ) NOT NULL AUTO_INCREMENT,
selected varchar(255) DEFAULT NULL,
session varchar(255) DEFAULT NULL,
ip varchar(255) DEFAULT NULL,
page varchar(255) DEFAULT NULL,
date varchar(255) DEFAULT NULL,
UNIQUE KEY id (id)
) $charset_collate;";
dbDelta( $setup_sql_sel );
update_option('wpd_activated',true);
}
}
$activation_setup = new activation_setup();
register_activation_hook( __FILE__ , array( $activation_setup, 'wpd_activate' ) );
I'm going absolutely nuts trying to work out WHY this code doesn't add the second table, even after stripping out the duplicate table code and running it with a different table name.
I've through a ton of blog posts and Stack answers trying to get to the bottom of it.
Any help would be fantastic.
Issue is with the table definition.
You've written trigger in your table definition it is keyword also for mysql.
That was the issue.
Your problem will be solved by this change.
Use "`" when writing field name.
class activation_setup {
public static function wpd_activate() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
$wpd_table_trig = $wpdb->prefix . 'wpd_triggers';
$setup_sql_trig = "CREATE TABLE $wpd_table_trig (
`id` int(11 ) NOT NULL AUTO_INCREMENT,
`trigger` varchar(255) DEFAULT NULL,
`popup` varchar(255) DEFAULT NULL,
`notify` varchar(255) DEFAULT NULL,
UNIQUE KEY id (id)
) $charset_collate;";
dbDelta( $setup_sql_trig );
$wpd_table_sel = $wpdb->prefix . 'wpd_selections';
$setup_sql_sel = "CREATE TABLE $wpd_table_sel (
`id` int(11 ) NOT NULL AUTO_INCREMENT,
`selected` varchar(255) DEFAULT NULL,
`session` varchar(255) DEFAULT NULL,
`ip` varchar(255) DEFAULT NULL,
`page` varchar(255) DEFAULT NULL,
`date` varchar(255) DEFAULT NULL,
UNIQUE KEY id (id)
) $charset_collate;";
dbDelta( $setup_sql_sel );
}
}
$activation_setup = new activation_setup();
register_activation_hook( __FILE__ , array( $activation_setup, 'wpd_activate' ) );
If you want to make sure that issue is with that trigger then remove "`" from trigger field and then again activate plugin.

Zend update() gives out application error even with correct parameters

I am using Zend_File_Transfer_Adapter_HTTP() to upload a file (image) and then with Application_Model_DbTable_User() to update the users mysql table with the corresponding path of the file .
This is the action in the controller :
public function profileAction() {
$form = new Application_Form_Updateprofile();
$users = new Application_Model_DbTable_User();
$session = new Zend_Auth_Storage_Session();
$adapter = new Zend_File_Transfer_Adapter_HTTP();
$loggedUser = $session->read()->username;
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$adapter->setDestination('ProfilePhotos');
$filename = pathinfo($form->image->getFileName());
$adapter->addFilter('Rename', uniqid() . '.' . $filename['extension']);
if (!$adapter->receive()) {
$messages = $adapter->getMessages();
echo implode("\n", $messages);
} else {
$userProfilePhoto = $adapter->getFileName('image');
$users->UpdateProfilePic($loggedUser, $userProfilePhoto);
}
}
}
This is the function UpdateProfilePic() in the Zend_File_Transfer_Adapter_HTTP() :
public function UpdateProfilePic($username, $img_address) {
$bind = array("profile_pic" => $img_address);
$where = "username = $username";
$this->_db->update($this->_name, $bind, $where);
}
Var_dump($username,$img_address,$bind,$where)
Output :
$img_address - string(31) "ProfilePhotos\5429294234ebe.gif"
$username - string(7) "Tiberiu"
$bind - array(1) { ["profile_pic"]=> string(31) "ProfilePhotos\5429294234ebe.gif" }
$where - string(18) "username = Tiberiu"
Users table :
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`username` varchar(30) NOT NULL,
`password` varchar(15) DEFAULT NULL,
`profile_pic` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
This is my first attempt on Zend_File_Upload and although the file transfer is a success it won't update the users table and I can't figure out why , I've checked the manual and I think I'm feeding the correct parameters to the update() action.
The mistake was in UpdateProfilePic() function in my db class .
It should be :
$where = "`username` = '$username'";
Instead of :
$where = "`username` = $username";

If only one record from row duplicate

I have problem with record which I must record in my table. I want update row if product with same name exist.
if ((int)$price > 0) {
$query = "SELECT name FROM phones WHERE LOWER(`name`) = LOWER(?)";
$duplicate = $this->db->query($query, array($name));
if ($duplicate->num_rows() > 0) {
$query = "update phones (name,price,shop,link,photo,priority) VALUES (?,?,?,?,?,?)";
$this->db->query($query, array($name,$price,"Pigu.lt", $link, $photos, rand(0,1000)));
} else {
$query = "insert into phones (name,price,shop,link,photo,priority) VALUES (?,?,?,?,?,?)";
$this->db->query($query, array($name,$price,"Pigu.lt", $link, $photos, rand(0,1000)));
}
}
table structure:
CREATE TABLE `phones` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(500)
COLLATE utf8_lithuanian_ci NOT NULL, `price` int(15)
NOT NULL, `shop` varchar(100)
COLLATE utf8_lithuanian_ci NOT NULL, `link` varchar(400)
COLLATE utf8_lithuanian_ci NOT NULL, `photo` varchar(500)
COLLATE utf8_lithuanian_ci NOT NULL, `priority` int(5)
NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=544 DEFAULT CHARSET=utf8 COLLATE=utf8_lithuanian_ci;
at know code dont work, please help for this
I do not know the reason why your PHP doesn't work, but since you tagged your post with mysql and sql and not php, I assume you'll accept a SQL-centric solution. Here are two; both assume that name is the primary key in table phones.
ANSI-compliant:
$query = "INSERT INTO phones (name, price, shop, link, photo, priority) \
VALUES (?,?,?,?,?,?) \
ON DUPLICATE KEY UPDATE price=?, shop=?, link=?, photo=?, priority=?";
$randnum = rand(0, 1000);
$this->db->query($query, array($name, $price, "Pigu.lt", $link, $photos, $randnum,
$price, "Pigu.lt", $link, $photos, $randnum));
MySQL-only:
$query = "REPLACE INTO phones (name, price, shop, link, photo, priority) \
VALUES (?,?,?,?,?,?)";
$this->db->query($query, array($name, $price, "Pigu.lt", $link, $photos, rand(0,1000)));