简体   繁体   中英

Simple PDO write not working

I'm trying to get a simple PDO insert to work. I have successfully created a tabled named mydb10 using PDO, and the next part I want to do is insert data into that table. Running the script does not return any errors (PDO error mode exception is enabled), but the table still contains null values.

I'm using a local server to run the PHP file, and am connecting to an Amazon RDS database. Currently all inbound traffic through SSH, HTTP, HTTPS, and MYSQL is allowed through the database's security group

$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$username,$password);

$statement = $link->prepare("INSERT INTO mydb10 (selectedMain, selectedSide)
    VALUES(:selectedMain, :selectedSide)");

$statement->execute(array(
    "selectedMain" => "test",
    "selectedSide" => "test2"
));

This might be silly, but I've been stuck for a while now and any help is appreciated. If you'd like any more information, let me know. I'm trying to utilize PHP in my app, but can't even get this simple test to work, so it's a bit discouraging.

EDIT # 1

This snippet is part of a larger file. I am able to successfully connect to the database with my credentials and create new tables on the server. I do have PDO error reporting enabled in exception mode, and it has helped me work past syntax errors, but I am no longer getting any errors when I run the code. There are also no errors on the MYSQL server log.

I can provide any additional information that may be useful in debugging if desired.

First you need to properly set connection to MySQL database. You can write this code to sql.php :

<?php
  $ServerName = "******";
  $Username = "******";
  $Password = "******";
  $DataBase = "******";

  try {
    $CONN = new PDO("mysql:host=$ServerName; dbname=$DataBase", $Username, $Password);
    $CONN->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  } catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
  }
?>

Now, when you properly set connection, you need to execute sql, but before this you need to include sql.php :

try {
    $SQL = 'INSERT INTO MyDB10 (SelectedMain, SelectedSide) VALUES(:SelectedMain, :SelectedSide)'; // Write SQL Query to variable
    $SQL = $CONN->prepare($SQL); // Prepare SQL Query
    $SQL->execute(array('SelectedMain' => 'Test', 'SelectedSide' => 'Test2')); // Execute data to Insert in MySQL Databse
  } catch(PDOException $e) {
     echo "Error: " . $e->getMessage();
  } 

When you finish all queries you must close connection with:

$CONN = null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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