Connecting a MySQL database & creating & inserting values in a table via a php script

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ankit Diwan
    New Member
    • Dec 2013
    • 17

    Connecting a MySQL database & creating & inserting values in a table via a php script

    when i try to connect php script to MySQL for creating & inserting values in a table i get an error msg: Error creating database: Can't create database 'mi_db'; database existsAccess denied for user ''@'localhost' to database 'mi_db'. I am running the php via a wamp server...root directory - www and my database name is mi_db. Please suggest possible ways to resolve....
  • Luuk
    Recognized Expert Top Contributor
    • Mar 2012
    • 1043

    #2
    Technically the topic 'mysql' is wrong, it has more to do with 'php', especially when you write that the database exists.

    Can you post your PHP code here? (use '[CODE]' tags..)

    Comment

    • Ankit Diwan
      New Member
      • Dec 2013
      • 17

      #3
      Code:
      <?php 
       // Connects to your Database 
       $con = mysqli_connect("localhost", "root", "mysql@777") or die(mysqli_error());
      // Create Database 
       $sql="CREATE DATABASE mi_db";
       if (mysqli_query($con,$sql))
        {
        echo "Database mi_db created successfully";
        }
        else
        {
        echo "Error creating database: " . mysqli_error($con);
        } 
       $db_selected = mysqli_select_db('mi_db', $con);
      if (!$db_selected) {
          die ('Can\'t use mi_db : ' . mysqli_error());
      }
      // Create table
      $sql="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT(11))";
      // Execute query
      if (mysqli_query($con,$sql))
        {
        echo "Table persons created successfully";
        }
      else
        {
        echo "Error creating table: " . mysqli_error($con);
        }

      Comment

      • Ankit Diwan
        New Member
        • Dec 2013
        • 17

        #4
        There is no problem creating database mi_db but when I try to select the mi_db to create a table and to insert values into it..i get that error msg..please suggest

        Comment

        • Luuk
          Recognized Expert Top Contributor
          • Mar 2012
          • 1043

          #5
          Line#14 should be:
          Code:
          $db_selected = mysqli_select_db($conn, 'mi_db';
          see: http://www.php.net/manual/en/mysqli.select-db.php

          Because of this error, the database is not selected, and the table cannot be created.

          Comment

          • Ankit Diwan
            New Member
            • Dec 2013
            • 17

            #6
            Great..thanks for the answer..

            Comment

            Working...