How do I connect my website to a MySQL database? - php

Below is the code I have in my Sublime, but the database isn't being called.
<?php$username="root";
$password="changedpassword";$database="User";
$field1-name=$_POST['name'];
$field2-name=$_POST['password'];
$field3-name=$_POST['email'];
$field4-name=$_POST['sex'];
$field5-name=$_POST['school'];
$field6-name=$_POST['birth'];
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO create_user (name, password, email, sex, school, birth) VALUES('','$field1-name','$field2-name',
'$field3-name','$field4-name','$field5-name','$field6-name')";mysql_query($query);mysql_close();?>

Let's go through this step by step. First, here's your current code, tidied up to be readable:
<?php
$username = "root";
$password = "changedpassword";
$database = "User";
$field1_name = $_POST['name'];
$field2_name = $_POST['password'];
$field3_name = $_POST['email'];
$field4_name = $_POST['sex'];
$field5_name = $_POST['school'];
$field6_name = $_POST['birth'];
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die("Unable to select database");
$query = "
INSERT INTO
create_user
(
name,
password,
email,
sex,
school,
birth
)
VALUES
(
'',
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
";
mysql_query($query);
mysql_close();
?>
I've made only two changes (tidied the whitespace, and used _name instead of -name, as PHP variables cannot contain hyphens), but it's already a big improvement. The code is no longer an eyesore. It does not have syntax errors, and it is readable. There are still, though, a large number of problems.
First, you see that we are inserting seven values into six columns. This will be a problem. Fix that by removing the first blank value:
$query = "
INSERT INTO
create_user
(
name,
password,
email,
sex,
school,
birth
)
VALUES
(
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
";
Now we have something that might actually work. It's painfully insecure, with massive potential for SQL injection attacks, and it won't work on the latest PHP because the mysql_ functions have been removed, but it might actually kind of work somewhere. You wouldn't want to put it into production, but for test purposes, we're getting somewhere.

MySQL is deprecated since PHP 5.6 and is insecure, use PDO or MySQLi instead.
Connecting with MySQLi
<?php
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
$field1_name = $_POST['name'];
$field2_name = $_POST['password'];
$field3_name = $_POST['email'];
$field4_name = $_POST['sex'];
$field5_name = $_POST['school'];
$field6_name = $_POST['birth'];
$query = mysqli_query($connection, "INSERT INTO create_user
(name, password, email, sex, school, birth ) VALUES
(
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
");
Use this and you will be good. I hope this has helped you!

Related

What does the "Unrecognised SQL statement" mean when I am trying to use IF NOT EXISTS?

I am getting the error on line 26 as shown by my browser.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "tut";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Database connection failed: ".mysqli_connect_error());
}
if (isset($_POST['register']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$pass2=$_POST['password1'];
if(empty($username)||empty ($password)||empty($password1)){
echo "Oops! Can't leave any field blank";
}
elseif($pass!=$pass2){
echo "Passwords don't match";
}
else{
$phash = sha1(sha1($pass."salt")."salt");
$sql=IF NOT EXISTS (SELECT * FROM users WHERE username = '$user')
INSERT INTO users (id, username, password) VALUES ('', '$user', '$phash')
ELSE
RAISERROR 'Username exists, please select a different one';
$result = mysqli_query($conn, $sql);
}
}
?>
Is this not a correct way of writing the IF NOT EXISTS statement. Also when I try to execute this directly in XAMPP I get Unrecognised SQL statement error!
This is how to do it, I have test it and it works:
$sql = "
INSERT INTO users (username, password)
SELECT * FROM (SELECT '$user', '$phash') AS tmp
WHERE NOT EXISTS (
SELECT username FROM users WHERE username = '$user'
) LIMIT 1;
";
This solution is inspired from this answer.
The problem is that you can not combine PHP and MySQL statement like you did, you need to encapsulate all MySQL statements in quote ".
What comes RAISERROR, it is not MySQL function, it belongs to Microsoft.
You could easily make php if statement that checks if $sql contain valid username and return your message. That part is left to your fantasy.
XAMPP has no thing to do with the error, it just a software that provides an Apache and MySQL installation for Windows.
Note: P.S. please learn to use parameterized queries, because your
code is vulnerable to SQL injection. thanks to #BillKarwin for mentioning this.

Why doesn't my php connect to sql database code work?

/* I have set up a database in my php admin and use dreamweaver. Not sure
why it doesn't work. The $ vars are taken from the ftp site i use. Here is
the code: */
<?php
$db_host = "host";
$db_username = "user_name";
$db_pass = "password";
$db_name = "db_name";
#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 'signups' (FirstName, LastName, email,CompanyName,
JobTitle, ProductSector,ProductWebsite,ProductName,id)
VALUES ('$FirstName', '$LastName', '$email','$CompanyName', '$JobTitle',
'$ProductSector','$ProductWebsite','$ProductName','$id')";
?>
I realize this is a 'quick and easy' way to connect to MySQL - but it is extremely prone to Sql injection. A parameterized query is a more secure approach. Additionally, the 'mysql' driver should not be used the driver is deprecated and will not exist in php7. Instead, MySQLi or PDO driver(preferred) for sql is to be used. The MySQL_connect is no longer documented on the PHP website.
Even if this is a test environment, I would strongly encourage switching to a secure driver early.
As Elias Nicolas pointed out... Placing the # symbol in front of mysql_connect causes any error you are having to be 'skipped'. The error won't log, and it will make it look like there isn't a problem when there is.
Edit: This will get you close to Mysqli - should already exist in the extensions for php. You might need to enable it in the php.ini. Also, you might need single ' marks around the ?'s. i.e: ('?').
// don't forget to sub the vars!
$db_host = "host";
$db_username = "user_name";
$db_pass = "password";
$db_name = "db_name";
$link = new mysqli($db_host, $db_username, $db_pass, $db_name) or die ('Could not connect to the database server' . mysqli_connect_error());
$sql = <<<QUERY
INSERT INTO signups
(FirstName, LastName, email, CompanyName, JobTitle, ProductSector, ProductWebsite, ProductName, id)
VALUES
(?,?,?,?,?,?,?,?,?);
QUERY;
if ($stmt = $mysqli->prepare($sql))
{
$stmt->bind_param("sssssssss", $FirstName, $LastName, $email, $CompanyName, $JobTitle, $ProductSector, $ProductWebsite, $ProductName, $id);
$stmt->execute();
}
$link->close();
For your table name, and the names of the columns but not the values, you use ` instead of '. Your sql should look like this.
INSERT INTO `signups` (`FirstName`, `LastName` `email`, `CompanyName`,
`JobTitle`, `ProductSector'`,`ProductWebsite`,`ProductName`,`id`)
VALUES ('$FirstName', '$LastName', '$email','$CompanyName', '$JobTitle',
'$ProductSector','$ProductWebsite','$ProductName','$id')
Hope that helps.

PHPMyAdmin Cannot use PHP to Insert data into MySQL

I'm using MAMP Server to host a MySQL database to store some information about user accounts.
When I try to insert an entry using the code given by PHPMyAdmin, it won't insert it. Could somebody please tell me what's wrong with my code?
<?php
$username = "username";
$password = "*******";
$hostname = "localhost:8889";
$inputUsername = $_POST["username"];
$inputPassword = $_POST["password"];
$confirmPassword = $_POST["confirmPassword"];
if ($inputPassword != $confirmPassword) {
die("Your two password entries are not the same!");
}
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$sql = mysql_select_db("billet",$dbhandle)
or die("Could not select database");
$sql = mysql_query("INSERT INTO `billet` (`username`, `password' VALUES ('$inputUsername', '$inputPassword')");
echo "Inserted values! <a href='index.html'>Go</a>";
mysql_close($dbhandle);
?>
You need to query the database to insert the data that you want, currently you are just connecting to the database and then closing.
You will need to do something like this (depending on your MySQL table) :
$result = mysql_query("INSERT INTO `billet` (`username`, `password`) VALUES ('$inputUsername', '$inputPassword')");
You should also think about switching to PDO as mysql_ functions are deprecated.

migrating mysql to mysqli in ajax environment

First i would like to say thank you for letting me ask questions again. I know my previous question was a bit low level of knowledge. Today, I would like to ask if the principle of converting mysql to mysqli in ajax is same with html. Suppose this is my Connect.php
<?php
$host = "localhost";
$dbusername = "root";
$dbpassword = "765632";
$dbname = "student";
$link_id = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link_id));
?>
and my ajax.php is
<?php
//Connect to MySQL Server
include 'Connect.php';
mysql_connect($host, $dbusername, $dbpassword);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Escape User Input to help prevent SQL Injection
$first_name = mysql_real_escape_string(trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysql_query($query) or die(mysql_error());
//Generate the output
$searchResults = '';
if(!mysql_num_rows($result))
What are the changes should i made to convert it to mysqli without changing its logical scheme.
Did you mean this?
$link_id = mysqli_connect($host, $dbusername, $dbpassword);
//Select Database
mysqli_select_db($link_id, $dbname) or die(mysqli_error($link_id));
// Escape User Input to help prevent SQL Injection
$first_name = mysqli_real_escape_string($link_id, trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysqli_query($link_id, $query) or die(mysqli_error($link_id));
//Generate the output
$searchResults = '';
if(!mysqli_num_rows($result))

Simple table query syntax error?

I hope someone here can help me see where this error is coming from.
I have a form with two fields: email and password. The form's action takes it to a php page that is supposed to
start a session
connect to a database via mysql
run a query and select a row in a table where the email field is similar to the email
submitted in the form.
At this stage it is incomplete, I only echo some of the fields at the end of the script to
see if it works.
I tested it and there was an unexpected end error that came up right at the last line; a bracket I left out. So I though there would be no other errors, but then when I tested it again I got this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#gmail.com' at line 6
#gmail.com is the last bit of the email I submitted.
Here is the code of the php (action) page:
<?php
session_start();
$_SESSION['sessionemail'] = $_POST['email'];
$_SESSION['sessionpassword'] = $_POST['password'];
$_SESSION['authuser'] = 0;
$dbhost = 'somewhere.com';
$dbuser = 'user';
$dbpass = 'pw';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'medreunten_db1';
mysql_select_db($dbname) or die(mysql_error($conn));
$query = 'SELECT
name, smacker, surname, sex, age, nationality, email
FROM
employee
WHERE
email = ' . $_POST['email'];
$result = mysql_query($query, $conn) or die (mysql_error($conn));
extract(mysql_fetch_assoc($result));
while ($row = mysql_fetch_array($result)) {
echo $row['name'];
echo $row['surname'];
echo $row['age'];
}
?>
I tried removed the first 5 lines and I still got the same error.
Somehow, when the php gets parsed, the browser reads the content of the email variable as if it is part of my php code. At least that's what I thought because the error I receive states that there is a problem with the syntax near "#gmail.com".
I hope someone can give me a clue!
You have an SQL injection, always apply mysql_real_escape_string() to any user-submitted or otherwise potentially tampered-with data before sending to a MySQL database.
Note the ' around the email variable.
$email = mysql_real_escape_string($_POST['email']);
$query = "
SELECT name, smacker, surname, sex, age, nationality, email
FROM employee
WHERE email = '$email'
";
<?php
session_start();
$_SESSION['sessionemail'] = $_POST['email'];
$_SESSION['sessionpassword'] = $_POST['password'];
$_SESSION['authuser'] = 0;
$dbhost = 'dedi147.cpt2.host-h.net';
$dbuser = 'medreunten_1';
$dbpass = 'AGqrVrs8';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'medreunten_db1';
mysql_select_db($dbname) or die(mysql_error($conn));
$query = "SELECT name, smacker, surname, sex, age, nationality, email FROM employee WHERE email = '" . $_POST['email']."'";
$result = mysql_query($query, $conn) or die (mysql_error($conn));
extract(mysql_fetch_assoc($result));
while ($row = mysql_fetch_array($result)) {
echo $row['name'];
echo $row['surname'];
echo $row['age'];
}
?>
try this, should work

Categories