0

I have a database that I have made on phpmyAdmin that consists of three columns: id, name and number. I have added 3 rows of data to the database through phpmyadmin. I now wish to add data to this database through my php file. This is the code that I use to add in the data and display the data on the browser:

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myfirstsite";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}

$sql = "INSERT INTO hi (id, name, number)
VALUES ('99', 'Doe', '999999')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}


//displaying data
$sql = "SELECT id, name, number FROM hi";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " .                    $row["number"]. "<br>";
}
} else {
echo "0 results";
}

$conn->close();
?>

The thing is that I don't understand why the new data isn't placed into the database but the current data is displayed onscreen.

Dharman
  • 30,962
  • 25
  • 85
  • 135
kitchen800
  • 197
  • 1
  • 12
  • 36

2 Answers2

4

In your code you are making reference to $link which doesnt exists, it should be $conn

Chaneg this:

if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

To:

if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
yardie
  • 1,583
  • 1
  • 14
  • 29
-2

you need to fix this one

$conn = new mysqli($servername, $username, $password, $dbname);

to

$conn = new mysqli_connect($servername, $username, $password, $dbname);

and also this need to fix

if(mysqli_query($conn, $sql)){
     echo "Records inserted successfully";
}else{
     echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
Abhinav Suman
  • 940
  • 1
  • 9
  • 29