connecting to database

Discussion in 'PHP' started by omarali, Sep 30, 2008.

  1. #1
    Hi everyone
    could any one tell me what is wrong with this code,when I run it, dose not insert data into the database. i did create the database and the table . Thanks a lot

    
    
    <?php
    $con = mysql_connect("localhost","","");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
    	mysql_select_db("my_db", $con)
    	or die("can not connected to selected " . mysql_error());
    	$sql="INSERT INTO person (FirstName, LastName, Age)
    VALUES
    ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
    if (!mysql_query($sql,$con))
      {
      die('Error: ' . mysql_error());
      }
    echo "1 record added";
    mysql_close($con)
    ?>
    
    
    PHP:

     
    omarali, Sep 30, 2008 IP
  2. Colbyt

    Colbyt Notable Member

    Messages:
    3,224
    Likes Received:
    185
    Best Answers:
    0
    Trophy Points:
    210
    #2
    $con = mysql_connect("localhost","","");

    Are you using:

    $con = mysql_connect("localhost","username","password");

    And:

    mysql_select_db("your_databas_name", $con)
     
    Colbyt, Sep 30, 2008 IP
  3. Kaizoku

    Kaizoku Well-Known Member

    Messages:
    1,261
    Likes Received:
    20
    Best Answers:
    1
    Trophy Points:
    105
    #3
    Your arrays are wrong.
    Fix it to this

    
    $sql="INSERT INTO person (FirstName, LastName, Age)
    VALUES
    ('{$_POST['firstname']}','{$_POST['lastname']}','{$_POST['age']}')";
    
    PHP:
    And this is very vulnerable to sql injections, since you are directly querying from raw post data.
     
    Kaizoku, Sep 30, 2008 IP
  4. ads2help

    ads2help Peon

    Messages:
    2,142
    Likes Received:
    67
    Best Answers:
    1
    Trophy Points:
    0
    #4
    when doing sql query, add curly brackets to the array-type variable

    {$_POST['name']}
    PHP:
     
    ads2help, Sep 30, 2008 IP
  5. spc

    spc Well-Known Member

    Messages:
    136
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    125
    #5
    How can you connect without using a username in the connection?
    
    $con = mysql_connect("localhost","","");
    
    PHP:
    You should have at least 1 username and the user should have proper privillege in the database to insert/select/update etc.

    Try using the default one, if you don't create an user.
    
    $con = mysql_connect("localhost","root","");
    
    PHP:
     
    spc, Oct 1, 2008 IP