Now i have such method:
function exportFromTransbase($table_name) {
$odbc_query = "SELECT * FROM " . $table_name;
$data = odbc_exec($this->odbc_id, $odbc_query);
odbc_longreadlen($data, 10485760);
while($row = odbc_fetch_array($data))
{
foreach($row as $key => $value) {
$keys[] = "`" . $key . "`";
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
$mysql_query = "INSERT INTO `" . strtolower(substr($table_name, 4)) . "` (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";
mysql_query($mysql_query);
set_time_limit(3600);
unset($keys);
unset($values);
unset($row);
}
if ($mysql_query){
print "Ýêñïîðò äàííûõ èç òàáëèöû " . $table_name . " çàâåðøåí!";
//strtolower(substr($table_name, 4))
}
}
But it's very slow when importing to mysql. I decide to change this to export to file .sql, so that in future i can via terminal or phpmyadmin import that table. How to change to export to sql file my data?
Note! i'm converting from transbase to mysql
Instead of...
while($row = odbc_fetch_array($data))
{
foreach($row as $key => $value) {
$keys[] = "`" . $key . "`";
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
$mysql_query = "INSERT INTO `" . strtolower(substr($table_name, 4)) . "` (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";
mysql_query($mysql_query);
set_time_limit(3600); // this should not be here
unset($keys); // this is redundant
unset($values); // and this
unset($row); // and this too
}
Try:
$oufile=fopen("export.sql", 'w') || die("error writing file");
while($row = odbc_fetch_array($data))
{
foreach($row as $key => $value) {
$keys[] = "`" . $key . "`";
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
$mysql_query = "INSERT INTO `" . strtolower(substr($table_name, 4)) . "` (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";
fputs($outfile, $mysql_query . ";\n";
}
However it'll be much faster if you....
$oufile=fopen("export.sql", 'w') || die("error writing file");
fputs($outfile, "ALTER TABLE `" . . strtolower(substr($table_name, 4)) . "` DISABLE KEYS;\n";
while($row = odbc_fetch_array($data))
{
foreach($row as $key => $value) {
$keys[] = "`" . $key . "`";
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
$head="INSERT DELAYED INTO `" . strtolower(substr($table_name, 4)) . "` (" . implode(",", $keys) . ") VALUES ";
$row[]="(" . implode(",", $values) . ")";
if (count($row)>100) {
flush_ins($outfile, $head, $row);
$row=array();
}
}
if (count($row)) flush_ins($outfile, $head, $row);
fputs($outfile, "ALTER TABLE `" . . strtolower(substr($table_name, 4)) . "` ENABLE KEYS;\n";
fclose($outfile);
...
function flush($rows, $head, $fh)
{
fputs($fh, $head . implode("\n,", $rows) . ";\n");
}
see this post:
Easy way to export a SQL table without access to the server or phpMyADMIN
it uses the select into outfile syntax. The docs for this syntax are here: http://dev.mysql.com/doc/refman/5.1/en/select-into.html
you would do something like this:
mysql_query('SELECT * INTO OUTFILE "/path/to/my_file/my_file.sql" from '.$table_name)
Then this .sql file will be on your server.
If you don't have permissions to run the select into outfile synatx. You can use the mysqldump utility, like this:
<?php
exec('mysqldump db_name '.$table_name.' > my_file.sql');
?>
This will create an .sql file with the name indicated.
Related
I have a mySQL table with the fields:
preview_url
large_url
And I have an object that I submit with the following structure:
var $urls = {largeImg:[],preview:[]}
$urls.largeImg values have to be inserted into 'large_url' and
$urls.preview_url values have to be inserted into 'preview_url'
$urls.largeImg[0] has to go in the same mysql table row as $urls.preview[0],
$urls.largeImg[1] into the same row as $urls.preview[1] and so on.
my php:
$urls = $_POST['urls'];
function cache_urls($urls){
global $db;
foreach($urls as $url){
$sql = "INSERT INTO cache ";
$sql .= "(preview_url, large_url) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $url['preview']) . "', ";
$sql .= "'" . db_escape($db, $url['largeImg']) . "'";
$sql .= ");";
$result = mysqli_query($db, $sql);
}
And then I also tried this:
foreach($urls as $url){
foreach($url as $key => $value){
$sql = "INSERT INTO cache ";
$sql .= "(preview_url, large_url) ";
$sql .= "VALUES (";
if($key==="preview"){
$sql .= "'" . db_escape($db, $value) . "', ";
}
if($key==="largeImg"){
$sql .= "'" . db_escape($db, $value) . "'";
}
$sql .= ");";
$result = mysqli_query($db, $sql);
}
}
So I assume the SQL bit must be wrong but I'm really at the end of my knowledge! Any help much appreciated.
You should do it like this way,
$sql = "INSERT INTO cache (preview_url, large_url) values";
foreach($urls["largeImg"] as $index => $large_url){
$preview_url = $urls["preview"][$index];
$sql .= "('" . db_escape($db,$preview_url) . "','" . db_escape($db,$large_url) . "'),";
}
$sql = rtrim($sql,",");
I'm getting the error "SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens" when I try to run the below function:
public function find_products($string = '', $fields = array(), $sort_by = '', $sort_dir = 'ASC') {
$fields = empty($fields) ? '*' : ('' . implode(',', $fields) . '?');
$bindings = array('%' . $string . '%','%' . $string . '%','%' . $string . '%');
$and_where_checks = array('series','material');
$AND = '';
// Loop through the POST variables to see what is safe to play with
$allowed = array();
foreach ($and_where_checks as $awc)
if ( ! empty($_POST[$awc]))
$allowed = $awc;
if ( ! empty($allowed)) {
$tmp = array();
foreach ($allowed as $v)
$tmp = '' . $v . ' IN (' . str_pad('', count($v) * 2 - 1, '?,') . ')';
$AND = 'AND (' . implode(' AND ', $tmp) . ') ';
foreach ($allowed as $k)
foreach ($_POST[$k] as $v)
$bindings = $v;
}
$query =
"SELECT " . $fields . " FROM " . $this->product_table . " " .
"WHERE (" . $this->primary_key . " LIKE ? " .
$AND .
"ORDER BY " . $sort_by . " " . $sort_dir;
$sth = $this->$dbh->prepare($query);
$sth->execute($bindings);
return $sth->fetchAll(PDO::FETCH_ASSOC);
}
The $POST[$awc] variables are filled by checkboxes on this page http://ladd-dev.bitstormweb.com/products/interactive-product-finder/. When I choose one of each checkbox group (e.g. 1 Series and 1 Material) the results are fine, but when I choose multiple boxes in the same group, I get the PDOException.
Does anyone know why? I'm still learning this code so any help would be appreciated!
In your query, you only have one variable to be bound (the ?):
$query =
"SELECT " . $fields . " FROM " . $this->product_table . " " .
"WHERE (" . $this->primary_key . " LIKE ? " .
$AND .
"ORDER BY " . $sort_by . " " . $sort_dir;
Here, you must be either binding 0 or binding more than 1. Check how many values are in $bindings.
$sth = $this->$dbh->prepare($query);
$sth->execute($bindings);
You can check how many values are in $bindings by using print_r($bindings);
Update: Without knowing what your input is, your code seems to be using $bindings twice. It is set at the top with 3 values that are the same thing: $bindings = array('%' . $string . '%','%' . $string . '%','%' . $string . '%'); then at the bottom you have a foreach where you are not using an array at all:
foreach ($_POST[$k] as $v)
$bindings = $v;
i am working on dynamic array i need to insert these array in the database.when i insert dynamic array into the database instead of inserting all rows it only inserting one row in the database.
below is the array that contain result
$asma[]=GA::select($ga->population,'total',3);
below is code for inserting multiple array in database table ga
<?php
//code not tested check it
//Logic is changed instead of for looping many times
$data = array();
$j = 0;
foreach($asma as $key => $value)
{
$i = 0;
foreach ( $value as $ind => $hObject )
{
if($i==0)
{
$data[$j]['fe'] = mysql_escape_string($hObject->Voltage);
}else{
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Voltage);
}
$i++;
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Duration);
$i++;
$data[$j]['fe'.$i] = mysql_escape_string($hObject->Number);
$i++;
}
$j++;
}// endforeach
//multiple array
foreach($data as $array)
{
//unique array
//$array3 = array_merge($Voltage,$Duration,$Number);
$fields = implode(',',array_keys($array));
//if you want append any new field append it
$fields .= ','.'timestamp,username';
$vals = "'".implode("','",array_values($array))."'";
//if you want append any new values append it
$vals .= ",'".time()."','".$login_session."'";
$q = "INSERT INTO ga (".$fields.") VALUES(".$vals.")";
$result = mysql_query($q);
if ( ! $result ) {
die( 'Insert failed ' . mysql_errno() . ' ' . mysql_error() );
}
}
whenever user enter 3 then after computation result will store in array asma after store result will store in table ga that should be three rows but only one row insert in the table and display instead of three same in case the user enter any value in the text box.
I'm not sure what you mean, i think is an insert statement like this:
INSERT INTO `ga` (`field1`, `field2`, `field3`, `etc`)
VALUES (value11, value21, value31, more_values1),
(value12, value22, value32, more_values2),
(value13, value23, value33, more_values3)
So you should use your foreach cycle to create the values statement.
$sql = "INSERT INTO `ga` (`voltage`, `duration`, `number`, `timestamp`, `username`) VALUES ";
$values = "";
foreach ($asma as $row) {
$values .= ($values != "" ? "," : "") . "(" .
"'" . $row['voltage'] . "', " .
"'" . $row['voltage'] . "', " .
"'" . $row['number'] . "', " .
"'" . time() . "', " .
"'" . $login_session . "'" .
"),";
}
$sql .= substr($values, 0, -1) . ";";
There is problem with Query :
$outputs = rosy, rosmary; //array1
$filenames =2.2, 3.2; // array 2
Query:
$insert_col = "UPDATE `lil` SET `D`='" .$output. "' WHERE `A`= '" .$filename. "'";// does not work
Instead of the arrays when i give single value, it works very fine, like :
$insert_col = "UPDATE `lil` SET `D`='rosy' WHERE `A`= '2.2'"; // it works
for taking two arrays into the query i have written foreach loop, as follows
foreach (array_combine($outputs, $filenames) as $output => $filename) {
$insert_col = "UPDATE `4` SET `D`='" . $output . "' WHERE `A`= '" . $filename . "'";
echo $insert_col;
}
Please Help !!
try using for loop. get the size of array and run for loop for that no of times
Try
$query = 'UPDATE lil SET D = CASE A';
foreach($arr as $k => $v)
$query .= 'WHEN ' . $k . ' THEN ' . $v;
$query .= ' END';
$insert_col = 'UPDATE 4 SET D = CASE A';
foreach($arr as $output => $filename)
{
$insert_col .= 'WHEN ' . $output . ' THEN ' . $filename;
$insert_col .= ' END';
$insert_result= mysql_query($insert_col)or die("Query failed: " . mysql_error());
dint work #eli
i apologize if the question is wrong. i am a still a newbie and a learner however i would appreciate if someone correct me if i am somewhere wrong.
here in the Class method i am using for Inserting the data into the database
public function insert($table,$col,$value)
{
if(is_array($col) && is_array($value))
{
$query = "INSERT INTO ".$table."(" . implode(",",$col) . ") VALUES(" . implode(",",$value) . ")";
}
else
{
$query = "INSERT INTO " . $table . "(" . $col . ") VALUES(". $value . ")";
}
}
now here i am determining if the $col and $value is an array if yes then process it.
however i have a problem here since the VALUES in the Insert statement needs to be represnted in the single or double quote format it will not process the query and hence print the error
for example the below code would print the error
$query = "INSERT INTO users(username,email) VALUES(test,test#test.com)";
and the correct format will be
$query = "INSERT INTO users(username,email) VALUES('test','test#test.com')";
now in the col value i would like to add the single quotes to every value in the array for example the $value array which is like this.
$value = array('test','test#test.com');
should give back the value
'test','test#test.com'
instead of
test,test#test.com
how do i achieve it?
$query = "INSERT INTO $table ('" . implode("','",$col) . "')
VALUES ('" . implode("','",$value) . "')";
Make sure that neither $col nor $value is empty.
Right code:
public function insert($table,$col,$value)
{
if(is_array($col) && is_array($value))
{
$query = "INSERT INTO ".$table."(" . implode(",",$col) . ") VALUES('" . implode("','",$value) . "')";
}
else
{
$query = "INSERT INTO " . $table . "(" . $col . ") VALUES('". $value . "')";
}
}
CHANGE:
VALUES(" . implode(",",$value) . ")
TO
VALUES('" . implode("','",$value) . "')
(Your output:)
VALUES(demo,demo2)
(New Output:)
VALUES('demo','demo2')
you could do this?
$value = array("'test'","'test#test.com'");
You can use array_map() method:
function addQuotes($str)
{
return "'".$str."'";
}
$value = array_map("addQuotes", $value);
or follow a Oswald's answer recommendations.