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

/* 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.

Related

Inserting variables in database in php + mysql

I'm totally PHP beginner, and I'm trying to insert variables in a database in PHP and MySQL.
This is my code:
$link = mysql_connect('localhost','','','onlynews') or die('Cannot connect to the DB');
mysql_select_db('TEST',$link) or die('Cannot select the DB');
$strSQL = "INSERT INTO news(id, title,photo,url,source, at) VALUES('$x','$title','$url','$imgurl ','$source','$at')";
mysql_query($strSQL) or die(mysql_error());
The problem is it is doing: NOTHING! No Entries at all, Nothing changes in the database.
-How can I fix this?
-Do I have to write codes to prevent SQL Injection, even if the variables are coming from an API, not from users?
You have to execute your query using $conn->query($sql);.
However, to avoid SQL injections you should definitely use prepared statements or at least $conn->real_escape_string() to escape the values in your SQL statement.
For example, this is your code using prepared statements:
$servername = "localhost";
$username = "";
$password = "";
$dbname = "onlynews";
$tableName = "news";
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO news (id, title, photo, url, source, at)
VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss', $thetitle, $urlToImage, $theurl, $thesource, $thetime);
$stmt->execute();
$stmt->close();
You should also add some error checking, since $conn->prepare() and $stmt->execute() may fail (and return false). Of course, establishing the connection to the database during the construction of $conn could also fail, which can be checked using $conn->connect_error.

How do I connect my website to a MySQL database?

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!

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.

Can't connect to database in php

I have a database running on my server with phpmyadmin but I can't connect with it. Here is an example:
$user_name = "xxxxx";
$password = "xxxxx";
$database = "xxxxx";
$host = "db.xxxx.nl";
$db_handle = mysql_connect($host, $user_name, $password);
$db_found = mysql_select_db($database);
But this doesn't seem to work. If I try to insert some values into a table it still stays empty.
$sql = "INSERT INTO tbl_forum
(
title,
name,
content,
lastname,
post_image
)
VALUES
(
'{$_POST['contactsubject']}',
'{$_POST['contactname']}',
'{$_POST['contactmessage']}',
'{$_POST['contactlastname']}',
'{$_FILES["contactBrowse"]["name"]}'
)";
Am I doing something wrong?
I'm going to completely rewrite your code. As you are clearly new to databases within PHP, there is absolutely no reason not to use the new mysqli API.
Your connection should look something like this;
$mysqli = new mysqli($host,$user_name,$password,$database);
if ($mysqli->connect_errno) echo "Failed to connect to MySQL: " . $mysqli->connect_error;
This will create a new database object called $mysqli (or you can call it what you like, such as $db).
You can then prepare your SQL statement and execute it. In the code below, we have 5 parameters that are represented in the SQL as ?, and then we bind the variables to those 5 parameters. The first argument in bind_param tells the API the 5 parameters are 5 strings (hence s x5). For integers, use i;
if($query = $mysqli->prepare("INSERT INTO tbl_forum (title,name,content,lastname,post_image) VALUES (?,?,?,?,?)")) {
$query->bind_param('sssss',$_POST['contactsubject'],$_POST['contactname'],$_POST['contactmessage'],$_POST['contactlastname'],$_FILES["contactBrowse"]["name"]);
$query->execute();
}
else {
echo "Could not prepare SQL: " . $mysqli->error;
}
Assuming all your connection information is correct, this will insert your information into the database as required.
Hope this helps.
I think the last value '{$_FILES["contactBrowse"]["name"]}' has some problem. Try this and get the sql after preparing(echo $sql;) to debug by your self.
$file_name = $_FILES["contactBrowse"]["name"];
$sql = "INSERT INTO tbl_forum
(
title,
name,
content,
lastname,
post_image
)
VALUES
(
'{$_POST['contactsubject']}',
'{$_POST['contactname']}',
'{$_POST['contactmessage']}',
'{$_POST['contactlastname']}',
'{$file_name}'
)";

MySQL query returning an error

This returns a MySQL error:
<?php
$name = $_POST['inputName2'];
$email = $_POST['inputEmail2'];
$instruments = $_POST['instruments'];
$city = $_POST['inputCity'];
$country = $_POST['inputCountry'];
$distance = $_POST['distance'];
// ^^ These all echo properly ^^
// CONNECT TO DB
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO depfinder (name, email, instrument1, instrument2, instrument3, instrument4, instrument5, city, country, max_distance) VALUES ($name, $email, $instruments[0], $instruments[1], $instruments[2], $instruments[3], $instruments[4], $city, $country, $max_distance)";
$result = mysqli_query($con, $query) or die(mysqli_error($con)); // script fails here
if (!$result)
{
echo "There was a problem with the signup process. Please try again later.";
}
else
{
echo "Success";
}
}
?>
N.B. I'm not sure whether it's relevant, but the user may not choose five instruments so some $instrument[] array values may be empty.
Bonus question: is my script secure enough or is there more I could do?
You need quotes around the string values in the query:
$query = "INSERT INTO depfinder
(name, email, instrument1, instrument2, instrument3, instrument4, instrument5, city, country, max_distance)
VALUES ('$name', '$email', '$instruments[0]', '$instruments[1]', '$instruments[2]',
'$instruments[3]', '$instruments[4]',
'$city', '$country', $distance)";
To answer your bonus question, your script is not secure at all, it is susceptible to SQL injection, and will also get a syntax error if any of the values contain apostrophes. You should use a prepared query with parameters rather than string substitution. Or if you use substitution, you should use mysqli_real_escape_string to protect against injection and syntax errors.
It looks like the lack of single quotes around the variables in your query seems to have been the initial issue. So that can be considered a quick fix.
But I went ahead and refactored your code to streamline it a bit as well as provide some basic validation.
Additions of note include using a $post_array to roll through your $_POST values and do basic value checking with isset & !empty. Just a side note, but in your original script—and in this cleanup—you are setting a $distance string but then you are not actually using that in this code. Does it show up later? Realted but what is $max_distance? Could you have mixed up $distance with $max_distance? Fair typo, but just something I noticed.
Also, another option to get away from the single quotes is to use mysqli_stmt_bind_param which I have set here as mysqli_free_result & mysqli_close to neatly end the MySQL process.
// Set a '$_POST' array and roll through each value.
$post_array = array('inputName2', 'inputEmail2', 'instruments', 'inputCity', 'inputCountry', 'distance');
foreach ($post_array as $post_key => $post_value) {
$$post_value = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// CONNECT TO DB
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
// Set the connection or die returning an error.
$con = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die(mysqli_connect_error());
// Set the query.
$query = "INSERT INTO depfinder (name, email, instrument1, instrument2, instrument3, instrument4, instrument5, city, country, max_distance)"
. " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
;
// Bind the params.
mysqli_stmt_bind_param($query, 'ssssssssss', $inputName2, $inputEmail2, $instruments[0], $instruments[1], $instruments[2], $instruments[3], $instruments[4], $city, $country, $max_distance);
// Run the query.
$result = mysqli_query($con, $query) or die(mysqli_error());
// Check if the result is returned & echo a message based on that.
if (!$result) {
echo "There was a problem with the signup process. Please try again later.";
}
else {
echo "Success";
}
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);

Categories