trying to get PHP and database to work together - php

I'm trying to teach myself how to work with php and mysql. For practice, I made a simple test website that takes a username and a password, and a database using phpmyadmin and mysql. I was able to create a successful connection to my DB, but now I'm trying to take the data from the form on my website and insert it into a table called 'account'. Account has three fields: 'username', 'password', and 'userID'(primary key). user ID is supposed to auto increment, so that field doesn't require input data. I wrote code that I thought would collect the username and password and add it as a new record in the account table, but I get an error message:
Internal Server Error
The server encountered an internal error or misconfiguration and was
unable to complete your request.
Additionally, a 404 Not Found error was encountered while trying to
use an ErrorDocument to handle the request.
Below I've included my code. I've never worked with PHP before or made a DB before so it's possible I've made very obvious mistakes.
php_script
<?PHP
$db_host = "stevie.heliohost.org";
$db_username = "secret";
$db_pass = "secret";
$db_name = "secret";
$connection = #mysql_connect ("$db_host","$db_username", "$db_pass")
or die ("could not connect to mySQL");
#mysql_select_db("$db_name") or die ("No database");
$sql="INSERT INTO account(username, password)
VALUES('$_POST[user]','$_POST[password]')";
if (!mysql_query($sql,$connection ))
{die('Error: ' . mysql_error());}
echo "1 record added";
mysql_close($con);
?>
HTML FORM
<form name="LOGIN" action="php_script.php" method="post">
Username: <input id="username" type="text" name="user">
password: <input id="password" type="text" name="password">
<input id="submit" type="submit" value="Submit">
</form>

try this out
$db_host = 'stevie.heliohost.org';
$db_username = "secret";
$db_pass = "secret";
$db_name = "secret";
$connection = mysql_connect($db_host,$db_username, $db_pass)
or die ("could not connect to mySQL");
mysql_select_db($db_name) or die ("No database");
$sql="INSERT INTO account(username, password)
VALUES('".$_POST[user]."','".$_POST[password]."')";
if (!mysql_query($sql,$connection ))
{die('Error: ' . mysql_error());}
echo "1 record added";
mysql_close($con);
OBS: u should use mysqli or PDO , your code is easy for sql injections

If you are teaching yourself PHP, the First thing you should do is learn PDO. Because, the way you are using mysql, you are leaving your site open for SQL-Injection type of hacking, which anyone can do. Since you are directly submitting the value of $_POST['']; in your database. Start learning PDO today, it is much more secure. You can find the a good tutorial here: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Additionally, Check this code as I have modified it a little bit. and host name, is almost always localhost
<?PHP
$db_host = "localhost";
$db_username = "secret";
$db_pass = "secret";
$db_name = "secret";
$connection = mysql_connect ("$db_host","$db_username", "$db_pass")
or die ("could not connect to mySQL");
mysql_select_db("$db_name") or die ("No database");
$sql="INSERT INTO account(username, password)
VALUES('$_POST[user]','$_POST[password]')";
if (!mysql_query($sql,$connection ))
{die('Error: ' . mysql_error());}
echo "1 record added";
mysql_close($con);
?>

First of all you shouldn't be using mysql_ functions because they are being deprecated. Try to use PDO or likes.
second try this
$db_host = 'stevie.heliohost.org';
$db_username = "secret";
$db_pass = "secret";
$db_name = "secret";
$connection = mysql_connect($db_host,$db_username, $db_pass)
or die ("could not connect to mySQL");
mysql_select_db($db_name) or die ("No database");
$sql="INSERT INTO account(username, password)
VALUES('".mysql_escape_string($_POST[user])."','".mysql_escape_string($_POST[password])."')";
if (!mysql_query($sql,$connection ))
{die('Error: ' . mysql_error());}
echo "1 record added";
mysql_close($con);
you should be escaping your values in your query too so the its not up for SQL injection
I am not up for for using mysql_escape_string either you should be using atleast mysqli
So go through a good tutorial to learn more about it

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

Uploading my site from XAMPP to Apache public host

This is a general question.
I`ve compliled site in xampp and it is properly running, because lack of experience I used mysql functions rather than the improved mysqli.
Uploading my site on ecowebhost the site does not work, I have changed paths so that, apparently, no connection error happens. but still I cannot interact with my database.
From the site seems that php4 version are supported, am I required to recompile my web site because of that?
this is a little sample code of what I am trying to do...
<?php
function connectto($tablename){
$db_host = "xxx";
$db_username = "xxx";
$db_pass = "xxx";
$link = mysqli_connect("$db_host","$db_username","$db_pass","$tablename") or die ("Could not connect to MySQL");
// #mysql_connect("$db_host","$db_username","$db_pass") or die ("Could not connect to MySQL");
// #mysql_select_db("$tablename") or die ("No database");
}
?>
Thanks
if I run the following
<?php
// connection to database
// include_once "connectto.php";
// connectto('test');
$tablename = "test";
$db_host = "xxx";
$db_username = "xxx";
$db_pass = "xxx";
$link =mysqli_connect("$db_host","$db_username","$db_pass","$tablename")
or die ("Could not connect to MySQL");
if (mysqli_connect_errno()) { die("Failed to connect to MySQL: " . mysqli_connect_error());}
else { echo " <br /><br />connection established! <br />";}
?>
the only error message that comes out is
Could not connect to MySQL
update....
I got a bit of my code working but I am struggling with finding a way to insert some values in the database...
<?php
$db_host = "xxxx";
$db_username = "xxxx";
$db_pass = "xxxx";
// $link = mysqli_connect("$db_host","$db_username","$db_pass","cl45-members-7b5") or die ("Could not connect to MySQL");
#mysql_connect("$db_host","$db_username","$db_pass") or die ("Could not connect to MySQL");
#mysql_select_db("cl45-members-7b5") or die ("No database");
$sql ="INSERT INTO members (username, email, gps_lat, gps_long, password, skill, skill_rate,) VALUES ('a','2','3','4','5','5','6')";
print '<br /><br /> Great! now you are registered; now update your profile <br />';
mysql_query ("$sql");
print '<br /><br />tutto ok;<br /><br />';
?>
Is there anything that strikes being wrong? I got no error like database not found...
Your question is confusing me slightly but you can connect using MySQLi using the following:
$link = new mysqli($db_host,$db_username,$db_pass,$tablename);
In your code you have
or die ("Could not connect to MySQL");
Which says if you can not connect for whatever reason just print out this. You're not going to get any more information because you need to include $conn->connect_error e.g.
if ($link->connect_error) {die ("Failed: " . $link->connect_error);}
You should end up with something like
$tablename = "test";
$db_host = "xxx";
$db_username = "xxx";
$db_pass = "xxx";
$link = new mysqli($db_host,$db_username,$db_pass,$tablename);
if ($link->connect_error) {
die ("Failed: " . $link->connect_error);
} else {
echo " <br /><br />connection established! <br />";
}
After some wondering around and splitting the problem in little subtasks, i believe I managed to understand that that little stupid extra comma in the list was preventig me to run the program, I copy pasted a syntax shared on-line and now everything seems to work...
outcome:
- check the spelling
- Isolate problems one by one...

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

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

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