How to specify a export-path, with sql in php? - php

Background: I work with phpMyAdmin (MySQL Workbench) in a mysql DB. I write some PHP code to import data in the DB and execute this with the task scheduler of windows. <= this works fine!
My Topic: Now I want to export some data into a file in a Windows folder. At first I write the SQL code in phpMyAdmin to see some debug-infos.
Independent of php my sql-query works fine.
If I put the code in the php-programm my export didn't work.
I think the problem occurs because of my path specification.
The other programmparts, specially the Update-Part, do what they should.
Here is my code:
<?php
include "../config.php";
$conn = new mysqli('192.168.10.120', 'alb5', 'alb5','testdatenbank');
if ( $conn->connect_error ) {
die( "Connection failed: " . $conn->connect_error );
} //$conn->connect_error
$sql = "set #sql = concat(\"SELECT `LS_ID_Nr`, `Stk_pro_Krt_DL` * `Krt_DL` + `RB_Stk_pro_Krt_DL` * `RB_Krt_DL`, `Umstellzeit`, `Produktionszeit`, `Teilmeldung`, `Fertigmeldung`
INTO OUTFILE 'C:/Temp/Export/Test - \", DATE_FORMAT(NOW(), '%Y%m%d%H%i%s'),\" - Test.txt'
fields terminated by ';'
lines terminated by '\r\n'
From praemie where Proof_P = 0\");";
$sql = "prepare s1 from #sql;";
$sql = "execute s1;";
$sql = "DROP PREPARE s1;";
$sql = "UPDATE praemie SET Proof_P = 1 WHERE Proof_P = 0;";
$result = $conn->query( $sql );
echo("Error description: " . mysqli_error($conn));
?>
Does anybody have an idea how I specify a export-path, with sql in php?
Thanks in advance.

This is creepy way of doing this.
I suggest to fetch the data into the php and store it via file_put_contents.
Quick example:
<?php
include "../config.php";
$conn = new mysqli('192.168.10.120', 'alb5', 'alb5','testdatenbank');
if ( $conn->connect_error ) {
die( "Connection failed: " . $conn->connect_error );
} //$conn->connect_error
$query = 'SELECT `LS_ID_Nr` AS `LS_ID_Nr`, `Stk_pro_Krt_DL` * `Krt_DL` + `RB_Stk_pro_Krt_DL` * `RB_Krt_DL` AS ``, `Umstellzeit`, `Produktionszeit`, `Teilmeldung`, `Fertigmeldung`FROM praemie WHERE Proof_P = 0';
$result = $conn->query($sql);
file_put_contents('C:/Temp/Export/Test/test.txt', json_encode($result->fetch_all()));

yeeeah it works now!
Only for other people out there who want do the same.
Two things I have to change. I execute my programm in an other path so I have to write
$include_path = 'C:/xampp/php/pear/PEAR/config.php'; this fixed the first error.
The second point: Your quick example $result = $conn->query($sql); have to be $result = $conn->query($query);
Down below is the whole code:
<?php
$include_path = 'C:/xampp/php/pear/PEAR/config.php';
$conn = new mysqli('192.168.10.120', 'alb5', 'alb5','testdatenbank');
if ( $conn->connect_error ) {
die( "Connection failed: " . $conn->connect_error );
} //$conn->connect_error
$query = 'SELECT `LS_ID_Nr`, `Stk_pro_Krt_DL` * `Krt_DL` + `RB_Stk_pro_Krt_DL` * `RB_Krt_DL` AS `Ges. Stück`, `Umstellzeit`, `Produktionszeit`, `Teilmeldung`, `Fertigmeldung` FROM praemie WHERE Proof_P = 0';
$result = $conn->query($query);
if (mysqli_num_rows($result)!==0)
{
file_put_contents('C:/Temp/Export/' . date('Y-m-d H-i-s') . '.txt', json_encode($result->fetch_all()));
}
$sql = "UPDATE praemie SET Proof_P = 1 WHERE Proof_P = 0";
$result = $conn->query( $sql );
echo("Error description: " . mysqli_error($conn));
?>
*Edit: I integrate a proof if the result (num_rows of query) is not equal to zero and give the file a unique name with the variable date('Y-m-d H-i-s') (attention with windows filename permissions H - i - s not H : i : s)
Thanks alot Damian for all your knowledge and the help of the forum!
I'm happy now.
(~: First attempts with php and it works now fine! :~)

Related

Mysql update table column from one database to another

