0

For some reason this little php insert won't work, could someone help? I've been trying to upload some data from a form in html. Here's some code

$dbServerName = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "kollegium_data";

$connection = mysqli_connect($dbServerName, $dbUsername, $dbPassword, $dbName);

if(isset($_POST['submit'])){ 
    $name = $_POST['teacher'];
    $email = $_POST['postdate'];
    $contact = $_POST['posttext'];
    if($name !=''||$email !='') {

        mysql_query("INSERT INTO posts(teacher, postdate, posttext) VALUES ('$name', '$email', '$contact')");
        echo "sikeres";
    }
    else{
        echo "sikertelen";
    }
}
$connection->close();

<form action="insert.php" method="POST">
    Neve: <input type="text" name="teacher" id="tanar" /><br/>
    Jelenlegi dátum (év,hónap,nap): <input type="text" name="postdate" id="datum"/><br/>
    Kiírandó szöveg (max. 3500 karakter): <input type="text" name="posttext" id="kiiras"/><br/>
    <input type="submit">
</form>
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
  • There is nothing named submit so isset is always a no – Victorbzh Dec 02 '21 at 15:14
  • mysql_* functions are deprecated as of PHP 5.5.0, and removed as of PHP 7.0.0. Switch your code to use [PDO](https://secure.php.net/manual/en/pdo.prepared-statements.php) or [mysqli](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead. Be sure to use prepared statements and parameter binding, so **you'll never have to worry about quoting issues again.** Also, you cannot mix MySQL APIs, so `mysql_query` will not work with `mysqli_connect` – aynber Dec 02 '21 at 15:33
  • 2
    Just an FYI whomever marked this close / duplicated. He never asked the mysql question problem, just a user here noticed it. He asked why it doesn't insert, and that's because of a HTML issue. So it's not really a duplicate of a MYSQL issue. – Forbs Dec 02 '21 at 16:01

2 Answers2

4

You didn't create a $_POST['submit'] variable.

Change

<input type="submit">

To

<input type="submit" name='submit'>
Forbs
  • 1,256
  • 1
  • 7
  • 9
2

Since you use mysqli_connect you must to use mysqli_query where first parameter is $connection:

mysqli_query(
    $connection, 
    "INSERT INTO posts(teacher, postdate, posttext) VALUES ('$name', '$email', '$contact')"
);

Also your code open to SQL Injection attack, so you need to use prepared statement:

$stmt = mysqli_prepare(
    $connection,
    "INSERT INTO posts(teacher, postdate, posttext) VALUES (?, ?, ?)"
);

mysqli_stmt_bind_param($stmt, "sss", $name, $email, $contact);

mysqli_stmt_execute($stmt);
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39