A
A
Andrey Petrov2013-11-27 12:08:33
PHP
Andrey Petrov, 2013-11-27 12:08:33

Loop insert into MySQL table from another table

Hello. Need help with this problem:
In the Joomla 2.5 database there is a table table1, the data from which is inserted into the table table2 by a php script. But in the `asset_id` field of the table2 table, I need to insert MY value with an increase by one for each subsequent record when inserting.
There is a code. Everything is inserted. But in the `asset_id` field, only the first value of the counter is constantly inserted into each line and there is no increment by one.
Tell me, where is the error?
The code:

include 'configuration.php';
$config = new JConfig;
$link = mysqli_connect($config->host, $config->user, $config->password)or die('db not found');
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
else {
echo "Connect";
}
mysqli_select_db($link, $config->db)
or die('db not found');

for($key=0;$key<265;$key++){
$myasset = $key+50; // учитываем уже имеющиеся значения asset_id в таблице table2
$insert = "INSERT INTO `table2` (
`id`, 
`asset_id`, 
`title`
) 
SELECT 
`id`, 
'".$myasset."' ,
`title`
FROM `table1` ";
$result = mysqli_query($link, $insert);
}
mysqli_close($link);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikolay Eliseev, 2013-11-27
@anndmill

Your request is invalid!
Look, you transfer the data from the table `table1` 265 times to the table `table2`
In your case, it is enough to execute the query from the $insert variable once with the correction:
Or, if you need to take into account the older `asset_id` and it is equal to 50

INSERT INTO `table2` (`id`,`asset_id`,`title`) SELECT `id`,`asset_id`+50+1 ,`title` FROM `table1`

Y
Yuri Denisov, 2013-11-27
@denissov

and asset_id auto_increment cannot be set?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question