I want to import a csv file content into a database table, I'm using this code that it works perfectly when pasting it in phpmyadmin console:
LOAD DATA LOCAL INFILE '/Applications/MAMP/htdocs/testApp/trips.csv' INTO TABLE trips FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 ROWS (type,startDate,endDate,steps,coordinates,distance)
However, when using it in a php file, I have an error:
<?php
$host = "localhost"; //Your database host server
$db = "dbTest"; //Your database name
$user = "root"; //Your database user
$pass = "root"; //Your password
$connection = mysqli_connect($host, $user, $pass);
//Check to see if we can connect to the server
if (!$connection) {
die("Database server connection failed.");
die(mysqli_error($db));
} else {
//Attempt to select the database
$dbconnect = mysqli_select_db($connection, $db);
//Check to see if we could select the database
if (!$dbconnect) {
die("Unable to connect to the specified database!");
} else {
$sql = "LOAD DATA LOCAL INFILE '/Applications/MAMP/htdocs/testApp/trips.csv'
INTO TABLE trips
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\\n'
IGNORE 1 ROWS (type,startDate,endDate,steps,coordinates,distance)"
;
$result = mysql_query($sql, $connection);
if (mysql_affected_rows() == 1) {
$message = "The trip was successfully inserted!";
} else {
$message = "The trip insert failed";
$message .= mysql_error();
}
echo $message;
}
}
?>
=> The trip insert failed
I'm pretty sure that the problems come from a \ or any other character that I can't target.
Thank you for helping .
You've mixed up MySQL and MySQLi plugins — you're trying to connect with MySQLi then perform a query with MySQL. You can't do that. Pick one API and use it consistently.
So:
mysql_query($sql) ---> $connection->query($sql)
mysql_affected_rows() ---> $result->affected_rows()
mysql_error() ---> $connection->error
Ultimately, this has nothing to do with LOAD DATA INFILE and you should have tried it with a basic SELECT! And I recommend reading the documentation for the functions that you use.
EDIT : You are mixing two plugins MYSQL and MYSQLi in same script, below i dumped remaining part of your code using mysqli plugin, because your upper part uses mysqli...
N.B:You can't do that. Pick just any single API.
$result = mysqli_query($connection, $sql);
if (mysqli_affected_rows($connection) >= 1) {
$message = "The trip was successfully inserted!";
} else {
$message = "The trip insert failed";
$message .= mysqli_error($connection);
}
Try to move you trip.csv file into datadir - You can find it with this command : SELECT # #datadir
Related
I am trying to use the mysql LOAD DATA LOCAL INFILE to get some csv data into my mysql database through a php script using mysqli. This is what my sql string looks like:
LOAD DATA LOCAL INFILE '/var/www/html/dashmaker/uploads/HHdata.csv' INTO TABLE dashmaker.HHdata FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES;
This is what my php script looks like:
$sql = "LOAD DATA LOCAL INFILE '/var/www/html/dashmaker/uploads/HHdata.csv'
INTO TABLE dashmaker.HHdata
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;";
$con=mysqli_connect("localhost","[user]","[password]","[database]");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
};
$result = mysqli_query($sql, $con);
if (mysql_affected_rows() == 1) {
$message = "The data was successfully added!";
} else {
$message = "The user update failed: ";
$message .= mysql_error();
};
echo $message;
mysqli_close($con);
I found that I needed to set the mysql my.cnf to include local-infile under [mysql] and [mysqld] - so I have done that.
When I run the sql query through the shell it works. When I try to do it through the php script the error message ($message) I now get says:
The user update failed: Access denied for user ''#'localhost' (using password: NO)
One weird thing is that it doesn't show any user name before the #'localhost'. Can't understand why. Besides this, I use the same connection setting to run regular SELECT queries from the database using php scripts. The user also has FILE privileges.
I have searched extensively but haven't found anything that can explain what's going on. Any advice would be much appreciated.
You're mixing MySQL APIs with mysql_ and mysqli_ functions in a few instances.
mysql_affected_rows()
mysql_error()
They do not mix together; use mysqli_ exclusively.
Plus, you're not using brackets in [user] etc, are you? That is MSSQL syntax, remove them.
Plus, in mysqli_, DB connection comes first, invert these $result = mysqli_query($sql, $con); to read as $result = mysqli_query($con, $sql);
$sql = "LOAD DATA LOCAL INFILE '/var/www/html/dashmaker/uploads/HHdata.csv'
INTO TABLE dashmaker.HHdata
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;";
$con=mysqli_connect("localhost","user","password","database");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
};
$result = mysqli_query($con, $sql);
if (mysqli_affected_rows($con) == 1) {
$message = "The data was successfully added!";
} else {
$message = "The user update failed: ";
$message .= mysqli_error($con);
};
echo $message;
mysqli_close($con);
I have written that seems to not be working, but MySQL does not return any error. It is supposed to get data from database1.table to update database2.table.column
<?php
$dbh1 = mysql_connect('localhost', 'tendesig_zink', 'password') or die("Unable to connect to MySQL");
$dbh2 = mysql_connect('localhost', 'tendesig_zink', 'password', true) or die("Unable to connect to MySQL");
mysql_select_db('tendesig_zink_dev', $dbh1);
mysql_select_db('tendesig_zink_production', $dbh2);
$query = " UPDATE
tendesig_zink_dev.euid0_hikashop_product,
tendeig_zink_production.euid0_hikashop_product
SET
tendesig_zink_dev.euid0_hikashop_product.product_quantity = tendesig_zink_production.euid0_hikashop_product.product_quantity
WHERE
tendesig_zink_dev.euid0_hikashop_product.product_id = tendesig_zink_production.euid0_hikashop_product.product_id";
if (mysql_query($query, $dbh1 ))
{
echo "Record inserted";
}
else
{
echo "Error inserting record: " . mysql_error();
}
?>
The manual page for mysql_error() mentions this about the optional parameter you're omitting:
link_identifier
The MySQL connection. If the link identifier is not
specified, the last link opened by mysql_connect() is assumed. If no
such link is found, it will try to create one as if mysql_connect()
was called with no arguments. If no connection is found or
established, an E_WARNING level error is generated.
So it's reading errors from $dbh2, which is the last connection you've opened. However, you never run any query on $dbh2:
mysql_query($query, $dbh1 )
Thus you get no errors because you are reading errors from the wrong connection.
The solution is to be explicit:
mysql_error($dbh1)
As about what you're trying to accomplish, while you can open as many connections as you want, those connections won't merge as you seem to expect: they're independent sessions to all effects.
All your tables are on the same server and you connect with the same users, there's absolutely no need to even use two connections anyway.
You can't just issue a cross-database update statement from PHP like that!
You will need to execute a query to read data from the source db (execute that on the source database connection: $dbh2 in your example) and then separately write and execute a query to insert/update the target database (execute the insert/update query on the target database connection: $dbh1 in your example).
Essentially, you'll end up with a loop that reads data from the source, and executes the update query on each iteration, for each value you're reading from the source.
I appreciate everyone's help/banter, here is what finally worked for me.
<?php
$dba = mysqli_connect('localhost', 'tendesig_zink', 'pswd', 'tendesig_zink_production') or die("Unable to connect to MySQL");
$query = " UPDATE
tendesig_zink_dev.euid0_hikashop_product, tendesig_zink_production.euid0_hikashop_product
SET
tendesig_zink_dev.euid0_hikashop_product.product_quantity = tendesig_zink_production.euid0_hikashop_product.product_quantity
WHERE
tendesig_zink_dev.euid0_hikashop_product.product_id = tendesig_zink_production.euid0_hikashop_product.product_id";
if (mysqli_query($dba, $query))
{
echo "Records inserted";
}
else
{
echo "Error inserting records: " . mysqli_error($dba);
}
?>
For some reason, the following code inside the query works in my MySQL command console, yet when I try to run it as a Query in PHP, something keeps going wrong and I'm not sure what. Here is the code I've done so far.
//2. Perform database query
$query = "SELECT skills.element_id, content_model_reference.element_id, element_name FROM skills, content_model_reference WHERE (skills.element_id = content_model_reference.element_id)";
$result = mysql_query($query);
//Tests if there was a query error
if(!$result){
die("Database query failed.");
}
Is there something preventing the code that worked in MySQL (The line with SELECT) from working, or is my syntax somehow wrong?
EDIT: So it's saying I didn't select a database. Yet I thought I had. Here is the code above it:
//1. Create a database connection
$dbhost = "host"; //Host: Can be either an IP address, or a domain (like google.com).
$dbuser = "user";//User: The user that is connecting to the database.
$dbpass = "pass";//Password: This is the password that the user is using.
$dbname = "db";//Name: This is the name of the database.
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);//The value, 'handle,' is the connection.
//Test if connection occurred. Die ends the program/php, and in this case, also prints a message
if(mysqli_connect_errno()){
die("Database connection failed: ".
mysqli_connect_error().
" (". mysqli_connect_errno() . ")"
);
}
Like I said, the error message I am getting is pertaining only to the query, the server is fine with my database connection.
You're using mysqli_* for the connection, but you're using mysql_* for the QUERY... don't think you can do that, has to be one or the other (MYSQLI_ preffered). Also the query should be:
$result = mysqli_query($connection,$query);
Can anyone see what the problem with my code is / where im going wrong?
I know i have the correct host,database,user and password.
This is the code in the php file, it should get all the details available on the players from my sql database, however if i go on the page it just gives me a white page. Im using go daddy as a host and my database is also on there.
Any ideas? thanks
<?php
$host = "abc12345"; //Your database host server
$db = "abc12345"; //Your database name
$user = "abc12345"; //Your database user
$pass = "abc12345"; //Your password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if (!$connection) {
die("Database server connection failed.");
} else {
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if (!$dbconnect) {
die("Unable to connect to the specified database!");
} else {
$query = "SELECT * FROM Player";
$resultset = mysql_query($query);
$records = array();
//Loop through all our records and add them to our array
while ($r = mysql_fetch_assoc($resultset)) {
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
The script is all right, I checked it with a different query.
Assuming that the table Player is not empty, the error can be either with your raw sql query (as pointed by #Sharikov in comments), otherwise the error is with the way you have configured your godaddy server.
For debugging that, I would suggest inserting dummy print_r or echo statements before you execute the query, and going through your apache logs at /var/log/apache2/access.log.
Also make sure that you don't have any core php package missing on your server (like php5-mysql if you use mysql).
I wonder whether someone can help me please.
I'm trying to put together a PHP script that takes data from an xml file and places the data in a mySQL data. I've been working on this for a few days and I'm still can't seem to get this right.
This is the code that I've managed to put together:
<?
$objDOM = new DOMDocument();
$objDOM->load("xmlfile.xml");
$Details = $objDOM->getElementsByTagName("Details");
foreach( $Details as $value )
{
$listentry = $value->getElementsByTagName("listentry");
$listentrys = $listentry->item(0)->nodeValue;
$sitetype = $value->getElementsByTagName("sitetype");
$sitetypes = $sitetype->item(0)->nodeValue;
$sitedescription = $value->getElementsByTagName("sitedescription");
$sitedescriptions = $sitedescription->item(0)->nodeValue;
$siteosgb36lat = $value->getElementsByTagName("siteosgb36lat");
$siteosgb36lats = $siteosgb36lat->item(0)->nodeValue;
$siteosgb36lon = $value->getElementsByTagName("siteosgb36lon");
$siteosgb36lons = $siteosgb36lon->item(0)->nodeValue;
//echo "$listentrys :: $sitetypes :: $sitedescriptions :: $siteosgb36lats :: $siteosgb36lons <br>";
}
require("phpfile.php");
//Opens a connection to a MySQL server
$connection = mysql_connect ("hostname", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
mysql_query("INSERT IGNORE INTO scheduledsites (listentry, sitetype, sitedescription, siteosgb36lat, siteosgb36lon) VALUES('$listentrys','$sitetypes','$sitedescriptions','$siteosgb36lats','$siteosgb36lons') ")
or die(mysql_error());
echo "Data Inserted!";
?>
I can pull the data from the xml file, but it's the part of the script that sends the data to my database table that I'm having trouble with.
The script runs but only the last record is saved to the database.
I can parse the fields from the xml file without any problems and the check I'm trying to put in place is, if there is a 'listentry' number in the new data that is matched to one already in the table then I don't want that record to be added to the table, i.e. ignore it.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Many thanks
You are only calling mysql_query once. So it will only insert one row.
The sql needs to be inside the loop.