Rick Menss
Rick Menss

Reputation: 107

Connecting and inserting data into mysql table using php

I am a PHP newbie and have been trying for sometime now to connect to MySQL database using PHP so I can insert data into a table I have created but I am unable to do this.

I suspect the problem is coming from my PHP .ini file,but that's just me.
Would be grateful if anyone can help me configure my PHP .ini file so I can connect to MySQL and insert data into my table. Here is my PHP script in case you are wondering.
Any help will be gratefully appreciated.

<?php

$host ="localhost";
$username = "username";
$password = "password";
$database = "database1";
$table ="users";
$con = mysql_connect("localhost","username","password");

if (!$con)
{
die('Could not connect:'.mysql_error());
}
mysql_select_db("database1",$con);


$mysql = "INSERT INTO $table(name,email,password)
VALUES('$_POST[name]','$_POST[email]','$_POST[password]";

if(mysql_query($mysql)) die(mysql_error()); 
echo"Data inserted";
mysql_close();
?> 

Upvotes: 3

Views: 11898

Answers (2)

I revised some of your code this should work. You had a bunch of little errors. I suggest you read a couple tutorials on just connecting and the syntax of php.

Here is some really basic examples of connecting to a database: http://www.w3schools.com/php/php_mysql_connect.asp

Also once you get the hang of it here is a really good tutorial to teach you the OOP way of creating a class for a database: http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/

As far as I see this is not an ini issue. I hope this helps.

<?php
//Set your variables
$host = "127.0.0.1";
$username = "username";
$password = "password";
$database = "database1";
$table = "users";

//Make your connection to database
$con = mysql_connect($host,$username,$password);

//Check your connection
if (!$con) {
die("Could not connect: " . mysql_error());
}

//Select your database
$db_selected = mysql_select_db($database, $con);

//Check to make sure the database is there
if (!$db_selected) {
    die ('Can\'t use the db : ' . mysql_error());
}

//Run query
$result = mysql_query("INSERT INTO $table(name,email,password) VALUES('$_POST[name]','$_POST[email]','$_POST[password]'");

//Check Query
if (!$result) {
die("lid query: " . mysql_error());
}
echo "Data inserted";

mysql_close($con);
?>

Upvotes: 2

Greeso
Greeso

Reputation: 8229

First, why do you have <br/> in your PHP statements? Remove all those. Also, you have to use PDO or mysqli_ instead of the mysql_ library, mysql_ is deprecated.

Upvotes: 0

Related Questions