@tameme0128

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

PHPからのSQLコードにつて

解決したいこと

PHPにてPOSTで受け取った内容をデータベースに登録する際のSQLにて苦戦しております。
解決方法を教えて下さい。

発生している問題・エラー

エラーが発生しました。:PDO::__construct(): Argument #1 ($dsn) must be a valid data source name
Fatal error: Uncaught Error: Call to a member function prepare() on null in /home/******/www/stock/regist.php:34 Stack trace: #0 {main} thrown in

該当するソースコード

//DBへの接続
try {
    $host = '*********';    //サーバ名
    $user = '*********';         //ユーザ名
    $pass = '*********';     //DBのパスワード
    $dbnm = '*********';        //データベース名
    $options = [];
    $conn = mysqli_connect($host,$user,$pass,$dbnm);
if (!$conn) {
    die("データベース接続エラー: " . mysqli_connect_error());
}
     $pdo = new PDO($host, $user, $pass, $options );
        } catch (Exception $e) {
                  echo 'エラーが発生しました。:' . $e->getMessage();
        }

    $sql = "INSERT INTO stock (indexno, date, customername, customerid, pono, productname, amountno, remark1, remark2) VALUES (:indexno, :date, :customername, :customerid, :pono, :productname, :amountno, :remark1, :remark2);";
    $sth = $pdo -> prepare($sql); //挿入する値は空のまま、SQL実行の準備をする
//クエリのパラメータに合わせて値を組み込む
$sth -> bindValue(':indexno', 5);
$sth -> bindValue(':date', $date);
$sth -> bindValue(':customername', $customername);
$sth -> bindValue(':customerid', $customerid);
$sth -> bindValue(':pono', $pono);
$sth -> bindValue(':productname', $productname);
$sth -> bindValue(':amountno', $amountno);
$sth -> bindValue(':remark1', $remark1);
$sth -> bindValue(':remark2', $remark2);
//組み込み後のSQL文を実行
$sth -> execute();

よろしくお願いいたします。

0 likes

1Answer

エラー内容以前にmysqli系のコマンドとPDO系のコマンドが混在してしまっています。
ちゃんと体系的な情報源から学習した方が良いですよ。

エラー内容は、
「引数 #1 ($dsn) は有効なデータソース名である必要があります」
とあるので、多分$hostが、PDOのコンストラクタで使用するフォーマットに合致していないのだと思います。(mysqli_connectで使用するものとは違います)

PDO::__construct

上記のdsnを参考に確認してください。

2Like

Comments

  1. @tameme0128

    Questioner

    確かに混同してました。
    引数としてホスト名しか渡していませんでした。
    ありがとうございました。

  2. This comment has been deleted for violation of our Terms of Service.

Your answer might help someone💌