如何在执行PHP脚本时修复服务器错误500?

时间:2022-11-07 18:58:09

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插入数据库。但是,当我连接到PHP文件时,我收到服务器500错误。有人能够发现我做错了吗?

<?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.

我发现当我将filer_input或$ _post添加到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

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();
?>

3 个解决方案

#1


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.

$ link定义在哪里?在“db-security.php”中?如果是,则您有可变范围问题。只需在函数调用中传递$ link。必须为所有功能完成此操作。

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:

不要为'db-security.php'使用函数,它应该是这样的:

<?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.

这不是完整的代码,只是一个示例。现在$ conn在全局变量范围内,并且在函数中使用global将起作用。或者只是将$ conn传递给函数,而根本不使用global。

EDIT2:

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.

以下是工作示例脚本。您需要更改一些信息以符合您的设置。我不确定为什么该函数被称为db_login(),因为该函数实际上将用户/密码添加到'user'表中。

conf.php

conf.php

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

db-security.php

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();
?>

#2


0  

So you need to bind your parameters after prepare statement

所以你需要在prepare语句之后绑定你的参数

$stmt = $link->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();

#3


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.

我一直在看你的代码,我建议你尝试不同的方法。在学习PHP时,我已经围绕这个主题了解了一段时间。我最好的建议是,每次从数据库中获取信息时都可以尝试使用try / catch语句。听起来很烦人或有问题,但很容易忽略和编写良好的代码,因为你知道每个try catch块都会执行或至少捕获错误。

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:*

PDO是最好的解决方案之一,因为它可以与多个数据库连接,执行从数据库获取信息的最佳方法是:*

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

为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

index.php执行一个简单的命令从雇主获取firstName

<?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.

祝你好运,我希望我的index.php有助于向您展示我如何找到与数据库交谈的最佳方式。

#1


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.

$ link定义在哪里?在“db-security.php”中?如果是,则您有可变范围问题。只需在函数调用中传递$ link。必须为所有功能完成此操作。

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:

不要为'db-security.php'使用函数,它应该是这样的:

<?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.

这不是完整的代码,只是一个示例。现在$ conn在全局变量范围内,并且在函数中使用global将起作用。或者只是将$ conn传递给函数,而根本不使用global。

EDIT2:

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.

以下是工作示例脚本。您需要更改一些信息以符合您的设置。我不确定为什么该函数被称为db_login(),因为该函数实际上将用户/密码添加到'user'表中。

conf.php

conf.php

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

db-security.php

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();
?>

#2


0  

So you need to bind your parameters after prepare statement

所以你需要在prepare语句之后绑定你的参数

$stmt = $link->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();

#3


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.

我一直在看你的代码,我建议你尝试不同的方法。在学习PHP时,我已经围绕这个主题了解了一段时间。我最好的建议是,每次从数据库中获取信息时都可以尝试使用try / catch语句。听起来很烦人或有问题,但很容易忽略和编写良好的代码,因为你知道每个try catch块都会执行或至少捕获错误。

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:*

PDO是最好的解决方案之一,因为它可以与多个数据库连接,执行从数据库获取信息的最佳方法是:*

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

为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

index.php执行一个简单的命令从雇主获取firstName

<?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.

祝你好运,我希望我的index.php有助于向您展示我如何找到与数据库交谈的最佳方式。