Can't get my code to work

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
linneabb
New php-forum User
New php-forum User
Posts: 2
Joined: Sun Mar 11, 2018 10:12 pm

Sun Mar 11, 2018 10:18 pm

Hi!
I've been coding PHP for a week now and can't get my code to work. I've created a table and connected to the database, so far so good. Now I try to get data from the first file via the second file and show the result but when I load the file it's all blank?

Here is the first file:

<?php header("location: http://webbred2.utb.hb.se/~s163007/uppgift-read.php"); ?>
<html>
<head></head>
<body>

<?php
$servername = "localhost";
$username = "s163;
$password = "*****";
$dbname = "s163";

try{
$sql = "INSERT INTO Book(book_id, author, title)
VALUES ('author', 'title')";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Database connected successfully. <br />";


}

catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
?>

</body>
</html>

And here is the second

<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$servername = "localhost";
$username = "s163";
$password = "****";
$dbname = "s163";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt = $conn->query("SELECT author, title FROM Book");

foreach ($stmt as $row){
echo $row ['author'];
echo $row ['title'];
}
}
catch(PDOException $e)
{
echo $sql . "<br />" . $e->getMessage();
}
?>
</body>
</html>


Can you see what I'm missing because I really can't... :(

chorn
php-forum Fan User
php-forum Fan User
Posts: 513
Joined: Fri Apr 01, 2016 2:18 am

Sun Mar 11, 2018 11:17 pm

If you redirect on the first line, all code that is coming after will never be executed.

Post Reply