I wrote a php script to import a CSV file into a wordpress database. I have been working through lots of different errors today which were crashing the website till I fixed them.
Now all the errors are cleared and the string at the end of the function is being printed to the screen as if everything is ok but it is not entering my data to the DB.
Also for testing sake I removed the create DB part and only left the remove to see if it would remove the DB and it did not. So basically it appears my function does not have errors but it is being ran. Also it is not actually doing anything. I do not understand how it could run through the function telling me each time there is an error or a file path that does not exist but not actually carry out the operations I am trying to execute.
Any input on how to troubleshoot this or where to go from here would be appreciated,
function productsExec() {
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
global $wpdb;
global $simple_prod_version;
$table_name = $wpdb->prefix . "wuno_inventory";
if($wpdb->get_var("show tables like '$table_name'") != $table_name) {
$sql = "DROP TABLE IF EXISTS $table_name";
dbDelta($sql);
// $wpdb->query($sql);
$sql = "CREATE TABLE " . $table_name . " (
id int(8) NOT NULL AUTO_INCREMENT,
wuno-product varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
wuno-description varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
wuno-alternates varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
wuno-onhand varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
wuno-condition varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";
dbDelta($sql);
// $wpdb->query($sql);
//Upload File
if (is_uploaded_file($_FILES['inventory.csv']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['inventory.csv']['name'] ." uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['inventory.csv']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen(inventory.csv, 'w');
while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {
$insert = "INSERT INTO" . $table_name . "(wuno-product, wuno-description, wuno-alternates, wuno-onhand, wuno-condition)" .
"VALUES ('$data[0]', '$data[1]', '$data[2]', '$data[3]', '$data[4]')";
$results = $wpdb->query( $insert );
}
fclose($handle);
echo 'Everything seems to be running smoothly.';
}
}
As mentioned in comments, and as per OP's request:
INSERT INTO" . $table_name . " translates to, and for example INSERT INTOtablename since there is no space between INFO and "
Plus, you have hyphens for column names that MySQL is translating as wuno MINUS product, as a math equation and the same for the other column names.
Consult http://dev.mysql.com/doc/refman/5.7/en/identifier-qualifiers.html on Identifier Qualifiers
You can use hyphens, but ticks are required to be used around the column names.
$insert = "INSERT INTO " . $table_name . " (`wuno-product`, `wuno-description`, `wuno-alternates`, `wuno-onhand`, `wuno-condition`)
Edit:
I spotted something else.
$handle = fopen(inventory.csv, 'w');
There should be quotes around the filename:
$handle = fopen("inventory.csv", 'w');
as per the manual on fopen() http://php.net/manual/en/function.fopen.php
$handle = fopen("c:\\folder\\resource.txt", "r");
and error reporting would have thrown you a notice about it.
Plus, since you're using $_FILES, and if using a form, it should be a POST method and contain a valid enctype.
http://php.net/manual/en/features.file-upload.post-method.php
However, this seems invalid $_FILES['inventory.csv'] or is unclear.
Usually, the first array parameter is a matching name attribute. Consult the manual link just above.
Also add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Related
I am new to wordpress , I am creating the table but I dont know where is the error occuring , hence table is not creating in database , my table code is below
$table_name = $wpdb->prefix . "myuser";
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
`id` int(11) AUTO_INCREAMENT NOT NULL ,
`name` varchar(50) CHARACTER SET utf8 NOT NULL,
`email` varchar(50) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`id`)
) $charset_collate; ";
and I am inserting data in it but there is no error showing neither the table is creating
$table_name = $wpdb->prefix . "myuser";
$wpdb->insert(
$table_name, //table
array('name' => $name, 'email' => $email), //data
array('%s', '%s') //data format
);
$message.="Users added successfully";
You've only defined the sql query yet, you still need to execute it.
According to this article you can use the following code:
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
Just put it right after the part that starts with $sql =.
Assuming you're writing some kind of plugin, notice you'll also have to add the function as register_activation_hook.
For more information, see Writing a plugin and Creating Tables with Plugins.
I am trying to get what should otherwise be a simple but of php to insert sample data into a table, but something just isn't having any of it.
Table Definition:
CREATE TABLE IF NOT EXISTS teams (
token varchar(12) COLLATE utf8_unicode_ci NOT NULL,
tname varchar(48) COLLATE utf8_unicode_ci NOT NULL,
captain varchar(64) COLLATE utf8_unicode_ci NOT NULL,
email varchar(64) COLLATE utf8_unicode_ci NOT NULL,
phone varchar(14) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (token),
UNIQUE KEY name (tname),
KEY id (token)
)
ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Code:
$con = mysqli_connect("localhost","username","password","database");
$tname = "Big Bang";
$cname = "Mike";
$cemail = "test#gmail.com";
$cphone = "123-456-7898";
$teamToken = strtoupper(bin2hex(mcrypt_create_iv(6, MCRYPT_DEV_URANDOM)));
$query = "INSERT INTO teams (token, tname, captain, email, phone) VALUES ('" . $teamToken . "', '" . $tname . "', '" . $cname . "', '" . $cemail . "', '" . $cphone . "')";
if (mysqli_query($con, $query))
{
echo "Pass!";
}
else
{
echo $query;
}
mysqli_close($con);
What's odd is the php echos the query, because the mysqli_query result is false, yet the echoed query, when copied and pasted right into phpMyAdmin's terminal, works fine.
I am at my qit's end.
Your Code:
$con = mysqli_connect("localhost","username","password","database");
Edited code:
$con = mysqli_connect("localhost","root","","database");
if(!$con):
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
endif;
Its worked fine on my localhost
Maybe the datatypes of our columns make any problems.
I have once a similar "error" where my token field was to short. phpMyAdmin simply cut the long string to fit (or some thing this) and so it worked inside phpMyAdmin but not with my program.
Please post the CREATE statement of your table.
Try this
mysqli_query($con, $query) or die(mysqli_error($con));
I will suggest go step by step
step 1 : $con = mysqli_connect("localhost","username","password","database");
comment everything other than this statement.
then below write
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
verify your username password and database name (by default:username=="root" password=="" )
step 2 : add the query statements and print it. also check that all values are within their bounds as specified id DB.
step 3 :if $con and $query are valid then you will get your o/p as you req.
If still you have an error please paste your error statement.
using following to connect:
username="root" password=""
Your code works fine in my system.
I used varchar as datatype. Maybe the length of the varchar which you have taken as 12 is less to store the $teamToken variable. Try increasing the size.
I am very new to WordPress, and writing a plugin to (ideally) allow our client to update their existing WP site and the dynamic info on our iphone app all in one place. This will require the creation of two tables. I have written what I believe should be creating these tables, but activating the plugin throws this error on my test WordPress site:
The plugin generated 1 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
Looking into the database also reveals that the tables were not created. I have looked at a handful of other posts here and elsewhere, but can't seem to isolate where I am going wrong. Any suggestions?:
<?php
// Plugin info omitted
register_activation_hook(_FILE_, 'event_manager_install');
register_deactivation_hook(_FILE_, 'event_manager_uninstall');
// Installer
function event_manager_install() {
global $wpdb;
// Builds queries for custom event and speakers tables
$event_table = $wpdb->prefix . 'events';
$eventSql = "CREATE TABLE $event_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
venueName VARCHAR(250) DEFAULT '' NOT NULL,
date datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
address text NOT NULL,
registrationDeadlineDate datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
UNIQUE KEY id (id)
);";
$speaker_table = $wpdb->prefix . 'speakers';
$speakerSql = "CREATE TABLE $speaker_table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
eventID mediumint(9) NOT NULL,
speaker text NOT NULL,
UNIQUE KEY id (id)
);";
// Executes queries
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($eventSql);
dbDelta($speakerSql);
}
// Uninstaller
function event_manager_uninstall() {
global $wpdb;
// Creates queries to delete custom tables
$event_table = $wpdb->prefix . 'events';
$speaker_table = $wpdb->prefix . 'speakers';
$eventSql = "DROP TABLE " . $event_table . ";";
$speakerSql = "DROP TABLE " . $speaker_table . ";";
// Executes deletion queries
$wpdb->query($eventSql);
$wpdb->query($speakerSql);
}
?>
The problem is that you've misspelled the name of the __FILE__ constant. Just replace _FILE_ with __FILE__ (note: two underscores), and it should work just fine.
Total newbie here, please bear with me.
Building a very small personal app that uploads some images and info. I can't figure out why the following PHP/MySQL doesn't add the last insert in the query ($file_data) to my DB's longblob field.
All the other fields in the query insert fine, meaning I tested them one at a time, adding to the query, until I got to the last and then the insert fails. I am able to echo $file_data before the insert and see that the data is there, I've also found that hardcoding a string value for $file_data (i.e $file_data="this will insert") inserts fine... which is frustrating.
So my guesses are there's an error in the reading of the file ($fp fread etc) or that my longblob is setup wrong. File sizes are <16kb, so I'm sure it's not a php.ini issue either.
Any ideas? Thanks.
$boxtype=$_POST['type'];
$title=$_POST['title'];
if(isset($_POST['submit']) && $_FILES['imgfile']['size'] > 0)
{
$filename = $_FILES['imgfile']['name'];
$tmpName = $_FILES['imgfile']['tmp_name'];
$file_size = $_FILES['imgfile']['size'];
$mime_type = $_FILES['imgfile']['type'];
$fp = fopen($tmpName, 'r');
$file_data = fread($fp, filesize($tmpName));
fclose($fp);
$query = "INSERT INTO table
(boxtype,title,filename,mime_type,file_size,file_data)
VALUES
('$boxtype','$title','$filename','$mime_type','$file_size','$file_data')
";
$db = db_connect();
$result = $db->query($query) or die('Error, query failed');
if ($result)
{
echo "<br>Success<br>";
}
}
else die("No Content");
MySQL Table:
CREATE TABLE `port` (
`id` int(2) unsigned zerofill NOT NULL AUTO_INCREMENT,
`boxtype` tinytext COLLATE latin1_general_ci NOT NULL,
`title` varchar(40) CHARACTER SET latin1 NOT NULL,
`filename` varchar(255) COLLATE latin1_general_ci NOT NULL,
`mime_type` varchar(255) COLLATE latin1_general_ci NOT NULL,
`file_size` int(11) NOT NULL,
`file_data` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
Because its a binary, it probably contains values which means its probably throwing a wobble
Try using addslashes on the file_data variable, so it can save it.
The examples I came across while using Google showed that the data was escape either using addslashes or mysql_real_escape_string. Therefor my guess is that this is a crucial part since the $file_data string may contain various characters.
If on windows use fopen($tmpName, 'rb'); and use mysql_escape_string($file_data) .
You'll have to use the mysqli_ functions to create a prepared statement. Here is an example
$sql = 'INSERT INTO Table(boxtype,title,filename,mime_type,file_size,file_data)
VALUES (?,?,?,?,?,?)';
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, "ssssib", $boxtype,$title,$filename,$mime_type,$file_size,$file_data);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
This will also prevent against SQL Injection attacks which it appears your code may be vulnerable to. Alternatively, you can use the PDO libraries to create prepared statements.
With PDO, you can do the following.
$sql = 'INSERT INTO Table(boxtype,title,filename,mime_type,file_size,file_data)
VALUES (:boxtype,:title,:filename,:mime_type,:file_size,:file_data)';
$statement = $con->prepare($sql);
$statement->bindParam(':boxtype',$boxtype,PARAM_STR);
$statement->bindParam(':title',$title,PARAM_STR);
$statement->bindParam(':filename',$filename,PARAM_STR);
$statement->bindParam(':mime_type',$mime_type,PARAM_STR);
$statement->bindParam(':file_size',$file_size,PARAM_INT);
$statement->bindParam(':file_data',$file_data,PARAM_LOB);
$statement->execute();
I'm trying to insert remote POST data (articles sent by iSnare) into MySQL with PHP. Data comes successfully from remote POST sender and I can write it to plain-text file without a problem.
Unfortunately, when it comes to insert it into MySQL, MySQL cuts off string (article) at special char. I tried many things but still I'm unsuccessful!
I tried:
Escaping chars with mysql_real_escape_string()
Using htmlentities() and htmlspecialchars() (with every parameter..)
Sending SET NAMES utf8 query to MySQL before doing everything else
All tables and columns are UTF-8 encoded and utf8_general_ci (also tried utf8_unicode_ci and utf8_bin as collation)
Saving all PHP files as UTF-8
Still I couldn't find the solution. I will appreciate it very very very much if someone can help me solve this problem.
Here is my table definition and PHP codes:
PHP
function guvenlik_sql($x){
// Cleans inputs agains sql injection
return mysql_real_escape_string(htmlentities(stripslashes($x)), ENT_QUOTES);
}
// Check if data really comes from an Isnare.com server (Address hidden)
if ($_SERVER['REMOTE_ADDR'] == $isnareIP || $_SERVER['REMOTE_ADDR'] == "xxx.xxx.xxx.xxx") {
$title = guvenlik_sql($_POST["article_title"]);
$first_name = guvenlik_sql($_POST["article_author"]);
$description = guvenlik_sql($_POST["article_summary"]);
$category = guvenlik_sql($_POST["article_category"]);
$article = guvenlik_sql($_REQUEST["article_body_text"]);
$article_html = guvenlik_sql($_POST["article_body_html"]);
$resource_box = guvenlik_sql($_POST["article_bio_text"]);
$resource_box_html = guvenlik_sql($_POST["article_bio_html"]);
$keywords = guvenlik_sql($_POST["article_keywords"]);
$email = guvenlik_sql($_POST["article_email"]);
$fp = fopen('test.txt', 'a');
fwrite($fp, $title."\n");
fwrite($fp, $article."\n\n\n\n");
fclose($fp);
mysql_query("INSERT INTO articles " .
"(" .
"first_name, " .
"email, " .
"title, " .
"description, " .
"article, " .
"article_html, " .
"category, " .
"resource_box, " .
"resource_box_html, " .
"keywords, " .
"distributor, " .
"distributor_host" .
") VALUES (" .
"'$first_name', " .
"'$email', " .
"'$title', " .
"'$description', " .
"'$article', " .
"'$article_html', " .
"'$category', " .
"'$resource_box', " .
"'$resource_box_html', " .
"'$keywords', " .
"'$isnare', " .
"'$_SERVER['REMOTE_ADDR']', " .
")") or die(mysql_error());
} //end if security
Table definiton
CREATE TABLE `articles` (
`article_ID` int(11) NOT NULL auto_increment,
`first_name` varchar(100) NOT NULL,
`last_name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`author_url` varchar(255) NOT NULL,
`company_name` varchar(100) NOT NULL,
`address1` varchar(100) NOT NULL,
`address2` varchar(100) NOT NULL,
`state_2digit` varchar(100) NOT NULL,
`state` varchar(100) NOT NULL,
`zip_code` varchar(100) NOT NULL,
`country` varchar(100) NOT NULL,
`phone` varchar(100) NOT NULL,
`newsletter` varchar(100) NOT NULL,
`title` varchar(255) NOT NULL,
`description` text NOT NULL,
`article` longtext NOT NULL,
`article_html` longtext NOT NULL,
`category` varchar(100) NOT NULL,
`cat` varchar(100) NOT NULL,
`resource_box` text NOT NULL,
`resource_box_html` longtext NOT NULL,
`keywords` varchar(255) NOT NULL,
`publish_date` timestamp NOT NULL default CURRENT_TIMESTAMP,
`distributor` varchar(255) NOT NULL default '',
`distributor_host` varchar(255) NOT NULL,
PRIMARY KEY (`article_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC
I've just dealt with the same situation, entries were cut off where the special character (ä, ö, è, etc) supposed to be. All my files are UTF8 encoded, the connection is UTF8 encoded, table collations are UTF8, still the entries were cut off.
My solution was: even more UTF-encoding! :) Use utf8_encode() on the entries which can contain special characters.
mysql_query("INSERT INTO articles (first_name, email, title, description, article, article_html, category, resource_box, resource_box_html, keywords, distributor, distributor_host) values (
'" . utf8_encode($first_name) . "',
'" . $email . "',
'" . utf8_encode($title) . "',
'" . utf8_encode($description) . "',
// etc
Very late answer, but I came across this issue in one of our older projects. It turns out, that MySql has its own "implementation" of UTF8. It cannot save chars, which consists of more than 3 bytes (like emoticons etc.). Sometimes it throws error (like in this question "Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?) and sometimes it just cuts off the string.
The solution is switching from utf8 to utf8mb4 as described in linked question above, or make sure you cut off all long chars before saving.
I know this is an old question, but as we are using more and more emoticons, this can occur in some older apps. Hope it helps someone.
"Set names utf8" only sets the character set for table and column names, you have to use "set character set utf8" too, for the content character set.
Are you sure that the string is not cut off because of was longer than your column definition allows?
The problem could also be that the data is stored successfully in the database, but the application which you use to show the data from the database cuts off the displayed string. This mostly happens with strings containing null characters in windows-based applications since windows-controls use null-terminated strings internally.
1) put that sql string you're generating into a variable and write it to a file before you send it to MySQL (so you can look at exactly what is being sent)
2) mysqld has a setting "max_allowed_packet" which I think cuts off long queries.
3) you're passing ENT_QUOTES to mysql_real_escape_string(). I think you mean to pass it to htmlentities()
For those who might have the same problem and the answers before do not help, I got another suggestion: Check the CONTENT TYPE ! It should be like this:
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
I had the very same probleme as Donald had - this did the MAGIC :) (I did not imagin that the colegue who worked on the file in the first place hadn't set it right...)
Just solved a similar issue. My problem was I was trying to insert Latin-1 encoded data into a UTF-8 encoded table. Double check the encoding of your data -- you are likely getting non-UTF-8 data from your input.
Using mysqli_set_charset is what saved the day for me:
$conn = new mysqli($host, $username, $password, $database);
mysqli_set_charset($conn, 'utf8');