mysql update using array

0

I'm having trouble inserting an array into the database ... I tried this script but it only inserts the last id of the array;

<?php
$_conexao = mysqli_connect("localhost", "root", "", "vbt_posteds");
$id_ind = $_POST["inds"];

$id = "57";

$dados = count($id_ind);

for($i=0; $i<$dados; $i++){

$idfnc = $id_ind[$i];

$sql = mysqli_query($_conexao,"UPDATE dados_inds SET id_inds='$idfnc'
                    WHERE id_user='$id'");              
}

echo "editado com sucesso";

?>

I want to update a relational table with 4 rows with ids

<table>
<tr>
<td>id_user</td><td>id_inds</td>
</tr>
<tr>
<td>57</td><td>8</td>
</tr>
<tr>
<td>57</td><td>4</td>
</tr>
<tr>
<td>57</td><td>5</td>
</tr>
<tr>
<td>57</td><td>2</td>
</tr>
<table>
    
asked by anonymous 25.09.2014 / 16:07

1 answer

1

If you are trying to update data from a relational table you need a compound key or a primary key to identify which record is going to be updated.

Below I would indicate what the records in your relationship table would look like with a primary key.

 id | id_user | id_inds
 1  | 57      | 2
 2  | 57      | 4
 3  | 57      | 5
 4  | 57      | 8

The id field can be auto-increment .

To update a record you would use the id field as a reference.

It looks like this:

$_conexao = mysqli_connect( 'localhost', 'root', '', 'vbt_posteds' );

$all_ids = $_POST[ 'ids' ];
$all_id_ind = $_POST[ 'inds' ];

foreach( $all_ids as $key => $id ) {
    $id_ind = $all_id_ind[ $key ];

    $query = "UPDATE 'dados_inds' SET 'id_inds' = '$id_ind' WHERE id = '$id'";
    $sql = mysqli_query( $_conexao, $query );              
}

echo "editado com sucesso";

Note that I have not used the id_user field because it will not be updated and will not serve as a reference to identify the record that I should update.

If you can not add this primary field to your relational table, I recommend deleting all records related to a user and then entering the new relationship.

$_conexao = mysqli_connect( 'localhost', 'root', '', 'vbt_posteds' );

$id_user = 57;
$all_id_ind = $_POST[ 'inds' ];

// Excluo todos os relacionamentos do usuário
$query = "DELETE FROM 'dados_inds' WHERE 'id_user' = '$id_user'";
$sql = mysqli_query( $_conexao, $query );     

foreach( $all_id_ind as $id_ind ) {
    $query = "INSERT INTO 'dados_inds' ( 'id_inds', 'id_user' ) VALUES ( '$id_ind', 'id_user' )";
    $sql = mysqli_query( $_conexao, $query );              
}

echo "editado com sucesso";
    
25.09.2014 / 17:26