PHP MYSQL unable to store object properties in table
I'm trying to add iterate through an object and add those object properties to mysql database. Using:
//This works
$sql = "CREATE TABLE $table ($ID int primary key auto_increment not null)";
mysql_query($sql);
//This works
function iterateObject($obj, $name='') {
foreach ($obj as $key=>$val) {
$myName = ($name !='') ? $name . "_" . $key : $key;
if ( is_object($val) || is_array($val) ) {
iterateObject($val, $myName);
} else {
//This works
$sql = ("ALTER TABLE home_timeline ADD COLUMN $myName VARCHAR(256);");
mysql_query($sql);
//This doesn't work
$sql2 = ("INSERT INTO home_timeline ($myName) VALUES ($val);");
mysql_query($sql2);
print "$myName - $val <br />";
}
}
}
The table is created and altered so that each iteration adds a new column to the table but when I try and add values to that column (second s开发者_Go百科ql statement) everything is null and the script creates 20+ rows rather than having all the values appear on one row in the relevant column. Could someone help?
why not use functions like serialize()
and unserialize()
when converting objects to/from string?
second: if $val
is string, then in the query put the string delimiters
"INSERT INTO home_timeline (`$myName`) VALUES ('$val');"
though inserting parameters via concatenation is a very bad practice prone to SQL injection.
If you have further problems, output the query before execution and put it here. You might be experiencing the case when you got a lot of columns which can't be nulls, and have no default values. Also output the table structure here.
精彩评论