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

时间:2022-09-25 16:47:23

I am having some trouble getting my HTML table to insert and update into my SQL database using PHP. Not really sure where I am going wrong. It doesn't throw any errors, but doesn't seem to do anything either. The 'get', 'new' and 'delete' buttons are all working fine. I am trying to insert and update data as well as images. Thanks

我在使用PHP将HTML表格插入并更新到我的SQL数据库时遇到了一些麻烦。不确定我哪里出错了。它不会抛出任何错误,但似乎也没有做任何事情。 'get','new'和'delete'按钮都运行正常。我正在尝试插入和更新数据以及图像。谢谢

<?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 个解决方案

#1


-1  

If you has this complete code in one file... you have to split it in others more readable, this will permit you detect errors easily.

如果您在一个文件中包含此完整代码...您必须将其拆分为更易读的其他文件,这将允许您轻松检测错误。

for example..

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

This class will give you a complete use for database transactions, and the next class is you Team class...

这个类将为您提供数据库事务的完整用途,下一课是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
     */
}

And them you HTML...

他们你HTML ...

Another tip... you have to know the * community don't have your complete development environment so you need to be more specific about your questions, and don't put questions like... I don't not why is not working.

另一个提示......你必须知道*社区没有完整的开发环境所以你需要更具体地提出你的问题,不要提出类似的问题...我不知道为什么不工作。

#1


-1  

If you has this complete code in one file... you have to split it in others more readable, this will permit you detect errors easily.

如果您在一个文件中包含此完整代码...您必须将其拆分为更易读的其他文件,这将允许您轻松检测错误。

for example..

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

This class will give you a complete use for database transactions, and the next class is you Team class...

这个类将为您提供数据库事务的完整用途,下一课是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
     */
}

And them you HTML...

他们你HTML ...

Another tip... you have to know the * community don't have your complete development environment so you need to be more specific about your questions, and don't put questions like... I don't not why is not working.

另一个提示......你必须知道*社区没有完整的开发环境所以你需要更具体地提出你的问题,不要提出类似的问题...我不知道为什么不工作。