weedo Posted January 10, 2009 Share Posted January 10, 2009 I have a PHP V5.1 script that is inserting a string variable ( $icw->t_name[0] ) into a MySQL V5 table. The following code works just fine, $t_name = $icw->t_name[0]; $sql = "insert into team (teamname) values (\"$t_name\")"; $result = @mysql_query($sql, $conn) ; But if I rewrite the code as follows, $sql = "insert into team (teamname) values (\"$icw->t_name[0]\")"; $result = @mysql_query($sql, $conn) ; instead of the the string variable being entered into the table I end up with Array(0) when I check the contents of the table field teamname. Can someone help explain what is going on. Quote Link to comment Share on other sites More sharing options...
xtopolis Posted January 10, 2009 Share Posted January 10, 2009 I don't know how to exactly explain it.. but the idea of $icw->t_name[0] involves a process of going to the object $icw and then accessing its property $t_name and then accessing the first element in the $t_name array. So the php interpreter isn't (able to?) taking all those steps and is stopping after the first conversion: variable name => value. which means $icw->t_name[0] to value "array[0]". The quick fix is: $sql = "insert into team (teamname) values ('".$icw->t_name[0]."')"; or you can use your \""..$icw->t_name[0]."\" ...but I think that's messy. Quote Link to comment Share on other sites More sharing options...
weedo Posted January 10, 2009 Author Share Posted January 10, 2009 Great, thanks thats fixed the problem and saved me writing a whole bunch of extra code. I assume that by enclosing the object=>parameter withing single quotes and forcing a concatenation with . helps the PHP interpreter resolve the string variable correctly. Is this is what is happening with this fix ? Quote Link to comment Share on other sites More sharing options...
xtopolis Posted January 10, 2009 Share Posted January 10, 2009 INSERT INTO tableName (column,column) VALUES ('value','value') Mysql expects VALUES values to be quoted; I just prefer single quotes because my sql statements are always enclosed in double quotes for interpretation. //me $sql = "INSERT INTO hats (hatID, hatName) VALUES ('','Cowboy'), ('','$hatname')"; As for the other part, taking it out of the string context probably allows it to resolve to the correct final value and then you just concatenate it with the two sides of the string. I don't know enough about it to give you a solid answer though. edit: On a side note, you should amend the class that you instantiate $icw from and use a getter method to return the appropriate value instead of trying to access the property directly. That would probably allow you to do it as you had it. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.