PHP Functions
Hey
Here's what I want to happen:
A form is submitted, with 6 variables... name, description, subject, type, email, and content.
I want it to choose the MySQL table to write to by the type drop down box... I have this set up now, using if/elseif/else loops with the entire code in each. However, that is a real pain to edit, so I want to create a function that inserts the data into the separate tables... Here is the code
<?php
function insert($table) {
$insert = \"INSERT INTO $table (name, description, subject, return, message) VALUES ('$name',
'$client_message_description',
'$subject', '$return', '$message') \";
$return = mysql_query($insert);
if ($return) {
print \"Message added to $account<br>\";
echo $client_message_type;
print \"<br>$account<br> $name<br>\";
} else {
print \"Error: It didn't work\";
echo mysql_error();
}
}
?>
Later, it calls this function:
<?php
if ($type == \"New\") {
insert(new);
} elseif ($type == \"Update\") {
insert(update);
}
?>
However, this doesn't add the form data into the database, it just puts empty lines in.
The variables that are in the VALUE() part of the MySQL query are passed from the form.
Why does it do this?
What's wrong?
How can I fix this?
Thanks
Mark Hensler posted this at 23:28 — 4th May 2002.
He has: 4,048 posts
Joined: Aug 2000
hmm...
<?php
function insert($table, $fields) {
for ($i=0; $i<count($fields); $i++) {
$fields[$i] = key($fields[$i]) . \"='\" . $fields[$i] . \"'\";
}
$insert = \"INSERT INTO $table SET \";
$insert .= implode(\", \", $fields);
$return = mysql_query($insert);
if ($return) {
print \"Message added to $account<br>\";
echo $client_message_type;
print \"<br>$account<br> $name<br>\";
} else {
print \"Error: It didn't work\";
echo mysql_error();
}
}
// table : type
// fields : name, description, subject, email, content
$values = array(
//field => value
'name' => $name,
'description' => $description,
'subject' => $subject,
'email' => $email,
'content' => $content);
if ($type == \"New\") {
insert('new', $values);
} elseif ($type == \"Update\") {
insert('update', $values);
}
?>
Mark Hensler
If there is no answer on Google, then there is no question.
nike_guy_man posted this at 01:03 — 5th May 2002.
They have: 840 posts
Joined: Sep 2000
I'm getting this error repeatedly... it never ends lol
Line 11 is
<?php
$fields[$i] = key($fields[$i]) . \"='\" . $fields[$i] . \"'\";
?>
Mark Hensler posted this at 06:17 — 5th May 2002.
He has: 4,048 posts
Joined: Aug 2000
Ssorry, I made a boo boo.
<?php
function insert($table, $fields) {
foreach ($fields as $key=>$val) {
$field[$key] = \"$key='$val'\";
}
$insert = \"INSERT INTO $table SET \";
$insert .= implode(\", \", $fields);
// . . .
?>
Mark Hensler
If there is no answer on Google, then there is no question.
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.