Big_Chair
Big_Chair

Reputation: 3239

Creating MySQL Table not working

I don't understand where my error in this code to create a simple Table in a MySQL database is:

<?php

// Create connection
$con=mysqli_connect("localhost", "administrator", "199992", "test");

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Select DB
mysqli_select_db($con, "test");

// Create table
$sql = "CREATE TABLE IF NOT EXISTS Notizen(Benutzer TEXT,Datum TEXT,Notiz TEXT)";  


This should actually work, shouldn't it?
But when I try to insert something later:

if(!(empty($_POST[vorname]) and empty($_POST[nachname]) and empty($_POST[notiz]))) {
$sql = "INSERT INTO Notizen (Benutzer, Datum, Notiz)
    VALUES
    ('$_POST[vorname] $_POST[nachname]', 'datum', '$_POST[notiz]')"; 

if (!mysqli_query($con,$sql))
{
echo "Error: " . mysqli_error($con);
 }
}

I get an error:

"Error: Table 'test.notizen' doesn't exist".

Upvotes: 1

Views: 2517

Answers (3)

Code Lღver
Code Lღver

Reputation: 15603

  1. As I see in your code, you are not executing the create query. execute it by mysqli_query($con,$sql).
  2. Give the space between Notizen (Benutzer table name and braces in create table query.
  3. Check that your query is executing or not by using the error function to create table.

Upvotes: 5

RiggsFolly
RiggsFolly

Reputation: 94662

After this line

$sql = "CREATE TABLE IF NOT EXISTS Notizen(Benutzer TEXT,Datum TEXT,Notiz TEXT)";  

You must run a

if (!mysqli_query($con,$sql))
{
    echo "Error creating a database: " . mysqli_error($con);
}

Upvotes: 2

Ben Matheja
Ben Matheja

Reputation: 115

make sure you run the query with mysqli_query() .. you cant insert before the table definition is stored in your db

Upvotes: 2

Related Questions