Connecting and inserting data into mysql table using php - 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();
?>

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);
?>

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.

Related

How do i connect to mysql server? and what do i use for the parameters?

Im trying to create a login for my website and i need to store emails, usernames, passwords, ect in a database i have created already using phpMyAdmin. I have gone through article after article and nothing seems to be working. i have my connect.php like this:
<?
$hostname = "localhost";
$username = "username";
$password = "password";
$databaseName = "_mySiteUserDataBase";
mysql_connect($hostname, $username, $password) or die("Cannot connect to server");
mysql_select_db($databaseName) or die("Cannot select database");
?>
And my main.php like this:
<?
include("connect.php");
$tableName = "myUsers";
$sql = "SELECT * FROM $tableName";
$result = mysql_query($sql);
?>
And i have created a simple form in my html like this:
<html>
<head></head>
<body>
<form>
<input type = "submit" action = "main.php" method = "post" value = "Login">
</form>
</body>
</html>
After submitting the form it says cannot connect to server. I am new to php and mysql and i dont understand what each parameter in the mysql_connect is, and i dont know what they do therefore im not sure what im supposed to enter in but everyone i keep reading about seems to be inputing random values? I could use a brief explanation on that, because i am stuck at connecting and cant even get past this point sadly enough. Also i have been reading that mysql_connect is deprecated and isnt valid anymore but i dont understand what im supposed to use as an alternative. I know its mysqli but thats it and im unclear of the syntax.
mysqli:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo "start<br/>";
try {
$mysqli= new mysqli('localhost', 'myusername', 'mypassword', 'dbname');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
echo "I am connected and feel happy.<br/>";
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
?>
If you need to know how to create users, what the heck the hostname is, how to grant access (often useful after the connect :>), just ask.
Try this code in 'connect.php'
<?php
error_reporting(0);
$con=mysql_connect('localhost','root','');// here 'root' is your username and "" is password
if(!$con)
{
echo 'not connect';die;
}
mysql_select_db('dbname',$con);// here 'dbname' is your database name
?>
And also try following code to include sql connection in your other php file(main.php)
<?php
include 'connect.php';
$sql = "SELECT * FROM myUsers";
$result=mysql_query($sql);
?>
Let me convert it to mysqli for you and maybe that will fix the problem. Also, make sure the username, password, and database name are correct.
Try this code. At very least, it will provide a better error message for debugging.
<?
$hostname = "localhost";
$username = "username";
$password = "password";
$databaseName = "_mySiteUserDataBase";
$con = mysqli_connect($hostname, $username, $password, $databaseName) or die(mysqli_error($con));
?>
Main.php
<?
include("connect.php");
$tableName = "myUsers";
$sql = "SELECT * FROM $tableName";
$result = mysqli_query($con,$sql);
?>

Cannot add values to table using mysql and php

I have a problem with my code. I'm trying to add new post to the table events. I'm confused because I have used this code in other place on the same website (but it was using mysqli_query to register new user). mysqql_error returns "No database selected"
This is the code:
<?php
$add_title = $_POST['add_title'];
$add_happen = $_POST['add_happen'];
$add_created = date('Y-m-d');
$add_content = $_POST['add_content'];
$add_author = $_POST['add_author'];
//connect to
//localhost
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_dbname = "zhp2";
$db_con = mysql_connect($db_host, $db_username, $db_password, $db_dbname);
$query = "
INSERT INTO events ( title, happen, created, content, author )
VALUES ( '$add_title', '$add_happen', '$add_created', '$add_content', '$add_author') )
";
$retval = mysql_query($query, $db_con);
if(! $retval ){
die('Could not enter data: ' . mysql_error());
}
else{
echo "Entered data successfully\n";
}
mysql_close($db_con);
//header('Location: ../../index.php?link=events');?>
I've tried to fix it using trial and error method playing with different combinations both mysql_query and mysqli_query
You are confusing mysql_connect and mysqli_connect functions in the way you pass those parameters. In your example:
$db_con = mysql_connect($db_host, $db_username, $db_password, $db_dbname);
you are passing a fourth parameter which is the database name but that wont work as you should only pass the three first (host,username,password) and then call mysql_select_db():
$db_con = mysql_connect($db_host, $db_username, $db_password);
mysql_select_db( $db_dbname, $db_con );
In mysqli which is the BETTER way of doing it since mysql_ functions are very vulnerable and being deprecated from php you could pass four elements like here:
$db_con = mysqli_connect($db_host,$db_username, $db_password, $db_dbname) or die("Error " . mysqli_error($link));
which is close to what you are trying to do, but in a correct mysqli_ way.
Well then, you need to select the database! ;) The fourth parameter of mysql_connect() is not the database name. You need to do this separate of connecting to the MySQL server.
Using mysql_select_db() function:
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_dbname = "zhp2";
$db_con = mysql_connect($db_host, $db_username, $db_password );
mysql_select_db( $db_dbname, $db_con );
And of course all the obligatory warnings about SQL injection, sanitizing your data, deprecation of mysql_* functions.
You need to select which database to connect to using the mysql_select_db function:
// make $db_dbname the current db
$db_selected = mysql_select_db($db_dbname, $db_con);
if (!$db_selected) {
die ("Can't use $db_dbname : " . mysql_error());
}
See the PHP manual for more info: http://php.net/manual/en/function.mysql-select-db.php