I am working on a script that updates from:
tendesig_zink_production | euid0_hikashop_product | product_quantity
to:
tendesig_zink_dev | euid0_hikashop_product | product_quantity
I have to do this because our inventory numbers are stored on the production instance. so before pushing a new version from our dev instance i have to update the dev's inventories from production prior to the push. I am a lot rusty with my mySQL, this is what i have so far I need to know what the proper query would be though.
<?php
$host1="localhost"; // destination
$base1="tendesig_zink_dev";
$user1="tendesig_zink";
$password1="1,&#GZAWiB5z";
$host2="localhost"; //source
$base2="tendesig_zink_production";
$user2="tendesig_zink";
$password2="1,&#GZAWiB5z";
$conection1 = #mysql_connect($host1, $user1, $password1)
or die("Error reaching destination<br>".mysql_error()." nr eroare: ".mysql_errno());
print "Succesfuly connected 1! <br>";
$Db1 = #mysql_select_db($base1, $conection1)
or die("Error reaching destination database:<br>" . mysql_error(). "<br>" . mysql_errno());
print "Database1 reached!<br>";
$conection2 = #mysql_connect($host2, $user2, $password2)
or die("Error reaching source<br>".mysql_error()." nr eroare: ".mysql_errno());
print "Succesfuly connected 2!<br>";
$Db2 = #mysql_select_db($base2, $conection2)
or die("Error reaching source database:<br>" . mysql_error(). "<br>" . mysql_errno());
print "Database2 reached!!<br>";
$query = 'create table destination_table select * from second_database.source_table';
//echo "<br>".$query."<br>";
$result2 = mysql_query($query2, $conection1) or die('Query failed: ' . mysql_error().'||'.mysql_errno());
mysql_close($conection1);
mysql_close($conection2);
?>
Your query is wrong. You want to do something like this:
CREATE TABLE destination_database.destination_table LIKE source_database.source_table
Then run this:
INSERT INTO destination_database.destination_table
SELECT * FROM source_database.source_table
In (untested) PHP code:
$create_query = 'CREATE TABLE destination_database.destination_table LIKE source_database.source_table';
$result = mysql_query($create_query, $conection1) or die('Query failed: ' . mysql_error().'||'.mysql_errno());
$insert_query = 'INSERT INTO destination_database.destination_table SELECT * FROM source_database.source_table';
$result = mysql_query($insert_query , $conection1) or die('Query failed: ' . mysql_error().'||'.mysql_errno());

Why this simple Query doesn't work?

i can't make it work this simple query,it gives me my "die" error
mysql_select_db("minigest_dev" , $con);
$query = " SELECT * "
. "FROM anag_c_indirizzi"
. "WHERE id_cliente = '1';";
$result = mysql_query($query, $con) or
die("query non valida: ". mysql_error());
where is the mistake?
When your query is concatenated, it becomes SELECT * FROM anag_c_indirizziWHERE id_cliente = '1'. You need to add a space so that it becomes [...] anag_c_indirizzi WHERE [...].
You can try this.
Your mistake that you are show error in or condition.
Note : $query = " SELECT * "
. "FROM anag_c_indirizzi"
. "WHERE id_cliente = '1';";
multiple semicolon not allow in sql plz remove one semicolon(;)
mysql_select_db("minigest_dev" , $con);
$query = " SELECT *
FROM anag_c_indirizzi
WHERE id_cliente = '1'";
$result = mysql_query($query);
if (!$result) {
die('query non valida:' . mysql_error());
}
When you append you need to take care of string. Just give one space WHERE clause starts.
mysql_select_db("minigest_dev" , $con);
$query = " SELECT * "
. " FROM anag_c_indirizzi "
. " WHERE id_cliente = 1;";
$result = mysql_query($query, $con) or
die("query non valida: ". mysql_error());

MySQL batch insert fails, no error

