Related
I'd like to get all of a mysql table's col names into an array in php?
Is there a query for this?
The best way is to use the INFORMATION_SCHEMA metadata virtual database. Specifically the INFORMATION_SCHEMA.COLUMNS table...
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename';
It's VERY powerful, and can give you TONS of information without need to parse text (Such as column type, whether the column is nullable, max column size, character set, etc)...
Oh, and it's standard SQL (Whereas SHOW ... is a MySQL specific extension)...
For more information about the difference between SHOW... and using the INFORMATION_SCHEMA tables, check out the MySQL Documentation on INFORMATION_SCHEMA in general...
You can use the following query for MYSQL:
SHOW `columns` FROM `your-table`;
Below is the example code which shows How to implement above syntax in php to list the names of columns:
$sql = "SHOW COLUMNS FROM your-table";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
echo $row['Field']."<br>";
}
For Details about output of SHOW COLUMNS FROM TABLE visit: MySQL Refrence.
Seems there are 2 ways:
DESCRIBE `tablename`
or
SHOW COLUMNS FROM `tablename`
More on DESCRIBE here: http://dev.mysql.com/doc/refman/5.0/en/describe.html
I have done this in the past.
SELECT column_name
FROM information_schema.columns
WHERE table_name='insert table name here';
Edit: Today I learned the better way of doing this. Please see ircmaxell's answer.
Parse the output of SHOW COLUMNS FROM table;
Here's more about it here: http://dev.mysql.com/doc/refman/5.0/en/show-columns.html
Use mysql_fetch_field() to view all column data. See manual.
$query = 'select * from myfield';
$result = mysql_query($query);
$i = 0;
while ($i < mysql_num_fields($result))
{
$fld = mysql_fetch_field($result, $i);
$myarray[]=$fld->name;
$i = $i + 1;
}
"Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future."
The simplest solution out of all Answers:
DESC `table name`
or
DESCRIBE `table name`
or
SHOW COLUMNS FROM `table name`
An old PHP function "mysql_list_fields()" is deprecated. So, today the best way to get names of fields is a query "SHOW COLUMNS FROM table_name [LIKE 'name']". So, here is a little example:
$fields = array();
$res=mysql_query("SHOW COLUMNS FROM mytable");
while ($x = mysql_fetch_assoc($res)){
$fields[] = $x['Field'];
}
foreach ($fields as $f) { echo "<br>Field name: ".$f; }
when you want to check your all table structure with some filed then use this code. In this query i select column_name,column_type and table_name for more details . I use order by column_type so i can see it easily.
SELECT `COLUMN_NAME`,COLUMN_TYPE,TABLE_NAME
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename' order by DATA_TYPE;
If you want to check only double type filed then you can do it easily
SELECT `COLUMN_NAME`,COLUMN_TYPE,TABLE_NAME,DATA_TYPE
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename' AND DATA_TYPE like '%bigint%' order by DATA_TYPE;
if you want to check which field allow null type etc then you can use this
SELECT `COLUMN_NAME`,COLUMN_TYPE,TABLE_NAME,IS_NULLABLE,DATA_TYPE
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename' and DATA_TYPE like '%bigint%' and IS_NULLABLE ='NO' order by COLUMN_TYPE;
you want to check more then thik link also help you.
https://dev.mysql.com/doc/refman/5.7/en/columns-table.html
this generates a string of column names with a comma delimiter:
SELECT CONCAT('(',GROUP_CONCAT(`COLUMN_NAME`),')')
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='database_name'
AND `TABLE_NAME`='table_name';
function get_col_names(){
$sql = "SHOW COLUMNS FROM tableName";
$result = mysql_query($sql);
while($record = mysql_fetch_array($result)){
$fields[] = $record['0'];
}
foreach ($fields as $value){
echo 'column name is : '.$value.'-';
}
}
return get_col_names();
Not sure if this is what you were looking for, but this worked for me:
$query = query("DESC YourTable");
$col_names = array_column($query, 'Field');
That returns a simple array of the column names / variable names in your table or array as strings, which is what I needed to dynamically build MySQL queries. My frustration was that I simply don't know how to index arrays in PHP very well, so I wasn't sure what to do with the results from DESC or SHOW. Hope my answer is helpful to beginners like myself!
To check result: print_r($col_names);
SHOW COLUMNS in mysql 5.1 (not 5.5) uses a temporary disk table.
http://dev.mysql.com/doc/refman/5.1/en/internal-temporary-tables.html
http://dev.mysql.com/doc/refman/5.1/en/show-columns.html
So it can be considered slow for some cases. At least, it can bump up your created_tmp_disk_tables value. Imagine one temporary disk table per connection or per each page request.
SHOW COLUMNS is not really so slow, possibly because it uses file system cache. Phpmyadmin says ~0.5ms consistently. This is nothing compared to 500ms-1000ms of serving a wordpress page. But still, there are times it matters. There is a disk system involvement, you never know what happens when server is busy, cache is full, hdd is stalled etc.
Retrieving column names through SELECT * FROM ... LIMIT 1 was around ~0.1ms, and it can use query cache as well.
So here is my little optimized code to get column names from a table, without using show columns if possible:
function db_columns_ar($table)
{
//returns Array('col1name'=>'col1name','col2name'=>'col2name',...)
if(!$table) return Array();
if(!is_string($table)) return Array();
global $db_columns_ar_cache;
if(!empty($db_columns_ar_cache[$table]))
return $db_columns_ar_cache[$table];
//IMPORTANT show columns creates a temp disk table
$cols=Array();
$row=db_row_ar($q1="SELECT * FROM `$table` LIMIT 1");
if($row)
{
foreach($row as $name=>$val)
$cols[$name]=$name;
}
else
{
$coldata=db_rows($q2="SHOW COLUMNS FROM `$table`");
if($coldata)
foreach($coldata as $row)
$cols[$row->Field]=$row->Field;
}
$db_columns_ar_cache[$table]=$cols;
//debugexit($q1,$q2,$row,$coldata,$cols);
return $cols;
}
Notes:
As long as your tables first row does not contain megabyte range of data, it should work fine.
The function names db_rows and db_row_ar should be replaced with your specific database setup.
IN WORDPRESS:
global $wpdb; $table_name=$wpdb->prefix.'posts';
foreach ( $wpdb->get_col( "DESC " . $table_name, 0 ) as $column_name ) {
var_dump( $column_name );
}
Try this one out I personally use it:
SHOW COLUMNS FROM $table where field REGEXP 'stock_id|drug_name'
This question is old, but I got here looking for a way to find a given query its field names in a dynamic way (not necessarily only the fields of a table). And since people keep pointing this as the answer for that given task in other related questions, I'm sharing the way I found it can be done, using Gavin Simpson's tips:
//Function to generate a HTML table from a SQL query
function myTable($obConn,$sql)
{
$rsResult = mysqli_query($obConn, $sql) or die(mysqli_error($obConn));
if(mysqli_num_rows($rsResult)>0)
{
//We start with header. >>>Here we retrieve the field names<<<
echo "<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"0\"><tr align=\"center\" bgcolor=\"#CCCCCC\">";
$i = 0;
while ($i < mysqli_num_fields($rsResult)){
$field = mysqli_fetch_field_direct($rsResult, $i);
$fieldName=$field->name;
echo "<td><strong>$fieldName</strong></td>";
$i = $i + 1;
}
echo "</tr>";
//>>>Field names retrieved<<<
//We dump info
$bolWhite=true;
while ($row = mysqli_fetch_assoc($rsResult)) {
echo $bolWhite ? "<tr bgcolor=\"#CCCCCC\">" : "<tr bgcolor=\"#FFF\">";
$bolWhite=!$bolWhite;
foreach($row as $data) {
echo "<td>$data</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
This can be easily modded to insert the field names in an array.
Using a simple: $sql="SELECT * FROM myTable LIMIT 1" can give you the fields of any table, without needing to use SHOW COLUMNS or any extra php module, if needed (removing the data dump part).
Hopefully this helps someone else.
if you use php, use this gist.
it can get select fields full info with no result,and all custom fields such as:
SELECT a.name aname, b.name bname, b.*
FROM table1 a LEFT JOIN table2 b
ON a.id = b.pid;
if above sql return no data,will also get the field names aname, bname, b's other field name
just two line:
$query_info = mysqli_query($link, $data_source);
$fetch_fields_result = $query_info->fetch_fields();
This query fetches a list of all columns in a database without having to specify a table name. It returns a list of only column names:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'db_name'
However, when I ran this query in phpmyadmin, it displayed a series of errors. Nonetheless, it worked. So use it with caution.
if you only need the field names and types (perhaps for easy copy-pasting into Excel):
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA='databasenamegoeshere'
AND DATA_TYPE='decimal' and TABLE_NAME = 'tablenamegoeshere'
remove
DATA_TYPE='decimal'
if you want all data types
i no expert, but this works for me..
$sql = "desc MyTable";
$result = #mysql_query($sql);
while($row = #mysql_fetch_array($result)){
echo $row[0]."<br>"; // returns the first column of array. in this case Field
// the below code will return a full array-> Field,Type,Null,Key,Default,Extra
// for ($c=0;$c<sizeof($row);$c++){echo #$row[$c]."<br>";}
}
I have tried this query in SQL Server and this worked for me :
SELECT name FROM sys.columns WHERE OBJECT_ID = OBJECT_ID('table_name')
The call of DESCRIBE is working fine to get all columns of a table but if you need to filter on it, you need to use the SHOW COLUMNS FROM instead.
Example of PHP function to get all info of a table :
// get table columns (or return false if table not found)
function get_table_columns($db, $table) {
global $pdo;
if($cols = $pdo->query("DESCRIBE `$db`.`$table`")) {
if($cols = $cols->fetchAll(PDO::FETCH_ASSOC)) {
return $cols;
}
}
return false;
}
In my case, I had to find the primary key of a table. So, I used :
SHOW COLUMNS FROM `table` WHERE `Key`='PRI';
Here is my PHP function :
// get table Primary Key
function get_table_pk($db, $table) {
global $pdo;
$q = "SHOW COLUMNS FROM `$db`.`$table` WHERE `Key` = 'PRI'";
if($cols = $pdo->query($q)) {
if($cols = $cols->fetchAll(PDO::FETCH_ASSOC)) {
return $cols[0];
}
}
return false;
}
I have a Dynamic Pivot in MySQL (see this question: MySQL "Multi-Dimensional?" Dynamic Pivot)
I want to know the Column/As/Field names as if it were a table and I queried INFORMATION_SCHEMA (which if this was a REAL table, would be easy enough: MySQL query to get column names?).
But, I can find no question or reference to a function or SELECT option to get the Column/As/Field names from a query. Is this possible? If so, how?
Using Perl to access MySQL (http://dbi.perl.org/).
So, flipping this around... we know the fixed columns. So, if we use the same basic query that creates the Pivot to begin with, we can get a GROUP_CONCAT of the names.
SET #sql = NULL;
SELECT GROUP_CONCAT(qrv.req_name) INTO #sql
FROM (SELECT qrt.req_name FROM qual_requirment_values qrv JOIN qual_requirment_types qrt ON qrt.id = qrv.req_type_id) qrv;
SET #sql = CONCAT('r.rank,r.member_type,im.name,qrv.grouping,', #sql);
SELECT #sql;
This can then be split into an array and used.
Seems like the long way around, but in the absence of something else it will work for my application. Seems horribly inefficient! :)
The better answer, thanks to #OllieJones. The Data Base Interface used to access MySQL should provide a way.
In my case (Perl), the answer is here: http://www.perlmonks.org/?node_id=264623
my $sql = ... [some query];
my $sth = $dbh->prepare($sql);
$sth->execute();
my $field_name_arrayref = $sth->{NAME};
Further to the answer, this is the full method within my MySQL package. do() is our generic DBI method that returns queries in an AoA. Adapting that method to create do_fieldNames();
## Tested Method
sub do_fieldNames {
my ($self, $sql, $has_results) = #_;
my ($sth, $rv, #row, #query_results);
## Execute the SQL statement
$sth = $$self->prepare($sql);
$rv = $sth->execute or &error(3306, __LINE__, __FILE__, $sql, $$self->errstr);
return undef unless $rv > 0;
## SOLUTION >> Field Name arrayref, part of the standard included DBI Perl Module
my $field_name_arrayref = $sth->{NAME};
## Parse the results
if ($has_results || $sql =~ /^select/i) {
while (#row = $sth->fetchrow_array) {
push #query_results, [ #row ];
}
}
## Return results
return (\#query_results, $field_name_arrayref) ;
}
I have two mysql commands. I want to create a subroutine with these two mysql commands for the rest of my data that I have to search through. I have a lot of entries. Is there a way to create a subroutine such that in place of the actual numbers and characters I put in my two mysql commands, I put in variables that I can replace so I can then copy and paste the actual values of those variables and the commands are executed for the remaining entries?
For example, I have a command that says
$sth = $dbh->prepare ("select name from table1 where number > 5");
$sth->execute();
#row;
while (#row = $sth->fetchrow_array) {
print "$row[0]\tquestion1\n";
In place of the "5" listed in the select command and "question1" listed in the print command, I want to put something in place of it like "variables" so that I can create a subroutine with these commands in it, but you execute and can run the subroutine over and over by plugging in different values for those variables.
something like this: $dbh = DBI->connect($dsn, $user, $password);
not sure how to go about doing this for mysql perl.
You can use placeholders in your query to use different values in a search.
$sth = $dbh->prepare ("select name from table1 where number > ?");
$sth->execute(5);
After that, it should be trivial to make a subroutine for your print.
For example:
my #values = qw(5 10 15 20);
my #fields = qw(question1 question2);
# ... other code..
my $sth = $dbh->prepare ("select name from table1 where number > ?");
for my $field (#fields) {
for my $value (#values) {
printfields($sth, $value, $field);
}
}
sub printfields {
my ($sth, $value, $field) = #_;
$sth->execute($value);
while (my #row = $sth->fetchrow_array) {
print "$row[0]\t$field\n";
}
}
I prefer to build the select query before running prepare(). Then passing it into prepare() as a scalar. You could also add placeholders in the scalar (if you don't want to simply rebuild it for each query) that could easily be replaced via calls of s///;, which could be easily named/identified as well. This would make the code a bit easier to read than passing bare values to execute().
I'm new in mysql language and can not understand difference between procedures and functions, can anyone answer in which case should be use this routines ?
Also have some example => I've table named "data" and columns named "id"(primary key) , "local". this local includes multiple exactly same data. I want to search every id of this "data" (and after result manipulate with it) table which local equal to (for instance) 'something'
Please answer in this question ... Thanks
Functions:
select <function>(column) from table where <condition>;
Procedure:
call <procedure>( param0, param1 );
To get your result:
select * from <table> where data like "%something%";
I suppose that you use php with mysql.
your query should be
$result = mysql_query("SELECT * FROM data WHERE local='something'");
while($row = mysql_fetch_array($result))
{
// here you manipulate with your data
// for example:
echo $row['id'];
}
Using MySQL I can run the query:
SHOW CREATE TABLE MyTable;
And it will return the create table statement for the specificed table. This is useful if you have a table already created, and want to create the same table on another database.
Is it possible to get the insert statement for an already existing row, or set of rows? Some tables have many columns, and it would be nice for me to be able to get an insert statement to transfer rows over to another database without having to write out the insert statement, or without exporting the data to CSV and then importing the same data into the other database.
Just to clarify, what I want is something that would work as follows:
SHOW INSERT Select * FROM MyTable WHERE ID = 10;
And have the following returned for me:
INSERT INTO MyTable(ID,Col1,Col2,Col3) VALUES (10,'hello world','some value','2010-10-20');
There doesn't seem to be a way to get the INSERT statements from the MySQL console, but you can get them using mysqldump like Rob suggested. Specify -t to omit table creation.
mysqldump -t -u MyUserName -pMyPassword MyDatabase MyTable --where="ID = 10"
In MySQL Workbench you can export the results of any single-table query as a list of INSERT statements. Just run the query, and then:
click on the floppy disk near Export/Import above the results
give the target file a name
at the bottom of the window, for Format select SQL INSERT statements
click Save
click Export
Since you copied the table with the SQL produced by SHOW CREATE TABLE MyTable, you could just do the following to load the data into the new table.
INSERT INTO dest_db.dest_table SELECT * FROM source_db.source_table;
If you really want the INSERT statements, then the only way that I know of is to use mysqldump http://dev.mysql.com/doc/refman/5.1/en/mysqldump.htm. You can give it options to just dump data for a specific table and even limit rows.
I wrote a php function that will do this. I needed to make an insert statement in case a record needs to be replaced after deletion for a history table:
function makeRecoverySQL($table, $id)
{
// get the record
$selectSQL = "SELECT * FROM `" . $table . "` WHERE `id` = " . $id . ';';
$result = mysql_query($selectSQL, $YourDbHandle);
$row = mysql_fetch_assoc($result);
$insertSQL = "INSERT INTO `" . $table . "` SET ";
foreach ($row as $field => $value) {
$insertSQL .= " `" . $field . "` = '" . $value . "', ";
}
$insertSQL = trim($insertSQL, ", ");
return $insertSQL;
}
Laptop Lift's code works fine, but there were a few things I figured people may like.
Database handler is an argument, not hardcoded. Used the new mysql api. Replaced $id with an optional $where argument for flexibility. Used real_escape_string in case anyone has ever tried to do sql injection and to avoid simple breakages involving quotes. Used the INSERT table (field...) VALUES (value...)... syntax so that the fields are defined only once and then just list off the values of each row (implode is awesome). Because Nigel Johnson pointed it out, I added NULL handling.
I used $array[$key] because I was worried it might somehow change, but unless something is horribly wrong, it shouldn't anyway.
<?php
function show_inserts($mysqli,$table, $where=null) {
$sql="SELECT * FROM `{$table}`".(is_null($where) ? "" : " WHERE ".$where).";";
$result=$mysqli->query($sql);
$fields=array();
foreach ($result->fetch_fields() as $key=>$value) {
$fields[$key]="`{$value->name}`";
}
$values=array();
while ($row=$result->fetch_row()) {
$temp=array();
foreach ($row as $key=>$value) {
$temp[$key]=($value===null ? 'NULL' : "'".$mysqli->real_escape_string($value)."'");
}
$values[]="(".implode(",",$temp).")";
}
$num=$result->num_rows;
return "INSERT `{$table}` (".implode(",",$fields).") VALUES \n".implode(",\n",$values).";";
}
?>
In PHPMyAdmin you can:
click copy on the row you want to know its insert statements SQL:
click Preview SQL:
you will get the created insert statement that generates it
You can apply that on many rows at once if you select them and click copy from the bottom of the table and then Preview SQl
I use the program SQLYOG where I can make a select query, point at the results and choose export as sql. This gives me the insert statements.
The below command will dump into the terminal without all the extra stuff mysqldump will output surrounding the INSERT. This allows copying from the terminal without it writing to a file. This is useful if the environment restricts writing new files.
mysqldump -u MyUserName -pMyPassword MyDatabase MyTable --where="ID = 10" --compact --no-create-info --complete-insert --quick
Using mysqldump --help I found the following options.
-q, --quick Don't buffer query, dump directly to stdout.
(Defaults to on; use --skip-quick to disable.)
-t, --no-create-info
Don't write table creation info.
-c, --complete-insert
Use complete insert statements.
--compact Give less verbose output (useful for debugging). Disables
structure comments and header/footer constructs. Enables
options --skip-add-drop-table --skip-add-locks
--skip-comments --skip-disable-keys --skip-set-charset.
If you want get "insert statement" for your table you can try the following code.
SELECT
CONCAT(
GROUP_CONCAT(
CONCAT(
'INSERT INTO `your_table` (`field_1`, `field_2`, `...`, `field_n`) VALUES ("',
`field_1`,
'", "',
`field_2`,
'", "',
`...`,
'", "',
`field_n`,
'")'
) SEPARATOR ';\n'
), ';'
) as `QUERY`
FROM `your_table`;
As a result, you will have insers statement:
INSERT INTO your_table (field_1, field_2, ..., field_n) VALUES (value_11, value_12, ... , value_1n);
INSERT INTO your_table (field_1, field_2, ..., field_n) VALUES (value_21, value_22, ... , value_2n);
/...................................................../
INSERT INTO your_table (field_1, field_2, ..., field_n) VALUES (value_m1, value_m2, ... , value_mn);
, where m - number of records in your_table
Within MySQL work bench perform the following:
Click Server > Data Export
In the Object Selection Tab select the desired schema.
Next, select the desired tables using the list box to the right of the schema.
Select a file location to export the script.
Click Finish.
Navigate to the newly created file and copy the insert statements.
you can use Sequel pro to do this, there is an option to 'get as insert statement' for the results obtained
There is a quite easy and useful solution for creating an INSERT Statement for editing without the need to export SQL with just Copy & Paste (Clipboard):
Select the row in a query result window of MySQL Workbench, probably even several rows. I use this even if the row does contain different data than I want to insert in my script or when the goal is to create a prepared statement with ? placeholders.
Paste the copied row which is in your clipboard now into the same table (query results list is an editor in workbench) into the last free row.
Press "Apply" and a windows opens showing you the INSERT statement - DO NOT EXECUTE
Copy the SQL from the window to your clipboard
CANCEL the execution, thus not changing the database but keeping the SQL in your clipboard.
Paste the SQL wherever you want and edit it as you like, like e.g. inserting ? placeholders
You can create a SP with the code below - it supports NULLS as well.
select 'my_table_name' into #tableName;
/*find column names*/
select GROUP_CONCAT(column_name SEPARATOR ', ') from information_schema.COLUMNS
where table_schema =DATABASE()
and table_name = #tableName
group by table_name
into #columns
;
/*wrap with IFNULL*/
select replace(#columns,',',',IFNULL(') into #selectColumns;
select replace(#selectColumns,',IFNULL(',',\'~NULL~\'),IFNULL(') into #selectColumns;
select concat('IFNULL(',#selectColumns,',\'~NULL~\')') into #selectColumns;
/*RETRIEVE COLUMN DATA FIELDS BY PK*/
SELECT
CONCAT(
'SELECT CONCAT_WS(','''\'\',\'\''',' ,
#selectColumns,
') AS all_columns FROM ',#tableName, ' where id = 5 into #values;'
)
INTO #sql;
PREPARE stmt FROM #sql;
EXECUTE stmt;
/*Create Insert Statement*/
select CONCAT('insert into ',#tableName,' (' , #columns ,') values (\'',#values,'\')') into #prepared;
/*UNWRAP NULLS*/
select replace(#prepared,'\'~NULL~\'','NULL') as statement;
For HeidiSQL users:
If you use HeidiSQL, you can select the row(s) you wish to get insert statement. Then right click > Export grid rows > select "Copy to clipboard" for "Output target", "Selection" for "Row Selection" so you don't export other rows, "SQL INSERTs" for "Output format" > Click OK.
The insert statement will be inside you clipboard.
In case you use phpMyAdmin (Tested on version 5.x):
Click on "Edit" button next to the row for which you would like to have an insert statement, then on the bottom next to the action buttons just select "Show insert query" and press "Go".
With PDO you can do it this way.
$stmt = DB::getDB()->query("SELECT * FROM sometable", array());
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
$fields = array_keys($array[0]);
$statement = "INSERT INTO user_profiles_copy (".implode(",",$fields).") VALUES ";
$statement_values = null;
foreach ($array as $key => $post) {
if(isset($statement_values)) {
$statement_values .= ", \n";
}
$values = array_values($post);
foreach($values as $index => $value) {
$quoted = str_replace("'","\'",str_replace('"','\"', $value));
$values[$index] = (!isset($value) ? 'NULL' : "'" . $quoted."'") ;
}
$statement_values .= "(".implode(',',$values).")";
}
$statement .= $statement_values . ";";
echo $statement;
I think that the answer provided by Laptop Lifts is best...but since nobody suggested the approach that I use, i figured i should chime in. I use phpMyAdmin to set up and manage my databases most of the time. In it, you can simply put checkmarks next to the rows you want, and at the bottom click "Export" and chose SQL. It will give you INSERT statements for whichever records you selected. Hope this helps.
You can try this
function get_insert_query($pdo, $table, $where_sth)
{
$sql = "";
$row_data = $pdo->query("SELECT * FROM `{$table}` WHERE $where_sth")->fetch();
if($row_data){
$sql = "INSERT INTO `$table` (";
foreach($row_data as $col_name => $value){
$sql .= "`".$col_name."`, ";
}
$sql = rtrim($sql, ", ");
$sql .= ") VALUES (";
foreach($row_data as $col_name => $value){
if (is_string($value)){
$value = $pdo->quote($value);
} else if ($value === null){
$value = 'NULL';
}
$sql .= $value .", ";
}
$sql = rtrim($sql, ", ");
$sql .= ");";
}
return $sql;
}
To use it, just call:
$pdo = new PDO( "connection string goes here" );
$sql = get_insert_query($pdo, 'texts', "text_id = 959");
echo $sql;
Update for get insert statement for current registers at PhpMyAdmin:
Select the table from you DB to get registers from
"Export" tab at the top menú as the image below
Custom export
Move down to "Data creation options"
Once there, select "Insert" function at your preferred syntax
Its very simple. All you have to do is write an Insert statement in a static block and run it as a script as a whole block.
E.g. If you want to get Insert statements from a table (say ENGINEER_DETAILS) for selected rows, then you have to run this block -
spool
set sqlformat insert
select * from ENGINEER_DETAILS where engineer_name like '%John%';
spool off;
The output of this block will be Insert statements.
In MySQL Workbench, right-click the table and select 'Send to SQL Editor'/'Insert Statement'. Clean it up a bit and you're good to go.
Based on your comments, your goal is to migrate database changes from a development environment to a production environment.
The best way to do this is to keep your database changes in your source code and consequently track them in your source control system such as git or svn.
you can get up and running quickly with something like this: https://github.com/davejkiger/mysql-php-migrations
as a very basic custom solution in PHP, you can use a function like this:
function store_once($table, $unique_fields, $other_fields=array()) {
$where = "";
$values = array();
foreach ($unique_fields as $k => $v) {
if (!empty($where)) $where .= " && ";
$where .= "$k=?";
$values[] = $v;
}
$records = query("SELECT * FROM $table WHERE $where", $values);
if (false == $records) {
store($table, array_merge($unique_fields, $other_fields));
}
}
then you can create a migration script which will update any environment to your specifications.