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
Related
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! :~)
I have multiple rows with data, some with data in mysql table kjoring and some that don't.
I am able to echo both $km1 and $km2 correctly, but I am unable to subtract them to find the result and echo $km0
$sqlq = "SELECT kjoring FROM oko WHERE kjoring!='' ORDER BY logdate DESC LIMIT 2";
if ( array_key_exists( 'field' , $out ) ) {
$sqlq = $sqlq . " where field = '" . $out['field'] . "'" ;
}
$conn = new mysqli($servername, $username, $password, $dbname);
$result = mysqli_query( $conn , $sqlq );
if ( $result->num_rows > 0 ) {
while($row = mysqli_fetch_array($result)) {
$km1 = $row[0];
$km2 = $row[1];
$km0 = $km1 - $km2 ;
}
}
echo $km0 ;
First things first: Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
Next:
// $sqlq = 'SELECT ... FROM ... ORDER BY ... LIMIT'
if ( array_key_exists( 'field' , $out ) ) {
$sqlq = $sqlq . " where field = '" . $out['field'] . "'" ;
}
When you add your WHERE conditions after the LIMIT there WILL be a syntax error returned by your DB. You need to add the WHERE condition after the FROM and in front of the ORDER BY.
$sqlq = 'SELECT ... FROM ... ';
if ( array_key_exists( 'field' , $out ) ) {
$sqlq = $sqlq . " where field = '" . $out['field'] . "'" ;
}
$sqlq .= 'ORDER BY ... LIMIT ...';
Now to the 2 results:
while($row = mysqli_fetch_array($result)) {
$km1 = $row[0];
$km2 = $row[1];
When printing your row using var_dump() you will notice that there is only 1 column. You selected just one.
Using mysqli_fetch_all($result,MYSQLI_ASSOC); you will get an array containing both rows. Using this you can then do your computations.
PHP: mysqli_fetch_all()
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.
In this SQL query I select by id was set in the session but at some cases there is no found any id match the field in the table, so I put if/else statement with mysql_num_rows function to avoid error message...
So my question is: Is thre any SQL code to check if is there is value or not without using mysql_num_rows function?
SELECT *
, d_articles.ar_id
, d_articles.ar_article_title
, d_articles.ar_article_desc
, d_articles.ar_created
, d_articles.ar_link_img
, d_articles.ar_img
FROM
d_articles
WHERE
d_articles.ar_hide = 1 AND
d_articles.ar_category_id ='" . $this->session->userdata('branch_id') . "'
ORDER BY
ar_created desc limit 1
<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
FOR SQL QUERY:
$tsql = "SELECT ProductID, Name, Color, Size, ListPrice
FROM Production.Product
WHERE Name LIKE '%' + ? + '%' AND ListPrice > 0.0";
$params = array( $_REQUEST['query'] );
$getProducts = sqlsrv_query( $conn, $tsql, $params);
if ( $getProducts === false)
{ die( FormatErrors( sqlsrv_errors() ) ); }
READ MORE
Im having trouble trying to find out why my script wont delete a row in my table.
Each user has a randomkey assigned to them. I need to say delete row in table where random key equals that to the user...
<?php
$userRand = $_GET['Rand'];
$delUser = mysql_query("DELETE from users WHERE randomkey = '" . mysql_real_escape_string($userRand));
if(! $qResult )
{
die('Could not delete data: ' . mysql_error());
}
elseif($qResult )
{
echo "deleted";
}
?>
the following outputs...
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''111111111' at line 1
You're missing the closing ' in your PHP code.
$delUser = mysql_query("DELETE from users WHERE randomkey = '" . mysql_real_escape_string($userRand) . "'");
You are not closing the SQL-String.
$delUser = mysql_query(
sprintf("DELETE from users WHERE randomkey = '%d'", mysql_real_escape_string($userRand)
);