Insert array to mysql database php
Posted
by
ganjan
on Stack Overflow
See other posts from Stack Overflow
or by ganjan
Published on 2010-12-31T03:27:24Z
Indexed on
2010/12/31
3:54 UTC
Read the original article
Hit count: 283
Hi. I want to add an array to my db. I have set up a function that checks if a value in the db (ex. health
and money
) has changed. If the value is diffrent from the original I add the new value to the $db
array. Like this $db['money'] = $money_input + $money_db;
.
function modify_user_info($conn, $money_input, $health_input){
(...)
if ($result = $conn->query($query)) {
while ($user = $result->fetch_assoc()) {
$money_db = $user["money"];
$health_db = $user["health"];
}
$result->close();
//lag array til db med kolonnene som skal fylles ut som keys i array
if ($user["money"] != $money_input){
$db['money'] = $money_input + $money_db;
//0 - 20
if (!preg_match("/^[[0-9]{0,20}$/i", $db['money'])){
echo "error";
return false;
}
}
if ($user["health"] != $health_input){
$db['health'] = $health_input + $health_db;
//0 - 4
if (!preg_match("/^[[0-9]{0,4}$/i", $db['health'])){
echo "error";
return false;
}
if (($db['health'] < 1) or ($db['health'] > 1000))
{
echo "error";
return false;
}
}
The keys in $db
represent colums in my database. Now I want to make a function that takes the keys in the array $db
and insert them in the db. Something like this ?
$query = "INSERT INTO `main_log` ( `id` , ";
foreach(range(0, x) as $num) {
$query .= array_key.", ";
}
$query = substr($query, 0, -3);
$query .= " VALUES ('', ";
foreach(range(0, x) as $num) {
$query .= array_value.", ";
}
$query = substr($query, 0, -3);
$query .= ")";
© Stack Overflow or respective owner