Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting and inserting data into mysql table using php

Tags:

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();
?> 
like image 977
Rick Menss Avatar asked Mar 15 '26 05:03

Rick Menss


1 Answers

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);
?>
like image 120
Thomas Vincent Blomberg Avatar answered Mar 17 '26 00:03

Thomas Vincent Blomberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!