Monday 3 September 2018

Add to a SQL database from PHP Script. No errors and seems to succeed but does not

Currently working with a php script and a sql database. Everything seems like it's working okay and even when echoing the username at the end it seems to be successful. When looking further into the insertion in the database the row was not inserted. There is no error message and the insert statement reflects the columns exactly... Any ideas?

<?php
$db_name = "animator"; // Database name
$link = mysql_connect('localhost', 'root', 'admin');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

mysql_select_db($db_name) or die("Could not connect to Database" .mysql_error());

$username  = $_POST['fname'];
$passwords = $_POST['pass'];
$email     = $_POST['email'];

mysql_query($link,"INSERT INTO 'account'('username', 'passwords', 'email') VALUES
($username , $passwords , $email)");

mysql_close($link);
?>

***UPDATE**** Thank you so much for everyones response. I was finally able to get it working with another technique I found.
<?php
error_reporting(E_ALL);
ini_set('display_errors',"On");
$db_name = "animator"; // Database name
$link = mysql_connect('localhost', 'root', 'admin');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
mysql_select_db($db_name) or die("Could not connect to Database" .mysql_error());

$username = $_POST['fname'];
$passwords = $_POST['pass'];
$email = $_POST['email'];

$query =  "INSERT INTO account (username, passwords, email) VALUES ('$username',
'$passwords', '$email')";
$result = mysql_query($query);
echo $username;
mysql_close($link);
?>


Quotes are for strings; backticks are for table and column name escaping
mysql_query("INSERT INTO account (username, passwords, email)
VALUES ('$username', '$passwords', '$email')", $link);

So remove the quotes from the table and column names and add them to the values.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. Learn about Prepared Statements instead, and use PDO or MySQLi. See this article for a quick overview how to do it and why it is so important.

0 comments:

Post a Comment