Error updating using array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Fabiooo7
Forum Newbie
Posts: 10
Joined: Sun Feb 16, 2014 3:23 pm

Error updating using array

Post by Fabiooo7 »

[text]Hello Staff
I'm having trouble with my script to update records
someone could help me find the error?[/text]

Code: Select all


<form method="post">
<?
include "config.php";  
$id = $_GET['id'];
 
$sql = "SELECT * FROM incluidos2 WHERE tipo ='Salgados'  ";
$result = mysql_query($sql) or die ("Erro na consulta");
$count=mysql_num_rows($result);
while($linha=mysql_fetch_array($result)){

$id = $linha['id'];
$nome = $linha['nome'];
$tipo = $linha['tipo'];
$valor = $linha['valor'];
$unid = $linha['unid'];
$foto = $linha['foto'];

?>
    <input type="hidden" name="id[]"  value="<?echo $id?>" />
    Unid<input type="text" name="unid[]" size="2" value="<?echo $unid?>" /><br />
    
<?}?> 
<br />       
<input type="submit" value="Registrar" />
<br /><br />
</form>

<?php
if (isset($_POST['id'])) {
	$id = $_POST['id'];
    $sql = "UPDATE incluidos2 SET unid = '$unid' WHERE id = '$id' ";
    $result = mysql_query($sql) or die( mysql_error());
	if($result){
		echo "<meta http-equiv=\"refresh\" content=\"0;URL=teste.php\">";
	}
}
mysql_close();


?>

[text]

Thanks to all
[/text]
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Error updating using array

Post by Celauran »

You're trying to pass arrays directly into your update query. You need to extract the values from those arrays beforehand and update each row separately. Alternately, you could do a single INSERT ... ON DUPLICATE UPDATE
Fabiooo7
Forum Newbie
Posts: 10
Joined: Sun Feb 16, 2014 3:23 pm

Re: Error updating using array

Post by Fabiooo7 »

Hello Celauran Thanks For the help
I have no idea how to do that would have an example for me to follow
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Error updating using array

Post by Celauran »

Something like this

Code: Select all

foreach ($_POST['id'] as $key => $value) {
	$id = mysql_real_escape_string($value);
	$unid = mysql_real_escape_string($_POST['unid'][$key]);
	$query = "UPDATE incluidos2 SET unid = '{$unid}' WHERE id = '{$id}'";
	mysql_query($query);
}
Fabiooo7
Forum Newbie
Posts: 10
Joined: Sun Feb 16, 2014 3:23 pm

Re: Error updating using array

Post by Fabiooo7 »

Hello Friend. ok
Many thanks for the help, worked perfectly
Bo got very far.
thank you
Post Reply