Daniel Robinson
Daniel Robinson

Reputation: 653

update row with array items into database php

I am trying to update a record in my database with values pulled from an exploded array

    $arr2 = explode(",",$_POST['hidden-tags']); 
   //echo $arr2[0];

   //insert new rows into blog post
    mysql_select_db($db, $db);
 $insertq = mysql_query("UPDATE blog SET tags1 = $arr2[0],tags2 = $arr2[1],tags3 = $arr2[2], tags4 = $arr2[3], tags5 = $arr2[4]  WHERE idblog = '$id' ",$dbconnet);

If I echo the values from my array one at a time it works great. Once I try to put them in the db the row turns up empty. Whats more the user may not of entered 5 items they may only have entered 1 but I dont think thats really the problem. To be honest I cant see why its currently failing at all.

I know I can save all values in one field but it will be easier as separate fieldsfor when I pull back and query later on.

Upvotes: 1

Views: 1308

Answers (4)

Roger
Roger

Reputation: 1693

I think you might need to look at the datatypes of your table. If you are using varchar or text as data-types then single colon will be necessary.

$insertq = mysql_query("UPDATE blog SET tags1 =' $arr2[0]',tags2 = '$arr2[1]',tags3 = '$arr2[2]', tags4 = '$arr2[3]', tags5 = '$arr2[4]'  WHERE idblog = '$id' ",$dbconnet);

Also if the idblog is integer then donot use single quotes.

hope this helps

Upvotes: 1

Devang Rathod
Devang Rathod

Reputation: 6736

It should be like this :

$insertq = mysql_query("UPDATE blog SET tags1 = "'.$arr2[0].'",tags2 = "'.$arr2[1].'",tags3 = "'.$arr2[2].'", tags4 = "'.$arr2[3].'", tags5 = "'.$arr2[4].'"  WHERE idblog = "'.$id.'" ",$dbconnet);

Upvotes: 1

John Woo
John Woo

Reputation: 263713

if the data types of the columns are string, values must be wrap with single quotes as they are string literals. eg,

$insertq = mysql_query("UPDATE blog SET tags1 = '". $arr2[0] . "',....");

As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Upvotes: 1

nowhere
nowhere

Reputation: 1548

$insertq = mysql_query("UPDATE blog SET tags1 = $arr2[0],tags2 = $arr2[1],tags3 = $arr2[2], tags4 = $arr2[3], tags5 = $arr2[4]  WHERE idblog = '$id' ",$dbconnet);

should be:

$insertq = mysql_query("UPDATE blog SET tags1 = '".$arr2[0]."',tags2 = '".$arr2[1]."',tags3 = '".$arr2[2]."', tags4 = '".$arr2[3]."', tags5 = '".$arr2[4]."'  WHERE idblog = '".$id."' ,$dbconnet);

or the whole query is going to consider the variables names as part of the string

EDITED: i had the quotes inverted.

Upvotes: 1

Related Questions