0

I am trying to insert into a database through PHP. However, when I connect to the PHP file I get server 500 error. Would anyone be able to spot what I am doing wrong?

<?php

    include 'db-security.php';
    function db_login() 
    {
        $userName = filter_input(INPUT_POST, "userName");  
        $password = filter_input(INPUT_POST, "password");

       //binding the variable to sql.
       $statement = $link->prepare("INSERT INTO user(username, password)        
       VALUES($userName, $password)");

       //execute the sql statement.
       $statement->execute();
}
db_login();
?>

Updated:

I have discovered the error occurs when i add filer_input or $_post to the php.

<?php

include 'db-security.php';
function db_login() {
        global $conn;
        // use my eaxmple to filter input to get the data out of the form, because security.
        //$userName = filter_input(INPUT_POST, "userName");  
        $userName = $_POST['userName'];
        $password = $_POST['password'];
        //$password = filter_input(INPUT_POST, "password"); 

    //binding the variable to sql.

    $stmt = $conn->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
    $stmt->bindParam(':pswd', $password);
    $stmt->bindParam(':usrname', $userName);
    $stmt->execute();
    //execute the sql statement.
}
db_login();
?>

db-security.php

<?php

include_once 'conf.php';
function db_connect() {
 // Define connection as a static variable, to avoid connecting more than once 
    static $conn;

    // Try and connect to the database, if a connection has not been established yet
    if(!isset($conn)) {
         // Load configuration as an array. Use the actual location of your configuration file  
try 
      {
          $conn = new PDO("mysql:host=localhost;port=3307;dbname=database", DB_USERNAME,DB_PASSWORD);
              // stores the outcome of the connection into a class variable
          $db_msg = 'Connected to database';
      }
      catch(PDOException $e)
      {
          $conn = -1;
          $db_msg = $e->getMessage();
      }

//$conn = new PDO(DB_HOST,DB_USERNAME,DB_PASSWORD , MAIN_DB);



    }
}
db_connect();
?>
Bish25
  • 606
  • 1
  • 10
  • 35

3 Answers3

0

So you need to bind your parameters after prepare statement

$stmt = $link->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
  • Thanks for the reply. I have add this into the code but still getting error 500. do you reckon its to do with the filter_input ? – Bish25 Feb 10 '16 at 16:38
0

Where is $link defined? In 'db-security.php'? If yes then you have a variable scope problem. Just pass $link in the function call. This would have to be done for all functions.

define function as = function db_login($link)
call function like = db_login($link);

EDIT:

Don't use a function for 'db-security.php' it should be like this:

<?php
$conn = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>

This is not complete code, just a sample. Now $conn is in the global variable scope and using global in the functions will work. Or just pass $conn to the function and not use global at all.

EDIT2:

Below are the working sample scripts. You need to change some information to match your setup. I'm not sure why the function is called db_login() since the function actually adds the user/password into the 'user' table.

conf.php

<?php
define('DB_USERNAME', 'test');
define('DB_PASSWORD', '123456');
?>

db-security.php

<?php
include_once 'conf.php';

try
{
 $conn = new pdo("mysql:host=localhost; dbname=test; charset=utf8", DB_USERNAME, DB_PASSWORD);
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
 $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
 die('Unable to connect to database!');
}
?>

main script

<?php
include 'db-security.php';

function db_login()
{
 global $conn;
 $userName = $_POST['userName'];
 $password = $_POST['password'];
 $stmt = $conn->prepare("INSERT INTO user(username, password) VALUES(:usrname, :pswd)");
 $stmt->bindParam(':usrname', $userName);
 $stmt->bindParam(':pswd', $password);
 $stmt->execute();
}
db_login();
?>
CharlesEF
  • 608
  • 1
  • 15
  • 25
  • sorry I'm a newbie, but where would I place the define and where would I call it in the code? Thanks – Bish25 Feb 10 '16 at 19:18
  • Based on your new code you don't need my sample code anymore. One thing I will say is that the way your code is written the function call `db_login();` will run when the page loads. Which means username and password will be blank. You need to wrap that line of code in a isset test to check that the submit button has been clicked. Can you post the HTML
    code as well?
    – CharlesEF Feb 10 '16 at 19:51
  • I am creating a mobile app which is written in C#. an array is sent to the PHP. the page loads once i have the data in the array. – Bish25 Feb 10 '16 at 20:30
  • `byte[] InsertUser = client.UploadValues("http://test.co.uk/db-login.php", "POST", UserInfo);` – Bish25 Feb 10 '16 at 20:36
  • I know nothing about C# but assuming your array passed to the PHP page contains name/value pairs I don't see why it wouldn't work. PHP is case sensitive so are your sure `$_POST['userName']` is correct? Maybe it should be `$_POST['username']`? – CharlesEF Feb 10 '16 at 21:34
  • Unfortunately, I have checked all of that and no luck, I did a test that post to the PHP and then sends it straight back without the insert. This shows in C# perfectly. I can only think it's not connecting to database when running insert? but I get no error now with current code? – Bish25 Feb 10 '16 at 21:41
  • Would you like me to post the db-security.php ? – Bish25 Feb 10 '16 at 21:43
  • Yes, if you can. I have 'assumed' you were connecting correctly. – CharlesEF Feb 10 '16 at 22:02
  • That code seems overly complicated to me. I can tell you that the way the code is written will never set `$conn` because you have that code in a function which returns nothing. You should do a search for 'php pdo examples' and see how a connection is made. To make it easier you should not use a function at all. See my edit. – CharlesEF Feb 10 '16 at 23:12
  • Also, can you post 'conf.php'? I will put together a small sample script for you. – CharlesEF Feb 11 '16 at 03:14
  • I put together some sample scripts. They are just the basics, like the code you posted. You still need to sanitize the user data, add checking to make sure the user was inserted. This code is tested and works fine on my localhost. See Edit2 above. If this answer helps you then please accept the answer as correct. – CharlesEF Feb 11 '16 at 07:55
0

I have been looking at your code and I would advice you to try a different approach. I've been wrapping my head around this subject for a while when learning PHP. Best advice i've had is that you can best try when fetching information from the DB is using a try/catch statement everytime. Sounds annoying or problematic but it easy to overlook and well written maintained code because you know every try catch block will execute or catch the error atleast.

With PDO being one of the best solutions because it can connect with multiple databases the best way to execute getting information from the Database is this:*

I am gonna give you my example of something i wrote. I don't want to write it all out in your situation because i feel that's something you can better do to learn what went wrong and i hope this gives you a step in the right direction.

database.php

$serverName = "";
$dbName = "";
$userName = "";
$password = "";

try {

        $db = new PDO("mysql:host=$serverName;dbname=$dbName", $userName, $password);
        // Set the PDO error mode to exception
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->exec("SET NAMES 'utf8'");

    }
    catch(PDOException $e){

        echo"Connection failed: " . $e->getMessage();
        exit;
    }

?>

index.php Executing a simple commmand get firstName from employers

<?php 
require_once 'database.php';

try 
{ 
    $sQuery = " 
        SELECT 
            firstName 
        FROM 
            employees 
    "; 

    $oStmt = $db->prepare($sQuery); 
    $oStmt->execute(); 

    while($aRow = $oStmt->fetch(PDO::FETCH_ASSOC)) 
    { 
        echo $aRow['firstName'].'<br />'; 
    } 
} 
catch(PDOException $e) 
{ 
    $sMsg = '<p> 
            Regelnummer: '.$e->getLine().'<br /> 
            Bestand: '.$e->getFile().'<br /> 
            Foutmelding: '.$e->getMessage().' 
        </p>'; 

    trigger_error($sMsg); 
} 



?>

Good luck and i hope my index.php is helpful in showing you how I find is the best way momentarily to talk to the database.

izk
  • 234
  • 6
  • 19
  • You're doing a lot of useless job here. In fact, you don't need the code in the catch block - **PHP already doing it**. if you just remove try and catch from your code **the result be exactly the same** :) – Your Common Sense Feb 11 '16 at 10:49
  • Thanks for the clarification, I am learning php as it goes and thats at 1 tutorial how they teached me. I've seen on your profile a PDO link, i will try to see if that's a better explained version of pdo. Again thank you! – izk Feb 11 '16 at 12:05
  • Glad you noticed it. Please feel free to ask any questions, I am eager to get a feedback. I'll explain in detail whatever questions you'll have. – Your Common Sense Feb 11 '16 at 12:22
  • @YourCommonSene Hi, I have read through your website and just what I am looking for! being a beginner in PHP and PDO. However, I still can get a simple insert statement to work. I am developing an app in C# and trying to use PHP as a bridge between the two. Thanks Sam. – Bish25 Feb 13 '16 at 18:20