简体   繁体   English

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

[英]How to fix server error 500 when executing PHP script?

I am trying to insert into a database through PHP. 我正在尝试通过PHP插入数据库。 However, when I connect to the PHP file I get server 500 error. 但是,当我连接到PHP文件时,出现服务器500错误。 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. 我发现将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();
?>

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

Where is $link defined? $ link在哪里定义? In 'db-security.php'? 在“ db-security.php”中? If yes then you have a variable scope problem. 如果是,那么您有一个可变范围问题。 Just pass $link in the function call. 只需在函数调用中传递$ link即可。 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: 不要为“ 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. 现在$ conn在全局变量范围内,并且在函数中使用global将起作用。 Or just pass $conn to the function and not use global at all. 或者只是将$ conn传递给该函数,而根本不使用global。

EDIT2: 编辑2:

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()因为该函数实际上将用户名/密码添加到了“用户”表中。

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

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. 在学习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. 我得到的最好建议是,每次从数据库中获取信息时,都最好使用try / catch语句来尝试。 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. 听起来很烦人或有问题,但是很容易忽略和编写良好的维护代码,因为您知道每个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执行一个简单的命令,从雇主那里获得名字

<?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可以帮助您了解如何立即找到数据库的最佳方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM