transfer some informations from one database to another with php? - php

I have a mysql database called A.
I would like to to get informations where country=usa (There are about 40 000 with usa) and i want to insert to B database.
How i can do that with php?
Thanks in advance

Yes, you can do this slowly with PHP:
<?php
$data = mysql_query("SELECT x,y,z FROM db1.table WHERE where country='usa'");
$values = Array();
while ($row = mysql_fetch_assoc($data)) {
// do some work...
$row['x'] = mysql_real_escape_string($row['x']);
$row['y'] = mysql_real_escape_string($row['y']);
$row['z'] = mysql_real_escape_string($row['z']);
$values[] = "('$row[x]','$row[y]','$row[z]')";
}
mysql_query("insert into db2.table (x,y,z) VALUES ".implode(',',$values)."");
?>
But i prefer quicker and simplier MySQL INSERT ... SELECT statement, directly in MySQL console:
INSERT INTO db2.table (x,y,z) SELECT x,y,z FROM db1.table WHERE country='usa';

You should be able to do a dump of the database schema and data, as a big SQL file, and just run that SQL on the different database... no need for PHP scripting at all if you have phpMyAdmin. Just use the operations tab on the main database screen. Export database on the source, import it in to the destination.

<?php
$query = "SELECT * FROM database1.table_name WHERE country = 'USA'";
$result2 = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
//assigning of value to variable
$val1 = $row['field_name1'];
$val2 = $row['filed_name2'];
//and so on
$query2 = "INSERT INTO database2.table_name (field1,field2,.....) VALUES ('$val1', 'val2',....)"
$result2 = mysql_query($query2);
}
?>

Related

select BLOB type image and insert it to another table

I have two table one is storing basic info with image type is blob and
the other table is for attendance table , Now my problem is when i select all
the table with basic info with image and insert it to another table the image
column is only blank the rest has a value , Hope you can help fix it thanks.
here is my php code:
<?php
include_once('connection.php');
if(isset($_POST['submit0'])){
$rfid = $_POST['rfid'];
$sql = mysqli_query($conn,"select * from stud where rfid_num ='$rfid'");
$count = mysqli_num_rows($sql);
if ($count == 0) {
header("location:notexist.php");
} else{
while( $row = mysqli_fetch_array($sql)) {
$rfid=$row['rfid_num'];
$id=$row['id'];
$name0 = $row['name'];
$course0 = $row['course'];
$image = $row['image'];
$InsertSql = "INSERT INTO student_att(rfid_num,id,name,course,image) VALUES ('$rfid','$id','$name0','$course0','$image')";
$res = mysqli_query($conn, $InsertSql);
}
}
}
?>
Instead of executing two separate queries I will suggest you to have a single query which will select from one table and insert into another table.
Example query:
INSERT INTO table2 (st_id,uid,changed,status,assign_status)
SELECT st_id,from_uid,now(),'Pending','Assigned'
FROM table1
NOTE: It's not good to save images in database. We usually keep them in folders and save the path of it in database.
The simplest way to solve your error is by doing like this
$image=mysqli_real_escape_string($mysqli,$row['image'];
$mysqli is connection variable.
and then in your query use $image to insert image hope it will helps.

How to display field from MySQL?

I'm trying to display a field from my MySQL database. It's in the table tblproducts in the row with the id is set to 1. And under the column qty.
This is the code I'm using:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database_name");
$available = "SELECT qty FROM tblproducts WHERE id = 1";
$result = mysql_query($available);
echo $result;
?>
However, I keep getting this message: Resource id #2
I've done a bit of research and seen where other people are having similar problems but most of them are trying to display their data in an HTML table whereas I just need the data from 'qty' to display. And of course I'm definitely not a MySQL guru.
Can anyone help me out with this please?
Try changing this:
$result = mysql_query($available);
To this:
$result = mysql_result(mysql_query($available), 0);
Let's start from the start. (I'll assume you have the connection set)
Form the query
$query = "SELECT `qty`
FROM `tblproducts`
WHERE `id` = 1";
Execute the query
$run = mysql_query($query);
Now, put the result in an assoc array
$r = mysql_fetch_array($run);
See the contents of the array
echo $r['qty'];
It's also advised that you move up from mysql to either mysqli, or PDO. PDO is preferred as you're not bound to the MySQL database model.
Try this:
Here you need to generate associative array and then get the resulting row.
$query = "SELECT `qty` FROM `tblproducts` WHERE `id` = 1";
$run = mysql_query($query);
$r = mysql_fetch_array($run);
echo $r['qty'];
-
Thanks

Loop MySql INSERT query. While or Foreach?

