0

Hi guys can you please tell me if there is an error on this code. this is not working. it didn't add any on my database. thanks you!

$con = mysql_connect("localhost","root","pass");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("mytable",$con);



if(isset($_POST['add'])){

// Variables

$acc_class = $_POST['acc_class'];

$AddQuery = "INSERT INTO mytable ('acc_class') VALUES ('$acc_class')";  

mysql_query($AddQuery, $con);

echo "Record Successfully Added!!";
};


mysql_close($con);

?>
<form action="add.php" method="post">

Account Classification:
<input  required="required" placeholder="e.g Hotel, Restaurant" type="text" name='acc_class' size=15 />

<input type="submit" name='add' Value='&nbsp;Add Record&nbsp;'/>
</form>
2
  • try some error checking. mysql would be a good start. us1.php.net/mysql_error Commented Mar 18, 2014 at 1:47
  • Your code is vulnerable to SQL injection attacks, and is using the deprecated mysql_* functions which will be going away in a future version of PHP. Commented Mar 18, 2014 at 1:59

2 Answers 2

1

The column name(s) should be wrapped in backticks and not quotes

$AddQuery = "INSERT INTO mytable (`acc_class`) VALUES ('$acc_class')";

or remove the quotes

$AddQuery = "INSERT INTO mytable (acc_class) VALUES ('$acc_class')";

I suggest you move to mysqli_* functions with prepared statements or PDO.

and that you change $acc_class = $_POST['acc_class']; to

$acc_class = mysql_real_escape_string($_POST['acc_class']);

for the time being.

mysql_* functions are deprecated and will be removed from future PHP releases.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Thank you i found the problem: mysql_select_db("mytable",$con); i input my table haha thanks anyway! i think i need to have a coffe and break. though your comment help me also after changing mt db. thanks!
You're welcome. I also suggest you move to mysqli_* with prepared statements or PDO. It's much better and safer, cheers @Nixxx27 However what's contained in my answer should be changed to that. You can't use quotes for column names (and table names, should that happen in the future).
0

At a minimum:

$acc_class = $_POST['acc_class'];
$AddQuery = "INSERT INTO mytable ('acc_class') VALUES ('$acc_class')";

Should be:

$acc_class = $_POST['acc_class'];
$AddQuery = "INSERT INTO mytable ('acc_class') VALUES ('".$acc_class."')";

Also, it is unsafe to pass raw user input into to a SQL query in this way. Please read up on SQL Injection.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.