使用PHP更新并插入SQL数据库

时间:2018-08-28 09:45:13

标签: php sql pdo sql-update sql-insert

使用PHP将HTML表插入并更新到SQL数据库时遇到了麻烦。不太确定我要去哪里错。它不会引发任何错误,但似乎也没有任何作用。 “获取”,“新建”和“删除”按钮都可以正常工作。我正在尝试插入和更新数据以及图像。谢谢

<?php
$servername = "e0771987cert4rebeccagangemi.myitoc.com.au";
$username = "******";
$password = "********";
$message = "";
$teamID = "";
$Name = "";
$Logo = "";

if(isset($_POST["RetrieveTeam"])) {

getSpecificTeam($_POST["teamID"]);

    }

if (isset($_POST["NewTeam"])) { 
        resetTeamMaintenanceForm();
    }

if (isset($_POST["InsertTeam"])) {
        insertTeam();
    }

if (isset($_POST["UpdateTeam"])) {
updateTeam($_POST["teamID"]);
header("Location: admin.php");  
    }

if (isset($_POST["DeleteTeam"])) {
deleteTeam($_POST["teamID"]);
header("Location: admin.php");  
    }

function resetTeamMaintenanceForm() {
try {
    $teamID="";
    $TeamName="";
    $Logo = "";
    }
catch(PDOException $e) {
    echo "An error occured: " . $e->getMessage();
}
}

function getSpecificTeam($teamID) {

try {

    $conn = new PDO("mysql:host=" . $GLOBALS ['servername'] . ";dbname=e0771987_Oaktown", $GLOBALS['username'], $GLOBALS['password']);

    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $statement = $conn->query("SELECT * FROM Teams WHERE teamID='" . $teamID."'");

    $result=$statement->fetch();

    if($result == null) { //ID doesn't exist

    $GLOBALS['message'] = "The ID entered is not valid or does not exist";

    } else {

        $GLOBALS['teamID'] = $result[0];
        $GLOBALS['Name'] = $result[1]; 
        $GLOBALS['Logo'] = $result[2]; 


    }
}

catch(PDOException $e) {

    echo "An error occured:" . $e->getMessage();
}

$conn = null;
}
function insertTeam() 
{
try {
  $conn = new PDO("mysql:host=" . $GLOBALS['servername'] . ";dbname=e0771987_Oaktown", $GLOBALS['username'], $GLOBALS['password']);

  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $tmp_image_name  = $_FILES["team_image"]["tmp_name"]; //get image file

    if (!isset($tmp_image_name)) { //file hasn't been selected
        echo "Please select a file to upload"; 

   } else {
        $check = getimagesize($tmp_image_name);  // check if file is an image type

        if ($check) { // if file is an image

  $statement = $conn->prepare("INSERT INTO Teams (teamID, Name, Logo) VALUES (:teamID, :Name, :team_image)");

  $statement->bindValue(":teamID", $_POST["teamID"]);
  $statement->bindValue(":Name", $_POST["Name"]);
  $statement->bindValue(":team_image", $tmp_image_name);
  $result = $statement->execute();
  if ($result) {
     echo "Team record inserted into table successfully";

  } else {
     echo "The team record was not inserted";
  }

} else {
    echo "The file to be uploaded is not an image";
}
}
} catch(PDOException $e) {
  echo "A problem occurred: " . $e->getMessage();
}

$conn = null;
}
function updateTeam($teamID) {
try {
  $conn = new PDO("mysql:host=" . $GLOBALS['servername'] . ";dbname=e0771987_Oaktown", $GLOBALS['username'], $GLOBALS['password']);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $file_content = file_get_contents($_POST["Logo"]); 
  $statement = $conn->prepare("UPDATE Teams SET teamID=:teamID, Name=:Name, Logo=:Logo WHERE teamID='" . $teamID."'");

  $statement->bindValue(":teamID", $_POST["teamID"]);
  $statement->bindValue(":Name", $_POST["Name"]);
  $statement->bindValue(":Logo", $tmp_image_name);

  $result = $statement->execute();
  if ($result) {
     echo "Team record was updated";
  } else {
     echo "The team record was not updated";
  }
 }
catch(PDOException $e) {
  echo "A problem occured: " . $e->getMessage();
}

$conn = null;
}

function deleteTeam($teamID) {
try {
    $conn = new PDO("mysql:host=" . $GLOBALS['servername'] . ";dbname=e0771987_Oaktown", $GLOBALS['username'], $GLOBALS['password']);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $statement = $conn->prepare("DELETE FROM Teams WHERE teamID='" . $teamID. "'");

   $result = $statement->execute();
   if ($result) {
     $GLOBALS['message'] = "Team record was deleted successfully";
   } else {
     $GLOBALS['message'] = "The Team record was not deleted";
   }
 }
 catch(PDOException $e) {
  echo "A problem occurred: " . $e->getMessage();
 }

 $conn = null;
}

