user3427435
user3427435

Reputation: 11

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

Upvotes: 0

Views: 132

Answers (2)

Kyle Wiering
Kyle Wiering

Reputation: 474

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

Upvotes: 1

user3696866
user3696866

Reputation:

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.

Upvotes: 0

Related Questions