How to prevent PHP variables from being arrays or objects?
Posted
by MJB
on Stack Overflow
See other posts from Stack Overflow
or by MJB
Published on 2010-06-02T13:09:50Z
Indexed on
2010/06/02
14:24 UTC
Read the original article
Hit count: 229
I think that (the title) is the problem I am having. I set up a MySQL connection, I read an XML file, and then I insert those values into a table by looping through the elements. The problem is, instead of inserting only 1 record, sometimes I insert 2 or 3 or 4. It seems to depend on the previous values I have read. I think I am reinitializing the variables, but I guess I am missing something -- hopefully something simple.
Here is my code. I originally had about 20 columns, but I shortened the included version to make it easier to read.
$ctr = 0;
$sql = "insert into csd (id,type,nickname,hostname,username,password) ".
"values (?,?,?,?,?,?)";
$cur = $db->prepare($sql);
for ($ctr = 0; $ctr < $expected_count; $ctr++) {
unset($bind_vars,$dat);
$lbl = "csd_{$ctr}";
$dat['type'] = (string) $ref->itm->csds->$lbl->type;
$dat['nickname'] = (string) $ref->itm->csds->$lbl->nickname;
$dat['hostname'] = (string) $ref->itm->csds->$lbl->hostname;
$dat['username'] = (string) $ref->itm->csds->$lbl->username;
$dat['password'] = (string) $ref->itm->csds->$lbl->password;
$bind_vars = array( $id,$dat['$type'], $dat['$nickname'], $dat['$hostname'],
$dat['$username'], $dat['$password']);
print_r ($bind_vars);
$res = $db->execute($cur, $bind_vars);
}
P.S. I also tagged this SimpleXML because that is how I am reading the file, though that code is not included above. It looks like this:
$ref = simplexml_load_file($file);
UPDATE: I've changed the code around as per suggestions, and now it is not always the same pattern, but it is equally broken. When I display the bind array before inserting, it looks like this. Note that I also count the rows before and after, so there are 0 rows, then I insert 1, then there are 2:
0 CSDs on that ITEM now.
Array
(
[0] => 2
[1] => 0
[2] =>
[3] => X
[4] => XYZ
[5] =>
[6] =>
[7] =>
[8] => audio
[9] =>
[10] => 192.168.0.50
[11] => 192.168.0.3
[12] => 255.255.255.0
[13] => 255.255.255.0
[14] =>
[15] =>
[16] =>
[17] => 21
[18] => 5
[19] => Y
[20] => /dir
)
2 CSDs on that ITEM now.
© Stack Overflow or respective owner