1

I want to connect to mysql database with php. The codes are:


index.php

  <button>
    <a href='insert.php'>insert.php geçiş yap</a>
  </button>

 <?php 

  require_once 'baglan.php';
  if(!isset($_GET['sayfa'])){
    $_GET['sayfa'] = 'index';
  }

  switch ($_GET['sayfa']) {
    case 'insert':
      require_once 'insert.php';
      break;
  }

 ?>

baglan.php

<?php
try{
  $db = new PDO('mysql:host=localhost;dbname=ornek_veritabani','root','');  
}catch(PDOException $e){
  echo $e -> getMessage();
};

?>

insert.php

<?php 
  echo 'insert.php';
  $sorgu = $db->prepare('INSERT INTO deneme SET
  ad = ?,
  soyad = ?,
  yas = ?,
  memleket = ?');
  $ekle = $sorgu->execute([
    'php ad','php soyad', 10, 'php memleket'
  ]);

  if($ekle){
    echo 'verileriniz eklendi...';
  } else{
    print_r($sorgu->errorInfo());
  }

?>

Problem in insert.php document. Returns error. It gives the following error:

insert.php Notice: Undefined variable: db in C:\xampp\htdocs\PHP\insert.php on line 3

Fatal error: Uncaught Error: Call to a member function prepare() on null in >C:\xampp\htdocs\PHP\insert.php:3 Stack trace: #0 {main} thrown in >C:\xampp\htdocs\PHP\insert.php on line 3

  • 1
    The link in your button is pointing to the wrong file, the one that does not have a database connection included. You probably want to link to `index.php` or require the database file in your insert script. – jeroen Jun 28 '19 at 08:38
  • 1
    please -> ```require_once 'baglan.php';``` –  Jun 28 '19 at 08:49

0 Answers0