Trying to connect database MySQL from PHP (Not Successful)

I'm following a tutorial on the net on PHP and MySQL.
I'm using Linux. I'm trying to establish a connection to a database but it is not working.
I have my database:
create database test;
create table user(name text, pass text);
insert into user values('john', '123');
and then my php:
<?php
$_host = "localhost";
$_dbuser = "root"
$_dbpass = "";
$_dbname = "test";
#mysql_connect("$_host", "$_dbuser", "$_dbpass") or die("could not connect");
#mysql_select_db("$_dbname") or die("no database");
echo "connection stablished";
?>
And the output of my file is just a blank tab on the browser.
What should I do to solve this? What am I doing wrong?
Thank you in advance. I'm very new to web programming.
$_host = "localhost";
$_dbuser = "root"
$_dbpass = "";
$_dbname = "test";
$link = mysqli_connect($_host, $_dbuser, $_dbpass, $_dbname);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo "connection stablished";
Now...
Use mysqli_* functions as mysql_* are deprecated.
You will need $link variable later for queries.
As you're newbie read this: How can I prevent SQL injection in PHP?
Prepared statements FTW! Remember!

get current user and save to mysql

Based on suggestions and a better understanding of what I need I have changed my question:
My site is protected with .htaccess. Im trying to get the current user and a few other variables and save them to a MySQL database. Everything works except the current user part.
Heres my code:
<?php
$_SERVER["PHP_AUTH_USER"] = "rep";
$hostname = "hostname";
$username = "username";
$dbname = "dbname";
$password = "password";
$usertable = "usageStats";
$yourfield = "your_field";
$con = mysql_connect($hostname, $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
$sql="INSERT INTO usageStats (Bid, PRid, User)
VALUES
('$_POST[BID]','$_POST[branding]','$_POST[rep]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
I know that the below are both wrong. How should the current user be passed instead of $_POST[rep]?
Wong:
$_SERVER["PHP_AUTH_USER"] = "rep";
and
'$_POST[rep]'
If you are using Basic Authentication you do not need to send the username explicitly. The browser will send it and you can access it using the PHP_AUTH_USER server variable:
$_SERVER['PHP_AUTH_USER']
Also checkout the HTTP Authentication article in the documentation.

Unable to connect to MySQL database but able to connect to server

I am just using a basic code to connect to my Mysql database. I am able to connect to my server but not database. using sqlyog:
<?php
$username = "root";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username) or die("Unable to connect to MySQL");
$selected = mysql_select_db("project",$dbhandle) or die("Could not select project");
$sql = "SELECT image_small FROM images";
mysql_query($sql,$selected);
while($row=extract_row($sql))
{
echo $row['image_small'];
}
?>
where is password of database? mysql_connect should be used as:
mysql_connect("localhost", "mysql_user", "mysql_password");
otherwise it will be the default password that will be used
There are so many things wrong here.
1. Your have a blank password for the root user in your database.
2. You're using mysql_* which everybody know is subject to many hasck.
3. You're trying to "extract" a row from your SQL query.
Use PDO:
$DB = new PDO("mysql:host=localhost;dbname=project","root","root_password");
$sql = "SELECT image_small FROM images";
foreach($DB->query($sql, PDO::FETCH_ASSOC) as $row) {
echo $row['image_small'];
}
try to connect using the following statement
$selected = mysql_select_db("project");
// i think you have to provide password in here mysql_connect($hostname, $username,$password);
since it is localhost and user is root you could use like this
mysql_connect($hostname, $username,"");

Categories