简体   繁体   中英

How do I insert data from a php file using PDO?

I'm trying to log some data for my website using PDO from a PHP file. I have the following code which is called by by a javascript library, D3. The call works fine, but when I run this code I get an "internal server error".

What am I doing wrong? I have been following a guide on a website and I am basically using the same principles as them. If anyone can help I'd appreciate it. Thanks a lot in advance, my code is pasted below. (Of course the database information is something valid)

    $hostname="xxxx";
    $username="xxxxxx";
    $pw="xxxxxxxx";
    $dbname="xxxx";

    try {
        $pdo = new PDO ("mysql:host=$hostname;dbname=$dbname","$username","$pw");
    } catch (PDOException $e) {
        echo "Failed to get DB handle: " . $e->getMessage() . "\n";
        exit;
    }

    //Gets IP for client.
    $ip = get_client_ip();
    //An email, format of string.
    $email = "test@test.dk";
    //An int, in this case 19.
    $prgm_name = $_GET["prgm"];
    //Piece of text, format of string of course.
    $prgm_options.=$prgm_name;
    $prgm_options.= " - ";
    $prgm_options.=$_GET["gene"];
    $prgm_options.=" - ";
    $prgm_options.=$_GET["data"];
    //Datasize, int.
    $data_size = 0;
    //Timestamp.
    $now = "NOW()";

    //Table name.
    $STAT_TABLE = "stat";

    $query = $pdo->prepare("INSERT INTO $STAT_TABLE (ip, email, prgm, options, datasize, date) VALUES (:ip, :email, :prgm_name, :prgm_options, :data_size, :now);");
    $query->execute(array(  ':ip'=>'$ip',
                             ':email'=>'$email',
                             ':prgm_name'=>$prgm_name,
                             ':prgm_options'=>'$prgm_options',
                             ':datasize'=>'$datasize',
                             ':now'=>$now));

Try the following Code to Insert

$count = $pdo->exec("INSERT INTO $STAT_TABLE(ip, email, prgm, options, datasize, date) VALUES ('$ip','$email',$prgm_name,'$prgm_options','$datasize',$now)))");
/*** echo the number of affected rows ***/
echo $count;

I like to bind each parameter individually. I think it gives you more control over data types and sizes.

try {
  $sth = $pdo->prepare("INSERT INTO..."); 
  $sth->bindParam(":ip", $ip, PDO::PARAM_STR, 16);   
  $sth->bindParam(":email", $email, PDO::PARAM_STR, 30);     
  // etc...
  $sth->execute();
} catch (Exception $e) { 
  print_r($e);
}

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