PHP Mysql copy a record into a different database - php

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)");

Related

How to get column names from the result of a select query using mysqli

I need to create a script that goes through the results from MySQL and automatically returns the column names selected on the query using mysqli.
NOTE: I'll be using some pseudo code to explain my point easier. It is obviously wrong
For example a CLIENTS table with columns:
ID, NAME, EMAIL, TELEPHONE, ADDRESS
If I have a query:
$result = $mysqli->query("SELECT * FROM CLIENTS WHERE ID = 1");
I need the script to return ID NAME, EMAIL, TELEPHONE, ADDRESS.
Pseudo code:
foreach ($result as $column => $value){
echo $column
}
Result:
ID, NAME, EMAIL, TELEPHONE, ADDRESS,
Same thing if the query is only
$result = $mysqli->query("SELECT NAME as N, EMAIL as E FROM CLIENTS WHERE ID = 1");
The script should return only:
N, E,
Ideas?
This is not a complete working snippet, but instead a nod in the right direction.
$sql = "SELECT * FROM clients WHERE id = 1";
$res = $mysqli->query($sql);
$row = $res->fetch_assoc();
$colNames = array_keys($row);
Now $row contains an associative array with all column names and variables for the first selected row. If you only want the column names, you have them in $colNames and you're done.
To process all the data use
while ($row = $res->fetch_assoc()) {
...
}
I think you can also query to database with this query in PHP:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

Passing String Array in sql query using PHP

I have two tables is sql 1) friends_details and 2) user_info.
Now using the below query am getting the list of friends of that particular using $number = is coming from app
$sql = "select friends from user_info WHERE user_number ='$number' ";;
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
now $emparray have names of friends in String fromat. Now i want to pass this array into another query so that i can find the details of these friends. And Can't find the way to do. I have tried this code.
$friendsArray2 = "'" .implode("','", $emparray ) . "'";
$query120 = "SELECT * FROM friends_deataisl WHERE name IN ( $friendsArray2 )";
echo $query120;
and the result of echo $query120 is SELECT * FROM friends_deatails WHERE name IN ( 'Array','Array' )
So this means values are not going in the query. Any help would be appreciated.
And i have already checked $emparray is not empty it contains the name that means first query is right but the problem is in second query.
$emparray is a 2-dimensional array, not an array of strings, because $row in the first loop is an associative array.
You need to change the first loop to do:
$emparray[] = $row['friends'];
But you could just combine the two queries into a JOIN:
SELECT DISTINCT fd.*
FROM friend_details AS fd
JOIN user_info AS ui ON fd.name = ui.friends
WHERE ui.user_number = '$number'
Also, the column name friends makes me suspect that this is a comma-separated list of names. Using = or IN won't work with that -- it will try to match the entire list with friend_details.name. It's best to normalize your database so you don't have lists in a column. If you can't fix that, you need to use FIND_IN_SET to join the tables:
SELECT DISTINCT fd.*
FROM friend_details AS fd
JOIN user_info AS ui ON FIND_IN_SET(fd.name, ui.friends)
WHERE ui.user_number = '$number'
And in your original code, you'll need to explode $row['friends']:
$emparray = array_merge($emparray, explode(',', $row['friends']));

Column order when selecting column_names in Oracle

I want display a table content along with column names.
I have used SQL query for columns
"SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = $mytable"
and I have used SQL query for content
"SELECT * FROM $mytable"
Both are working fine. Only thing is that, order of columns is different. Some times its just reverse. sometimes it is reverse with some shift of 2-3 columns depending on number of column in $mytable.
You need to include an order by when you query ALL_TAB_COLUMNS on COLUMN_ID:
"SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = $mytable ORDER BY COLUMN_ID".
This orders the columns by the order created.
Probably a better approach is to simply read the column names from the returned resultset. This means you need only one query:
$conn = oci_connect($username, $password, $connectionString);
$stmt = oci_parse($conn, 'select * from mytable');
oci_execute($stmt);
$headers = false;
while ($row = oci_fetch_assoc($stmt)) {
if (!$headers) {
// this will only output the headers on the first iteration.
print_r(array_keys($row));
$headers = true;
}
print_r($row);
}
Or you could use oci_field_name() against the resultset but I've always felt the above method is simpler.
Edit: In case there are no results, you won't be able to get the keys (since the array is empty). You can add the following code after the while loop to handle that:
if (!$headers) {
for ($i = 1; $i <= oci_num_fields($stmt); $i++) {
echo oci_field_name($stmt, $i), PHP_EOL;
}
}

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

transfer some informations from one database to another with 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);
}
?>

Categories