Blade Blade - 18 days ago 8
iOS Question

PHP Database only inputs the last value

I have almost no experience with PHP and right now I'm stuck at the total beginning, which is really frustrating. I have a code, which seems to work. From my app I can input values and put them in my PHP database. Thing is that he only inputs the very last value from my PHP code. So the app aside: If I only use the PHP code to input something in my database he always only takes the last value. Here is my code:

<?php
$DB_HostName = "localhost";
$DB_Name = "xxx";
$DB_User = "xxx";
$DB_Pass = "xxx";
$DB_Table = "contacts";

if (isset ($_GET["name"]))
$name = $_GET["name"];
else
$name = "Blade";

if (isset ($_GET["lastname"]))
$lastname = $_GET["lastname"];
else
$lastname = "Xcoder";

if (isset ($_GET["number"]))
$number = $_GET["number"];
else
$number = "111";

$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());

$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql = "insert into $DB_Table (Lastname) values('$lastname');";
$sql = "insert into $DB_Table (Number) values('$number');";

$res = mysql_query($sql,$con) or die(mysql_error());

mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>


To clarify: If I only have the firstname value, he inputs it in the right place (firstname). If I have a firstname and lastname value, he only inputs the lastname value, but not the firstname value (still at the right place lastname). And the same for number. If I have a firstname, lastname and a number, he only puts the number in the right place but not the other values. In addition I can only do it once. If I want to enter another contact he always says (Duplicate entry 'myentry' for key 'PRIMARY').

Answer

You overwrite your query, 2 ways to solve. Either 3 different variables, or 1 variable with 3 queries in it. I would prefer the 2nd option

$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql .= "insert into $DB_Table (Lastname) values('$lastname');";
$sql .= "insert into $DB_Table (Number) values('$number');";

$res = mysql_query($sql,$con) or die(mysql_error());

Or if it can be 1 row in the table, as it is the same table anyways:

$sql = "insert into $DB_Table (Firtname,Lastname,Number) values('$name','$lastname','$number');";
$res = mysql_query($sql,$con) or die(mysql_error());