I am using a small script to automate schema transfers between servers, but now I will need to modify it to also include data. I am not that good with PHP so I am asking for your help.
This is what I have so far (parts I got from another source, not mine):
/*********** GRAB OLD SCHEMA ***********/
$db1 = mysql_connect($DB_SRC_HOST,$DB_SRC_USER,$DB_SRC_PASS) or die(mysql_error());
mysql_select_db($DB_SRC_NAME, $db1) or die(mysql_error());
$result = mysql_query("SHOW TABLES;",$db1) or die(mysql_error());
$buf="set foreign_key_checks = 0;\n";
$constraints='';
while($row = mysql_fetch_array($result))
{
$result2 = mysql_query("SHOW CREATE TABLE ".$row[0].";",$db1) or die(mysql_error());
$res = mysql_fetch_array($result2);
if(preg_match("/[ ]*CONSTRAINT[ ]+.*\n/",$res[1],$matches))
{
$res[1] = preg_replace("/,\n[ ]*CONSTRAINT[ ]+.*\n/","\n",$res[1]);
$constraints.="ALTER TABLE ".$row[0]." ADD ".trim($matches[0]).";\n";
}
$buf.=$res[1].";\n";
}
$buf.=$constraints;
$buf.="set foreign_key_checks = 1";
/**************** CREATE NEW DB WITH OLD SCHEMA ****************/
$db2 = mysql_connect($DB_DST_HOST,$DB_DST_USER,$DB_DST_PASS) or die(mysql_error());
$sql = 'CREATE DATABASE '.$DB_DST_NAME;
if(!mysql_query($sql, $db2)) die(mysql_error());
mysql_select_db($DB_DST_NAME, $db2) or die(mysql_error());
$queries = explode(';',$buf);
foreach($queries as $query)
if(!mysql_query($query, $db2)) die(mysql_error());
How can I modify the existing code to include data as well?
Thanks!
If you need to transfer both the data /and/ the schema, why not do a mysqldump, and just read the whole thing back in? What does this not to, that the script is supposed to be doing?
After going though a lot of links and tutorials, I managed to come up with something that simply works! Here is the code:
$connectDST = mysql_connect($DB_DST_HOST, $DB_DST_USER, $DB_DST_PASS);
mysql_select_db($DB_DST_NAME, $connectDST);
set_time_limit(0);
$connectSRC = mysql_connect($DB_SRC_HOST, $DB_SRC_USER, $DB_SRC_PASS);
mysql_select_db($DB_SRC_NAME, $connectSRC);
$tables = mysql_query("SHOW TABLES FROM $DB_SRC_NAME");
while ($line = mysql_fetch_row($tables)) {
$tab = $line[0];
mysql_query("DROP TABLE IF EXISTS $DB_DST_NAME.$tab") or die('Couldn\'t drop table:'.mysql_error());
mysql_query("CREATE TABLE $DB_DST_NAME.$tab LIKE $DB_SRC_NAME.$tab") or die(mysql_error()) or die('Couldn\'t create table:'.mysql_error());
mysql_query("INSERT INTO $DB_DST_NAME.$tab SELECT * FROM $DB_SRC_NAME.$tab") or die('Couldn\'t insert data:'.mysql_error());
echo "Table: <b>" . $line[0] . " </b>Done<br>";
}
I tried to avoid exec, since some hosts do not allow it...
Related
I have table named category which contain names of other tables in the same database. I want to fetch table names from category table and then fetch data from each table from db. So far I have this code below:
$db = new mysqli('localhost', 'root', '', 'db_cat');
if($db){
// $q = "SELECT TABLE";
// $echo = $db->query($q);
// echo $echo;
// $result = $db->query("SHOW TABLES");
$qCat="SELECT * FROM product_category";
$cat_query= $db->query($qCat) or die(mysql_error());
while ($fetch= $cat_query->fetch_object())
{
$cat_id=$fetch->id;
$category=$fetch->category;
$p_cat=str_replace(" ","_",strtolower($category).'_categories');
//if(strlen($category)>22){$fine_product_name= substr($service, 0,19).'...';}else{ $fine_product_name=$category;}
$result = $db->query("SHOW TABLES");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
}
The second query must be different.
$result = $db->query("SELECT * FROM $category");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
print_r($tables);
First of all your design to connect to a database is not that good, Please check the below code for a proper way of connecting to it.
<?php
$con=mysqli_connect("localhost","root","","db_cat");
//servername,username,password,dbname
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: ".mysqli_connect_error();
}
?>
Here is a sample code of getting data from a table ( where this table name is in another table).
$get_table_name ="SELECT TableName FROM table_name";
$get_name=mysqli_query($con,$get_table_name);
$count=0;
while($row_name=mysqli_fetch_array($get_name)){
$count++;
$tbName=$row_name['TableName'];
$_SESSION['table_name'][count]=$tbName;
}
This will show you how to fetch data from one table. You can use a For loop to get all the tables
$table=$_SESSION['table_name'][1];
$get_table ="SELECT * FROM $table";
.... // Normal way of fetching data
You can try to adjust your code according to this and improve it.
For further reference please refer http://php.net/manual/en/book.mysqli.php
I want to execute a query that i saved in my database like this:
ID | NAME | QUERY
1 | show_names | "SELECT names.first, names.last FROM names;"
2 | show_5_cities | "SELECT cities.city FROM city WHERE id = 4;"
Is this possible ?
I am kinda noob in php so plz explain if it is possible.
If I understand you correctly, you have your queries saved in the database in a table and you want to execute those.
Break the problem down: you have two tasks to do:
Query the database for the query you want to run.
Execute that query.
It's a bit meta, but meh :)
WARNING: the mysql_ functions in PHP are deprecated and can be dangerous in the wrong hands.
<?php
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
die('Could not connect to mysql');
}
if (!mysql_select_db('mysql_dbname', $link)) {
die('Could not select database');
}
$name = "show_5_cities"; // or get the name from somewhere, e.g. $_GET.
$name = mysql_real_escape_string($name); // sanitize, this is important!
$sql = "SELECT `query` FROM `queries` WHERE `name` = '$name'"; // I should be using parameters here...
$result = mysql_query($sql, $link);
if (!$result) {
die("DB Error, could not query the database\n" . mysql_error(););
}
$query2 = mysql_fetch_array($result);
// Improving the code here is an exercise for the reader.
$result = mysql_query($query2[0]);
?>
if you did create a stored procedure/function you can simply use:
mysql_query("Call procedure_name(#params)")
Thats will work. reference here: http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
Querying the table to get the query, then executing that query and looping through the results and outputting the fields
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$RequiredQuery = intval($_REQUEST['RequiredQuery']);
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $sql);
if ($row = mysqli_fetch_assoc($result))
{
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $row['QUERY']);
while ($row2 = mysqli_fetch_assoc($result))
{
foreach($row2 AS $aField=>$aValue)
{
echo "$aField \t $aValue \r\n";
}
}
}
?>
just open the Table and get the individual query in a variable like
$data = mysql_query('SELECT * FROM <the Table that contains your Queries>');
while(($row = mysql_fetch_row($data)) != NULL)
{
$query = $row['Query'];
mysql_query($query); // The Query from the Table will be Executed Individually in a loop
}
if you want to execute a single query from the table, you have to select the query using WHERE Clause.
Can anyone tell me a reason a query just wont return the same data in php as the ones that it returns on phpmyadmin sql?
$query = "UPDATE `boards` SET `contestPlaces`=0, `contestPlacesFilled`=0";
$result = mysql_query($query) or die("ERROR:QUERY_FAILED timeset 8" . mysql_error());
$query = "UPDATE `playerspoints` SET `points`=0";
$result = mysql_query($query) or die("ERROR:QUERY_FAILED timeset 9" . mysql_error());
$query = "SELECT `avatarId`, `points` FROM `contestants`";
$result = mysql_query($query) or die("ERROR:QUERY_FAILED timeset 10" . mysql_error());
$qualified = array();
while($row = mysql_fetch_row($result));
{
print_r($row);
$qualified[] = $row;
} `
Result: Array ( [0] => ) SUCCESS.
I get no error, it just returns an empty result, while in phpmyadmin sql tab, it runs fine.
I'm properly connected with the db, cause I run queries before this one. I checked to see and this one is the only one that fails without an apparent reason. So What should I look in order to see what's going wrong?
The user that I get connected to the database has the following privileges:
SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, CREATE VIEW, EVENT, TRIGGER, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EXECUTE
remove the semicolon:
while($row = mysql_fetch_row($result));
^
//this is latest code in php5.7.14 and accesses the database.....but still it was not working.
//therefore, i found that the database coallition was not 'utf_general_ci' rather i kept default leading to 'latin_swedish'.
//single mistake can ruin your project.
<?php
$mysqli_hostname = "localhost";
$mysqli_user = "root";
$mysqli_password = "krunal";
$mysqli_database = "krunal";
$bd = mysqli_connect($mysqli_hostname, $mysqli_user, $mysqli_password,$mysqli_database);
if(mysqli_connect_errno()){die("database connection failed");}
?>
<?php
$sql= "SELECT * FROM `done`;";
$result=mysqli_query($bd,$sql);
if(!$result){
die("database query failed". mysqli_connect_error()." (".mysqli_connect_errno().")");}?>
<?php while($row=mysqli_fetch_row($result)){
var_dump($row); }?>
<?php mysqli_close($bd);?>
I've been struggling with this problem for a couple of days and can't make any progress...
I'm trying to get just ONE result from my database but on contrary I'm getting the whole table : (
php:
{
$connect = #mysqli_connect ($host, $username, $pass, $dbname)
OR die ('Could not connect to MySQL');
$table = $_REQUEST['table'];
$key = $_REQUEST['id'];
$key_value = $_REQUEST['id_value'];
$q = "SELECT * FROM ".$table." where ".$key."='".$key_value."'";
$r = #mysqli_query ($connect, $q);
while ($row = mysqli_fetch_array($r))
$output[]=$row;
print(json_encode($output));
}
I think there's no need to show you my android code for that since the data is received well (also updating tables works fine) ... all i want is to get that ONE result from my DB.
When simply navigating to this file on the browser there's no problem obviously...
Thanks in advance, cheers
You are doing something like where 1 = 1 and that is always true. You are not naming your column. You are replacing that with a number.
try this (unverified):
"SELECT * FROM ".$table." where id='".$id."'";
If you want to get just the first row of the results, then you have two options:
include LIMIT in your query (preferred solution)
SELECT * FROM ".$table." where ".$id."='".$id."' LIMIT 1"
don't loop to get all the data, simply read the first row and return it.
$table = $_REQUEST['table'];
$key = $_REQUEST['id'];
$key_value = $_REQUEST['id_value'];
$q = "SELECT * FROM ".$table." where ".$id."='".$id."'";
You're assigning $key and $key_value but then using $id.
you are setting your condition to where ".$id."='".$id."'";, so, if you pass id=1, that will mean: WHERE 1=1, and that is always true. that's why it's returning all the records.
I'm trying to set up memcached to store the results of the query that pulls all the data to be shown on my front page. when i use memcached for one result it works fine, but when I set the query to 'LIMIT 10' and pull the cache it still only shows one result when I var_dump.
Is there something that I am missing? Or am I really only able to store one row at a time?
My basic syntax is as follows (result is assuming key has been set):
$sql = "select * from active limit 10";
//create an index key for memcache
$key = md5('query'.$sql);
$result = $memcache->get($key);
var_dump($result);
edit: added entire code i am trying to work with
$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211) or die ("Could not connect");
$sql = "select * from active limit 10";
$key = md5('query'.$sql);
$result = $memcache->get($key);
if($result == null) {
$qry = mysql_query($sql) or die(mysql_error()." : $sql");
if(mysql_num_rows($qry)> 0) {
$result = mysql_fetch_object($qry);
echo "THIS IS NOT CACHE<br>";
var_dump($result);
//store it
$memcache->set($key,$result,0,10);
}
}
else {
echo "this is cached<br>";
var_dump($result);
}
You are using:
$result = mysql_fetch_object($qry);
which only retrieve a single record from the database.
What you need to do is loop through and build an array of objects:
while ($result[] = mysql_fetch_object($qry));
which you can then serialize and cache.
Your code should then look something like this:
...
if($result == null) {
$qry = mysql_query($sql) or die(mysql_error()." : $sql");
while ($result[] = mysql_fetch_object($qry));
// cache it
$memcache->set($key,serialize($result),0,10);
}
...
You need to loop through your results, I'd recommend this:
$cachedResults = $memcache->get($key);
if (!empty($cachedResults)) {
var_dump(unserialize($cachedResults));
exit;
}
$qry = mysql_query($sql) or die(mysql_error()." : $sql");
while ($row = mysql_fetch_object($qry)) {
$results[] = $row;
}
$memcache->set($key, serialize($results));
Remember, if you already have the key in cache, then it will never hit the query to reload the correct result set, so flush it first, then try this code snippet.