Mount INSERT from SELECT

3

I would like to make a select and from it generate insert . I want to start from the preposto that I do not know the table structure, the number of columns, nothing more than the table name.

select * from cliente where nome like 'PEDRO%';

Viraria:

insert into cliente(.......) values(.......);
insert into cliente(.......) values(.......);
insert into cliente(.......) values(.......);
insert into cliente(.......) values(.......);
insert into cliente(.......) values(.......);

Is there any way to do this directly in mysql ? If not, how can php be possible in any way?

My intention is to save this result to a .sql file and leave it saved on the machine.
If mysql generates this output, I will export via php , otherwise, php itself should generate this expected output. But I do not know the table structure, so I can not tell which fields would be filled

    
asked by anonymous 07.08.2018 / 19:56

2 answers

5

EDITION

After talking to Marconi , I realized that you need to know the data type of each field in your table. To do this, I've used mysqli_fetch_field and with values I saved in an array. The values of this function are returned by the numbers representing the data type of the table field.

Thanks to this good citizen we can see the values of each type in this table:

numerics 
-------------
BIT: 16
TINYINT: 1
BOOL: 1
SMALLINT: 2
MEDIUMINT: 9
INTEGER: 3
BIGINT: 8
SERIAL: 8
FLOAT: 4
DOUBLE: 5
DECIMAL: 246
NUMERIC: 246
FIXED: 246

dates
------------
DATE: 10
DATETIME: 12
TIMESTAMP: 7
TIME: 11
YEAR: 13

strings & binary
------------
CHAR: 254
VARCHAR: 253
ENUM: 254
SET: 254
BINARY: 254
VARBINARY: 253
TINYBLOB: 252
BLOB: 252
MEDIUMBLOB: 252
TINYTEXT: 252
TEXT: 252
MEDIUMTEXT: 252
LONGTEXT: 252

And then create a function to know whether or not the value to be concatenated needs quotation marks.

function getTypeCampo($number){
    $numerics = array('16', '1', '2', '9', '3', '8', '4', '5', '246');
    if(in_array($number, $numerics)){
        return "numeric";
    }
    return "string";    
}

Full Code:

$query = mysqli_query($conn, "SELECT * FROM tabela WHERE campo LIKE 'PEDRO%'");
// string inicial
$campos = "INSERT INTO tabela (";
$valores = "VALUES ";
$status = true;
$titposDeDados = array();
while($value = mysqli_fetch_assoc($query)){
    $key = 0;
    $valores .= "(";
    if($status){
        // pega o tipo de dados e monta o array 
        while($types = mysqli_fetch_field($query)){
            $titposDeDados[] = getTypeCampo($types->type);
        }
        // pega o nome dos campos da tabela e concatena em $campos
        foreach($value as $campo => $valor){
            $campos .= "'".$campo."',";
             if($titposDeDados[$key] == 'string'){
                 $valores .= "'".$valor."',";
             } else {
                 $valores .= $valor.",";
             }
             $key++;
        }
        $status = false;
    } else {
        // concatena os valores que serão inseridos em $valores
        foreach($value as $valor){
            if($titposDeDados[$key] == 'string'){
                 $valores .= "'".$valor."',"; // se for string (varchar, text, ...)
             } else {
                 $valores .= $valor.","; // se for numerico (integer, decimal, ..)
             }
            $key++;
        }
    }
    $valores = substr($valores, 0, -1);
    $valores .= "),";
}

$insert = substr($campos, 0, -1).") ".substr($valores, 0, -1);
echo $insert; // mostra a string

function getTypeCampo($number){
    $numerics = array('16', '1', '2', '9', '3', '8', '4', '5', '246');
    if(in_array($number, $numerics)){
        return "numeric";
    }
    return "string";    
}
    
07.08.2018 / 20:41
0

In that case I think it would be easier with php. You will need to create a loop of repetition with the results. More or less like this:

select * from cliente where nome like 'PEDRO%';
$conexaoBanco = mysqli_query;

while($valorSelect = mysqli_fetch_array($resultadoDaQuery)){
    insert into cliente(nome, cpf, exemplo) values($valorSelect['nome'], $valorSelect['cpf'], $valorSelect['exemplo'] );
    $conexaoBanco = mysqli_query;
}

Well I do not know how you make your connection to the bank, I just put an example there. Anything ask the question how you make the connection.

    
07.08.2018 / 20:34