Ошибка PHP / MySQL: не удалось выполнить INSERT INTO с помощью PDO - PullRequest
0 голосов
/ 27 мая 2019

Я новичок в PHP / MySQL, пытаюсь вставить данные в таблицу через форму, но я продолжаю получать это:

Соединение успешно ОШИБКА: не удалось выполнить INSERT INTO foo (имя, фамилия, стационарный, мобильный) ЗНАЧЕНИЯ ('', '', ',').

Мое ограниченное понимание говорит мне, что я подключаюсь успешно, но ничего не происходит в таблице.Проверка таблицы подтверждает это.

Я пытаюсь отправить данные с сервера WHMCS PHP 7.1 на удаленный хост, на котором работает MySQL 5.1.73.Я извлекаю идентификатор пользователя из WHMCS и предварительно заполняю это поле идеей отправить его вместе с остальными данными формы.Мне присвоили это поле «скрытый» и «текст», не повезло.

Я даже скопировал / вставил форму в отдельный html и попытался запустить все в корне.Не повезло.

Я использовал этот пример в качестве руководства.

form.tpl:

<form method="post" action="includes/action.php">
User ID:<input type ="text" name = "userid" value={$d} readonly> //pulls userID from WHMCS
First name:<input type="text" name="firstname">
Last name:<input type="text" name="lastname">
Landline:<input type="text" name="landline">
Mobile:<input type="text" name="mobile">
<input type="submit" value="Submit"></form>

dbconnect.php:

$servername = "fqdn.com";
$username = "few";
$password = "2many";

try {
    $conn = new PDO("mysql:host=$servername;dbname=data_base", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

action.php:

//Open MySql Connection
include "dbconnect.php";

// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO foo (userid, firstname, lastname, landline, mobile) VALUES (:userid, :firstname, :lastname, :landline, :mobile)");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':landline', $landline);
$stmt->bindParam(':mobile', $mobile);

// insert a row
$userid = $_POST["userid"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$landline = $_POST["landline"];
$mobile = $_POST["mobile"];
$stmt->execute();


    echo "New records created successfully";
} catch(PDOException $e)
    {
        echo "Error: " . $e->getMessage();
    }

if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}

$conn = null;

Ответы [ 2 ]

0 голосов
/ 03 июня 2019

Извините за задержку.Вот решение.

action.php:

public function insertToDb($data)
    {
        try{
           $sql = "INSERT INTO table_name (column1, column2) VALUES ('" . $data['column1']."','" .  $data['column2']."')";
            $this->con->exec($sql);
           if($this->con->lastInsertId() > 0){
                return true;
            } else {
                return "Error: " . $sql . "<br>" . $conn->error;
            }
        } catch (\PDOException $e) {
            return "Insert failed: " . $e->getMessage();
        }
    }

    public function getSingleData($d,$c)
    {
        try{
           $sql = "SELECT * FROM table_name  WHERE d='".$d."' AND c='".$c."'";
           $query = $this->con->prepare($sql);
           $query->execute();
           return $query->fetchAll(\PDO::FETCH_ASSOC);
        } catch (\PDOException $e) {
            return "Error: " . $e->getMessage();
        }
    }

Редактировать: @halfer спасибо за указание на уязвимость.

public function insertToDb($data)
    {
        try{
            $insertdata = [
                'column1' => $data['column1'],
                'column2' => $data['column2'],
                'column3' => $data['column3'],
            ];
           $sql = "INSERT INTO table_name (column1, column2,column3) VALUES (:column1,:column2,:column3)";
           $stmt= $this->con->prepare($sql);
           $stmt->execute($insertdata);
           if($this->con->lastInsertId() > 0){
                return true;
            } else {
                return "Error: " . $sql . "<br>" . $conn->error;
            }
        } catch (\PDOException $e) {
            return "Insert failed: " . $e->getMessage();
        }
    }
0 голосов
/ 27 мая 2019

в action.php вы используете переменные до того, как их установите.

// insert a row
$userid = $_POST["userid"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$landline = $_POST["landline"];
$mobile = $_POST["mobile"];

// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO foo (id, firstname, lastname, landline, mobile) VALUES (:userid, :firstname, :lastname, :landline, :mobile)");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':landline', $landline);
$stmt->bindParam(':mobile', $mobile);
$stmt->execute(); 
...