aumandg aumandg - 4 years ago 129
PHP Question

how to insert into multiple fields in same db

I am looking to insert a single selection into a field for multiple users. I have the following code, when the selection is made and submit is entered. I do not get an error, I get the next page with the message posted 5 times, which is how many users are not it the weekpicks table. But nothing is inserted into the DB.



<?
// This code is to use to place info into the MySQL

$sTeam1 = $_POST['sTeam1'];

// (WHERE username FROM authorize WHERE username not in ( SELECT username FROM weekpicks WHERE whatweek='$totalnoOfWeek' )" .

//$nMemberID = (integer) Query

$sql_events = mysql_query("SELECT username FROM authorize WHERE username not in ( SELECT username FROM weekpicks WHERE whatweek='$totalnoOfWeek' )")

or die (mysql_error());

while ($row = mysql_fetch_array($sql_events)) {
$username = $row["username"];

(
"INSERT INTO weekpicks SET " .
"username = '". ($username). "',".
"date_create = NOW(), " .
"whatweek = '".($totalnoOfWeek) . "',".
"team = '" . addslashes($sTeam1) . "'".
'INSERT'
);

echo "<HTML>

<BODY>
<h2>Your pick of ".($sTeam1).", for week ".($totalnoOfWeek).", has been added.</h2>

<P align=left><a href=\"nopickpolicy.php\">Return to main page</a></p>
</BODY>
</HTML>";
}
?>




Answer Source

You are creating the string for insert but you are not running it.

Fixing your code it'd be:

while ($row = mysql_fetch_array($sql_events)) {
$username = $row["username"];
mysql_query("INSERT INTO weekpicks SET " . "username = '" . ($username) . "'," . "date_create = NOW(), " . "whatweek = '" . ($totalnoOfWeek) . "'," . "team = '" . addslashes($sTeam1) . "'");

//echo ...
}

Fixing the string syntax you could do this, which looks nicer. Also using mysql_real_escape_string() instead of addslashes(), since addslashes is not as safe as mysql's native function for php.

$sTeam1 = mysql_real_escape_string($sTeam1);
mysql_query("INSERT INTO weekpicks SET username = '$username', date_create = NOW(), whatweek = $totalnoOfWeek, team = '$sTeam1');

Another thing I must tell you:

Stop using mysql_*, use mysqli_* instead.

mysql_ was removed from PHP7 and deprecated after PHP 5.5

It's not as safe as mysqli_, so consider improving your code to the new model.

Follow this guide in order to change your code properly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download