I'm trying to create a php function to split up the data into batches as it fails when I try to insert them fairly quickly.
I'm trying to insert thousands of records of user-data into a different format in the same database, later to be exported to a seperate database. However the query fails.
Based on comments and answers below I've updated the code to the following. Still fails, though.
The code inserting values:
function insertUsers( $users ){
error_reporting(E_ALL);
ini_set('display_errors',1);
global $pdo;
//insert into database
$i = 0;
$base = 'INSERT INTO tth_user_accounts (user_login, user_pass, user_email, user_registered,
user_firstname, user_lastname ) VALUES ';
$sql = '';
var_dump($users);
while( $i < count( $users ) ){
$sql = $sql . ' ("' .
$users[$i]['user_login'] . '", "' .
$users[$i]['user_pass'] . '", "' .
$users[$i]['user_email'] . '", "' .
$users[$i]['user_registered'] . '", "' .
$users[$i]['meta_value']['first_name'] . '", "' .
$users[$i]['meta_value']['last_name'] . '")';
if (!( $i % 25 === 0 )){
$sql = $sql . ', ';
}
if ($i % 25 === 0) {
//execute $base + $query here
$sql = $base . $sql;
$query = $pdo->prepare( $sql );
echo 'check query: <br />';
print_r( $query );
if( $query->execute() ){
echo '50 users succesfully added to the database';
} else {
echo 'Query failed: ';
print_r( $pdo->errorInfo() );
echo '<br />';
}
$sql = ''; //Re-init query string
}
$i++;
}
if ( strlen( $sql ) > 0 ) { // Execute remainder, if any
//execute $base + $query here
$sql = $base . $sql;
$query = $pdo->prepare( $sql );
echo 'check query: <br />';
print_r($query);
if( $query->execute() ){
echo 'User succesfully added to the database';
} else {
echo 'Query failed: ';
print_r( $pdo->errorInfo() );
echo '<br />';
}
}
}
check query:
PDOStatement Object ( [queryString] => INSERT INTO tth_user_accounts (user_login, user_pass, user_email, user_registered, user_firstname, user_lastname ) VALUES ("John Smith", "4\/\/350M3 P4sS\/\/0r|)", "john.smith#greatmail.com", "2013-04-11 11:18:58", "John", "Smith") )
Query failed: Array ( [0] => 00000 [1] => [2] => )
Tried it with a %25 and %50, both don't work. Keep getting the 00000 error which is supposed to lead to victory (success, though for me it still fails, nothing in the DB)
I'd do it manually if I had the time but this won't be a one-time event so I need a solution to this issue. Is there a good way to split up the query into batches (and how?) that would allow this to be repeated and queries to be executed one after the other? I've been looking at a whole bunch of questions on SO (and elsewhere) already and can't find one that suits my needs.
UPDATE - has been answered, need a small modification as shown below:
if (!( $i % 25 === 0 )){
if(!( $i == ( count( $users ) - 1 ))){
$sql = $sql . ', ';
}
}
You're mixing PDO with mysql_ functions. Pick one and follow the respective library's error handling.
It would also be beneficial print out your $sql to yourself to see if it's formatted correctly. Additionally, if you're handling POSTed data, you will want to use prepared statements,
You might need to increase the max_allowed_packet value which defaults to 1Mb. If you want to split up the query in batches you can do so using the modulus operator.
$base = 'INSERT INTO ...';
$sql = '';
while( $i < count( $users ) ){
$sql = $sql . ' ("' ... //etc.
if ($i % 50 === 0) {
//execute $base + $qry here
$sql = ''; //Re-init query string
}
}
if (strlen($qry)>0) { // Execute remainder, if any
//execute $base + $query here
}
Or as an array (described here):
$base = 'INSERT INTO ...';
$sql = array();
while( $i < count( $users ) ){
$sql[] = ' ("' ... //etc.
if ($i % 50 === 0) {
//execute $base + implode(',', $sql) here
$sql = array(); //Re-init query string
}
}
if (sizeof($qry)>0) { // Execute remainder, if any
//execute $base + implode(',', $sql) here
}
Also please make sure you're using prepared statements correctly so you're not vulnerable to SQL injections.
Finally: you might need to enable error reporting so failures won't be silent; if they're still silent after enabling error reporting (e.g. error_reporting(-1);) you might need to set MySQL to strict mode (not sure if that will help). If they still fail silently file a bugreport.
Edit
Oh, I missed the fact that you're mixing mysql_ and PDO; that will probably be the reason why you're not seeing any errors... D'uh. Go read the manual on PDO error handling.
#Downvoters: If you're downvoting at least have the decency to leave a comment on why.
Is there a reason why you want to do it as one single statement? Why not just iterate through the users and insert each one with something like:
while($i < count( $users )) {
$sql = 'INSERT INTO tth_user_accounts (user_login, user_pass, user_email, user_registered, user_firstname, user_lastname ) VALUES ';
$sql = $sql + "(";
$sql = $sql + "'" . $users[$i]['user_login'] . '",';
$sql = $sql + "'" . $users[$i]['user_pass'] . '",';
$sql = $sql + "'" . $users[$i]['user_email'] . '",';
$sql = $sql + "'" . $users[$i]['user_registered'] . '",';
$sql = $sql + "'" . $users[$i]['meta_value']['first_name'] . '",';
$sql = $sql + "'" . $users[$i]['meta_value']['last_name'] . '"';
$sql = $sql + ")";
$query = $pdo->prepare( $sql );
if( $query->execute() ){
echo 'User succesfully added to the database';
} else {
die ("Query failed: " . $pdo->errorInfo());
}
}
Even better is to prepare the statement once and then bind the parameters. As pointed out by RobIII, you can introduce SQL injection vulnerabilities by building up your SQL statements as strings so instead, you could do something like:
$sql = 'INSERT INTO tth_user_accounts (user_login, user_pass, user_email, user_registered, user_firstname, user_lastname) ';
$sql += ' VALUES (:user_login, :user_pass, :user_email, :user_registered, :user_firstname, :user_lastname)';
$query = $pdo->prepare( $sql );
while ($i < count($users)) {
$query->bindParam(":user_login", $users[$i]['user_login']);
$query->bindParam(":user_pass", $users[$i]['user_pass']);
$query->bindParam(":user_email", $users[$i]['user_email']);
$query->bindParam(":user_registered", $users[$i]['user_registered']);
$query->bindParam(":user_firstname", $users[$i]['user_firstname']);
$query->bindParam(":user_lastname", $users[$i]['user_lastname']);
if( $query->execute() ){
echo 'User succesfully added to the database';
} else {
die ("Query failed: " . $pdo->errorInfo());
}
}
Another issue you may be encountering is a simple fact that the user's name / information may contain invalid characters and killing your command. Take for instance a person's last name is "O'Maley". When building your string of values and wrapping the name with hard quotes, you would get
'O'Maley'
I ran into something similar to this about 8 years ago and had to validate certain values within the data. Once you find it, you'll know how to correct each respective value, then go back to batch mode.
Also, consider someone supplying a bogus value of a bogus / bad value of "--" which indicates rest of line is a comment... or even a ";" to indicate end of statement. That is most likely what you are running into.
As RobIII responded, and I was too quick in my response, don't test one at a time, but query the data an look at it for such anomolies / bad escape posts in the data. Fix what you need to BEFORE trying the insert.

