Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting data into mysql table

Tags:

php

mysql

I have just installed xampp but I'm having problem inserting data into MySQL table. The data I inserted does not appear in phpmyadmin. I am not sure what is the problem.

Any help will be gratefully appreciated, here is my code:

<html>
<head>
<title>Test</title>
<body>
<form action="test.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit"name="submit" value="submit"/>
</form>

<?php 
$host ="localhost";
$username = "***";
$password = "***";
$database = "***";
$table ="persons";
$con = mysql_connect("localhost","***","***");
if (!$con)
{
 die('Could not connect: ' . mysql_error());
}
 mysql_select_db("bucksbug_mesovot", $con);

 $sql="INSERT INTO persons (firstname, lastname, age)
 VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

  if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
   echo "Data inserted";

   mysql_close($con);

  ?>
  </body>
  </html>
like image 616
Rick Menss Avatar asked Aug 02 '26 04:08

Rick Menss


1 Answers

Although you should really switch to PDO / mysqli and prepared statements with bound parameters to avoid sql injection and breaking sql statements if your variables contain quotation marks, you will probably run into problems with PDO / mysqli as well: Your password (change it!) contains a $.

See the following example on codepad:

<?php

function test($var)
{
  echo $var;
}

$test_var = "test$string";

test($test_var);

Output:

test

You will not be able to connect successfully to the database as your password will never be correct.

Change:

"=c(p$zTTH2Jm"

to:

'=c(p$zTTH2Jm'
like image 149
jeroen Avatar answered Aug 04 '26 19:08

jeroen