I'm struggling whit this...
Basically, I have a script that will run every day (cron job).
This script has to retrieve data from a table and it will post the data in another table (same database).
Here is my example script:
<?php
$c = mysql_connect("localhost", "user", "password");
$db = mysql_select_db("mydb", $c);
$query_sel = "SELECT id, rating, rating_count FROM mytableone";
$result_sel = mysql_query($query_sel) or die(mysql_error());
$ids = array();
while($id = mysql_fetch_array($result_sel))
$ids[] = $row;
foreach($ids as $id){
$lid = $row['id'];
$etvalue = $row['user_rating'];
$etcount = $row['rating_count'];
mysql_query("INSERT INTO mytabletwo VALUES ('$lid','$etvalue','$etcount',CURRENT_DATE())");
}
?>
My main idea is to insert data (as mysql query in foreach statement) "for each id from mytableone".
Where is my fault?
Thanks
You can do this with one SQL query
INSERT INTO mytabletwo SELECT id,rating,rating_count,CURRENT_DATE() FROM mytableone
As to the fault you are using $row instead of $id[...]
The easiest way to do this is:
INSERT INTO mytabletwo(idColumnName, ratingColumnName, rating_countColumnName, dateColumnName) SELECT id, rating, rating_count, CURRENT_DATE() FROM mytableone;
(That is one statement.)

MySQL - Batch rename all rows in PHP

So in this piece of code, I just deleted a row from the table, and so, the values for img_pos were:
1,2,3,4,5
And now, they are (assuming we deleted the third entry):
1,2,4,5
Of course, I want this to be:
1,2,3,4
So I have to batch rename the rows.
I got this, but doesn't seem to work....
$sql = "SELECT * FROM $tableImg WHERE img_acc = $accid ORDER BY img_pos";
$res = mysql_query($sql);
$num = mysql_num_rows($res);
$i = 0;
$n = 1;
while($i<$num){
$sql = "SELECT * FROM $tableImg WHERE img_acc = $accid ORDER BY img_pos DESC LIMIT $i,1";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$img_pos = $row['img_pos'];
$sql = "UPDATE $tableImg SET img_pos = '$n' WHERE img_acc = '$accid' AND img_pos = '$img_pos'";
$res = mysql_query($sql);
$i++;
$n++;
}
mysql_close();
$tableImg is just a variable containing the table name, that works just fine.
I guessthe problem is somewhere around "$img_pos = $row['img_pos'];", because all the querys are used somewhere differently, be it slightly different, and they should work...
Thanks in advance!
I ended up simply doing this:
$i = 1;
while($row = mysql_fetch_array($res)){
$old_pos = $row['img_pos'];
$sql = "UPDATE $tableImg SET img_pos = $i WHERE img_acc = $accid AND img_pos = $old_pos";
$res = mysql_query($sql);
$i++;
};
This is quite possible, just totally unnecessary. The nice thing about digital data is that you don't have to look at it so it doesn't matter if it's a bit gappy, does it?
If you REALLY want to do this (say, you are building an application and you are just cleaning up the stuff you deleted whilst working on it) the following example will do in in SQL, as this simple example shows:
CREATE TABLE disorder (id int,stuff CHAR(6));
CREATE TABLE disorder2 (id SERIAL,stuff CHAR(6));
INSERT INTO disorder (id,stuff)
VALUES
('1','ONE'),
('2','TWO'),
('3','THREE'),
('4','FOUR'),
('5','FIVE');
DELETE FROM disorder WHERE id='3';
INSERT INTO disorder2 (stuff) SELECT stuff FROM disorder;
TRUNCATE TABLE disorder;
INSERT INTO disorder SELECT * from disorder2;
DROP TABLE disorder2;
This can be seen in action on sqlfiddle but it's pretty obvious. If you do a SELECT * from disorder, you will see why you probably shouldn't do this sort of thing.
Your tables really do need to have primary keys. This speeds searches/indexing and makes them useful. Look up database normal forms for a thorough discussion of the reasoning.

PHP Mysql copy a record into a different database

I have two separate remote databases, the table in both databases is identicle and I want to copy a record from the old database to the new using PHP
While this the best way to copy new records from one database to another gives the solution as
mysqli_query($db1,"SELECT field1,field2,field3 FROM table1");
mysqli_query($db2,"INSERT INTO table1 (field1,field2,field3)");
Because of the number of fields involved I want to try and avoid naming all the fields
I was thinking of something like this...
$m = mysqli_query($db1,"SELECT * FROM table1");
****THIS IS WHERE I'M STUCK****
HOW DO I GET TO THIS FROM THE ABOVE STATEMENT?
$values = "'".implode("','",array_values($m))."'";
$columns = implode(",",array_keys($m));
So I can do this
mysqli_query($db2,"insert into table1 ($columns) values ($values)")
I'm aware I will need to change the PRIMARY KEY id to null.
To fetch the actual column names you could do like this:
$sql="SELECT column_name FROM information_schema.columns WHERE table_schema = 'database_name' AND table_name = table1";
Fetch the above into an array.
$result = $mysqli->query($query);
$cols = $result->fetch_array(MYSQLI_NUM);
and create comma-separated list into $columns-variable
$columns = implode(",", $cols);
For the values, just do a regular select-statement:
$sql="SELECT * FROM table1";
$result = $mysqli->query($query);
$vals = $result->fetch_array(MYSQLI_NUM);
in the end it was quite simple to modify my own code and create the array using mysqli_fetch_assoc
$m = mysqli_fetch_assoc(mysqli_query($db1,"SELECT * FROM table1"));
and then to make the id null
$m["id"] = 'replacethis';
$values = str_replace("'replacethis'","null","'".implode("','",array_values($m))."'");
$columns = implode(",",array_keys($m));
then finally...
mysqli_query($db2,"insert into table1 ($columns) values ($values)");

Categories