MYSQL/PHP outputting entire table when I only want to output one row

This is definitely a beginner's question. There are two issues. The id in my MYSQL table (set to autoincrement) keeps going up, even though I delete rows from my table (I'm using phpmyadmin). As for the other issue, I can't seem to find a way to work with the row most recently entered by the user. The code echos all existing rows from MYSQL.
I've bolded the most pertinent section of code.
<?php
//establish connection to mysql
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
/*retrieve user input from input form
and initialize variables */
$Word1 = $_POST["Word1"];
$Word2 = $_POST["Word2"];
$Word3 = $_POST["Word3"];
$Word4 = $_POST["Word4"];
$Word5 = $_POST["Word5"];
//select db
mysql_select_db("madlibs", $con);
//insert user input for word 1
$sql = "INSERT INTO test (Word1, Word2, Word3, Word4, Word5)
VALUES
('$Word1', '$Word2', '$Word3', '$Word4', '$Word5')";
if(!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query ("SELECT * FROM test");
/* take note here */
while($row = mysql_fetch_array($result))
{
echo $row['Word1'] . " " . $row['Word2'] . " " . $row['Word3'] . " " .
$row['Word4'] . " " . $row['Word5'] . " " . $row['id'];
echo "<br />";
} /* take note here */
mysql_close($con);
?>
$result = mysql_query ("SELECT * FROM test order by id desc limit 1");
As for your id question...that's how ids work. They don't fill in gaps.
On a side note: Never ever put user submitted data directly into the query string. Always escape them with mysql_real_escape_string().
SELECT * FROM test ORDER BY Id DESC LIMIT 1

php - disconnecting and connecting to multiple databases

I want to be able to switch from the current db to multiple dbs though a loop:
$query = mysql_query("SELECT * FROM `linkedin` ORDER BY id", $CON ) or die( mysql_error() );
if( mysql_num_rows( $query ) != 0 ) {
$last_update = time() / 60;
while( $rows = mysql_fetch_array( $query ) ) {
$contacts_db = "NNJN_" . $rows['email'];
// switch to the contacts db
mysql_select_db( $contacts_db, $CON );
$query = mysql_query("SELECT * FROM `linkedin` WHERE token = '" . TOKEN . "'", $CON ) or die( mysql_error() );
if( mysql_num_rows( $query ) != 0 ) {
mysql_query("UPDATE `linkedin` SET last_update = '{$last_update}' WHERE token = '" . TOKEN . "'", $CON ) or die( mysql_error() );
}else{
mysql_query("INSERT INTO `linkedin` (email, token, username, online, away, last_update) VALUES ('" . EMAIL . "', '" . TOKEN . "', '" . USERNAME . "', 'true', 'false', '$last_update')", $CON ) or die( mysql_error() );
}
}
mysql_free_result( $query );
}
// switch back to your own
mysql_select_db( USER_DB, $CON );
It does insert and update details from the other databases but it also inserts and edits data from the current users database which I dont want. Any ideas?
Never use the php mysql_select_db() fundtion - as you've discovered the code (and the coder) gets very confused very quickly.
Explicitly state the DB in the queries:
SELECT * FROM main_database.a_table....
UPDATE alternate_db.a_table SET...
REPLACE INTO third_db.a_table...
C.
You're probably have wrong database design.
one improve that i see is that you can use one query to duplicate or update
the syntax is like :
INSERT INTO mytable (field_list.....) VALUES (values_list...)
ON DUPLICATE KEY
UPDATE field1 = val1 ...
you are reassigning $query during your while loop. this will give strange results. use $query2 for the query inside the loop

Categories