1

Trying to insert into database by typing the value in the url, but having difficulties to insert into the database:

Here is the URL:

http://student.cs.hioa.no/~s180343/updatedb.php?verdi=22

Here is the code:

<?php

$dbhost = "MYSQL-SERVER";
$dbuser = "USERNAME";
$dbpass = "";
$verdi = $_GET['verdi'];

$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = "INSERT INTO test ('id') VALUES (`$verdi`)";

mysql_select_db('s180350');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
user3270211
  • 915
  • 4
  • 20
  • 42
  • what's the error you're getting? What type of column is ID? It looks like you're trying to send a string, but the value is an integer. – durbnpoisn Apr 03 '14 at 13:15

3 Answers3

4

Use quotes around your string values. Use ticks around your column names. You have it backwards:

$sql = "INSERT INTO test ('id') VALUES (`$verdi`)";

shjould be

$sql = "INSERT INTO test (`id`) VALUES ('$verdi')";

FYI, you are wide open to SQL injections

Community
  • 1
  • 1
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

You are doing reverse i.e. adding '' for column name and `` for the value

$sql = "INSERT INTO test ('id') VALUES (`$verdi`)";

should be

$sql = "INSERT INTO test (`id`) VALUES ('$verdi')";

Start using prepare statement or at least below after conn is defined.

$verdi = mysql_real_escape_string($verdi);
Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63
0

please dont forget to secure all user input into your sql querys. see SQL injection wiki

The problem with your code is wrong use on quotes. See edited code:

$conn = mysql_connect("MYSQL-SERVER", "USERNAME", $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('s180350');

$retval = mysql_query( "INSERT INTO test ('id') VALUES ('".mysql_real_escape_string($_GET['verdi'])"')", $conn );

if(! $retval )
{
  die('Could not enter data: ' . mysql_error());
}

echo "Entered data successfully\n";

PS: Dont use up resources by setting variables you dont need.

Adam Fischer
  • 1,075
  • 11
  • 23