-1

My code is below, I don't know what is wrong with my code, it says data submitted but not inserted into mysql database when I see in phpmyadmin

<?php
$dbhost = 'localhost';
$dbuser = 'Krishna';
$dbpass = 'xxxx';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
session_start();
if (isset($_POST['submit'])){
    if(! $conn ) {
        die('Could not connect: ' . mysqli_error());
    }
}
mysqli_select_db($conn, "krishna");
$sql = "INSERT INTO contact_us (name, email, sub, mess) 
    VALUES ('$_POST[name]','$_POST[email]','$_POST[sub]','$_POST[mess]')";
if(! $sql) {
    die('Error: ' . mysqli_error());
}
echo "1 Record Added to Table\n";
echo "<a href='contactForm.html'>Back to main page</a>";
mysqli_close($conn);
?>
Cœur
  • 37,241
  • 25
  • 195
  • 267
Krish
  • 19
  • 7
  • 2
    Required reading: [How can I prevent SQL-injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Alexander O'Mara Mar 27 '16 at 06:07
  • Have a bit of a look at symfony and laravel as ways of coding in PHP using a framework that might help you build a solution to your problem without having to learn every painful lesson from when PHP was invented till now. – Tim Ogilvy Mar 27 '16 at 07:31

1 Answers1

2

First let me start by saying you could do this in an attempt to learn how to use SQL which I also did when I was first learning but then realized ...

This method is subject to SQL injection attacks and should not be used. Directly taking any user input without sanitizing it first is critical mistake that can lead security vulnerabilities.

We now have tools like PDO statements which prepare your SQL for entry into a databases. Please consider using a similar tool which prepares your statements when getting anything from a user.

Users are not to be trusted. In the code below when you bindValue it takes the variable $id and removes anything harmful.

<?php
$stmt = $db->prepare("SELECT * FROM table WHERE id=? AND name=?");
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->bindValue(2, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

See this link for the source of the code above and a tutorial on PDO. There are probably better tutorials out there though.

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

ccjjmartin
  • 66
  • 6