?>

<div id="Edit Teams">
<p id="TableHeader2">Update or Delete Teams</p>


<table style="width:66%"

    <tr>
    <td style="width:30%"><b>teamID</b></td>
    <td colspan=2><input type="text" style="width:350px" name="teamID" value="<?php echo $teamID;?>"></td>
    </tr>
    <tr>
    <td style="width:30%"><b>Name</b></td>
    <td colspan=2><input type="text" style="width:350px" name="Name" value="<?php echo $Name;?>"></td>
    </tr>

    <tr>
    <td><b>Logo</b></td>
<?php   
     $image = NULL;
     $image = $Logo; 

    if(isset($image) && !empty($image)) {
                            //echo "<td><img src='images/" . $teamRecord['Logo'] . "'/></td>";
echo '<td><img src="data:image/jpg;base64,'.base64_encode( $GLOBALS['Logo']  ).'"/></td>';   

} else { ?>

<td><input type="file" name="logo" value=""></td> 

<?php }
?>
<!--td><input type="file" name="logo" value=""></td--> 
        </tr>


  </table><br>

<input class="button" type="submit" name="NewTeam" value="New">    
<input class="button" type="submit" name="InsertTeam" value="Insert">
<input class="button" type="submit" name="RetrieveTeam" value="Get">
<input class="button" type="submit" name="UpdateTeam" value="Update">
<input class="button" type="submit" name="DeleteTeam" value="Delete">
    </div>

1 个答案:

答案 0 :(得分:-1)

如果您在一个文件中拥有完整的代码...您必须将其拆分为其他可读性更高的文件,这将使您轻松检测错误。

例如。

class PdoMysqlConnection
{
    /**
     * @var array
     */
    private $settings;

    /**
     * @var \PDO|null
     */
    private $linkid;

    public function __construct($settings = array())
    {
        $this->settings = $settings;
        return $this;
    }

    /**
     * @param string $connection
     * @return $this
     */
    public function connect($connection){
        try{
            if(!isset($this->settings[$connection])){
                throw new \Exception('The connection '.$connection.' is not defined in the parameters');
            }
            $this->linkid = new \PDO(
                'mysql:dbname='.$this->settings[$connection]['db'].';host='.$this->settings[$connection]['host'],
                $this->settings[$connection]['user'],
                $this->settings[$connection]['password'],
                array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
            );
            if (!$this->linkid){
                throw new \Exception("Cant not connect with Mysql.");
            }
            return $this;
        }
        catch (\Exception $ex) {
            var_dump($ex->getMessage());
        }
    }

    /**
     * close connection
     * @return $this
     */
    public function close(){
        try{
            $this->linkid = null;
            return $this;
        } catch (\Exception $ex){
            var_dump($ex->getMessage());
        }
    }

    /**
     * @param $sql
     * @return \PDOStatement
     */
    public function query($sql){
        try{
            $query = $this->linkid->prepare($sql);
            $query->execute();
            return $query;
        }
        catch (\Exception $ex){
            var_dump('Error query: '. $query->queryString);
            var_dump($ex->getMessage());
        }
    }

    /**
     * @param \PDOStatement $query
     * @return bool
     */
    public function hasResult($query){
        if($query->rowCount() > 0){
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param \PDOStatement $query
     * @param null $first
     * @return array
     */
    public function fetchArray($query, $first = null){
        if($first){
            return $query->fetch(\PDO::FETCH_ASSOC);
        }
        return $query->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * @param \PDOStatement $query
     * @param null $first
     * @return array|object|\stdClass
     */
    public function fecthObject($query, $first = null) {
        if($first){
            return $query->fetchObject();
        }
        $rows = array();
        while ($row = $query->fetchObject()){
            $rows[] = $row;
        }
        return $rows;
    }

    /**
     * @return int|string
     */
    public function getLastInsertedId(){
        return $this->linkid->lastInsertId();
    }
}

该课程将为您提供数据库事务的完整用法,下一个课程是Team类...

class Team{

    private $pdoConnection;

    public function __construct(){
        $this->pdoConnection = new PdoMysqlConnection($GLOBALS['db_settings']);
        /**
         * mysql2 is the name of your connection, you can define multiple 
         * connection with a multiarray setting
         */
        $this->pdoConnection->connect('mysql2');
        return $this;
    }

    public function insertTeam(){
        $this->pdoConnection->query("INSERT .... YOU CODE");
        return $this->pdoConnection->getLastInsertedId();
    }

    public function selectTeam(){
        $query = $this->pdoConnection->query("SELECT .... YOU CODE");
        return $this->pdoConnection->fetchArray($query);
    }

    /**
     * the rest of your code is in here
     */
}

他们是HTML ...

另一个提示...您必须知道stackoverflow社区没有完整的开发环境,因此您需要对问题更具体,并且不要提出类似的问题...我不知道为什么不起作用。