0

I'm having problems with PHP and MySQL. I have this table called 'TestTable' in a databse in phpMyAdmin, which for now just holds names. I want to be able to add names from a webpage using PHP. Establishing connection has been succesful, but nothing seems to happen when I actually do the SQL query. I have tried using the query directly in phpMyAdmin, where it does work.

Here's the entire code (username and password are correctly filled in in the code, but I took them out for obvious reasons):

<?php
    $hostname = "localhost";
    $username = "";
    $password = "";
    $db = "jortmilan_form";
    
    $link = mysqli_connect($hostname, $username, $password, $db) 
    or die ("Connection failed: " . mysqli_connect_error());
    
    echo "Connection to database established!";
    echo "<br>";
    
    $sql = "INSERT INTO TestTable(Name) VALUES('peter');";
    $result = mysqli_query($db, $sql);

    echo "sql used: {$sql}";
    echo "<br>";
    echo "result was: {$result}";
    echo "<br>";
    
    if ($result) {
        echo "data succesfully added! yaay";
    }
    else {
        echo "data upload failed";
        echo "<br>";
        echo mysqli_error();
    }
?>

This is the output on the webpage:

Connection to database established! sql used: INSERT INTO TestTable(Name) VALUES('peter'); result was: data upload failed

Milan
  • 1
  • 2
  • You have an error. [`mysqli_error()`](https://www.php.net/manual/en/mysqli.error.php) needs one argument. Please consider switching error mode on instead. [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman Feb 01 '21 at 16:25
  • If you are only starting to learn PHP then you should learn PDO instead of mysqli. PDO is much easier and more suitable for beginners. Start here https://phpdelusions.net/pdo & https://websitebeaver.com/php-pdo-prepared-statements-to-prevent-sql-injection – Dharman Feb 01 '21 at 16:26
  • Once you check for the error, it will show you the source of the problem - you're passing the wrong variable. Instead of the actual connection, you give `mysqli_query` only the database name - `mysqli_query($db, $sql)` (you use `$db` instead of `$link`). – El_Vanja Feb 01 '21 at 16:27

0 Answers0