Rectangle 27 110

Multiple Values Insert with PDO Prepared Statements

Inserting multiple values in one execute statement. Why because according to this page it is faster than regular inserts.

$datafields = array('fielda', 'fieldb', ... );

$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);
$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);

more data values or you probably have a loop that populates data.

With prepared inserts you need to know the fields you're inserting to, and the number of fields to create the ? placeholders to bind your parameters.

insert into table (fielda, fieldb, ... ) values (?,?...), (?,?...)....
function placeholders($text, $count=0, $separator=","){
    $result = array();
    if($count > 0){
        for($x=0; $x<$count; $x++){
            $result[] = $text;
        }
    }

    return implode($separator, $result);
}

$pdo->beginTransaction(); // also helps speed up your inserts.
$insert_values = array();
foreach($data as $d){
    $question_marks[] = '('  . placeholders('?', sizeof($d)) . ')';
    $insert_values = array_merge($insert_values, array_values($d));
}

$sql = "INSERT INTO table (" . implode(",", $datafields ) . ") VALUES " .
       implode(',', $question_marks);

$stmt = $pdo->prepare ($sql);
try {
    $stmt->execute($insert_values);
} catch (PDOException $e){
    echo $e->getMessage();
}
$pdo->commit();

Although in my test, there was only a 1 sec difference when using multiple inserts and regular prepared inserts with single value.

I agree and have supported your suggestion with some test data below for reference.

A typo, in the explanation above it mentions $datafields although $datafield is used in $sql. Thus copy paste would result in error. Please do rectify. Thanks for this solution though.

Used this for a while then noticed that values with single quotes in them aren't escaped properly. Using double quotes on implosion works like a charm for me: $a[] = '("' . implode(",", $question_marks) . '", NOW())';

array_merge seems more expensive than just using a array_push.

When you say "there was only a 1 sec difference", how many rows a data were you inserting? 1 sec is pretty significant depending on the context.

php - PDO Prepared Inserts multiple rows in single query - Stack Overf...

php pdo insert prepared-statement
Rectangle 27 107

Multiple Values Insert with PDO Prepared Statements

Inserting multiple values in one execute statement. Why because according to this page it is faster than regular inserts. http://dev.mysql.com/doc/refman/5.0/en/insert-speed.html

$datafields = array('fielda', 'fieldb', ... );

$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);
$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);

more data values or you probably have a loop that populates data.

With prepared inserts you need to know the fields you're inserting to, and the number of fields to create the ? placeholders to bind your parameters.

insert into table (fielda, fieldb, ... ) values (?,?...), (?,?...)....
function placeholders($text, $count=0, $separator=","){
    $result = array();
    if($count > 0){
        for($x=0; $x<$count; $x++){
            $result[] = $text;
        }
    }

    return implode($separator, $result);
}
$pdo->beginTransaction(); // also helps speed up your inserts.
$insert_values = array();
foreach($data as $d){
    $question_marks[] = '('  . placeholders('?', sizeof($d)) . ')';
    $insert_values = array_merge($insert_values, array_values($d));
}

$sql = "INSERT INTO table (" . implode(",", $datafields ) . ") VALUES " . implode(',', $question_marks);

$stmt = $pdo->prepare ($sql);
try {
    $stmt->execute($insert_values);
} catch (PDOException $e){
    echo $e->getMessage();
}
$pdo->commit();

Although in my test, there was only a 1 sec difference when using multiple inserts and regular prepared inserts with single value.

I agree and have supported your suggestion with some test data below for reference.

A typo, in the explanation above it mentions $datafields although $datafield is used in $sql. Thus copy paste would result in error. Please do rectify. Thanks for this solution though.

Used this for a while then noticed that values with single quotes in them aren't escaped properly. Using double quotes on implosion works like a charm for me: $a[] = '("' . implode(",", $question_marks) . '", NOW())';

array_merge seems more expensive than just using a array_push.

When you say "there was only a 1 sec difference", how many rows a data were you inserting? 1 sec is pretty significant depending on the context.

php - PDO Prepared Inserts multiple rows in single query - Stack Overf...

php pdo insert prepared-statement
Rectangle 27 106

Multiple Values Insert with PDO Prepared Statements

Inserting multiple values in one execute statement. Why because according to this page it is faster than regular inserts. http://dev.mysql.com/doc/refman/5.0/en/insert-speed.html

$datafields = array('fielda', 'fieldb', ... );

$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);
$data[] = array('fielda' => 'value', 'fieldb' => 'value' ....);

more data values or you probably have a loop that populates data.

With prepared inserts you need to know the fields you're inserting to, and the number of fields to create the ? placeholders to bind your parameters.

insert into table (fielda, fieldb, ... ) values (?,?...), (?,?...)....
function placeholders($text, $count=0, $separator=","){
    $result = array();
    if($count > 0){
        for($x=0; $x<$count; $x++){
            $result[] = $text;
        }
    }

    return implode($separator, $result);
}
$pdo->beginTransaction(); // also helps speed up your inserts.
$insert_values = array();
foreach($data as $d){
    $question_marks[] = '('  . placeholders('?', sizeof($d)) . ')';
    $insert_values = array_merge($insert_values, array_values($d));
}

$sql = "INSERT INTO table (" . implode(",", $datafields ) . ") VALUES " . implode(',', $question_marks);

$stmt = $pdo->prepare ($sql);
try {
    $stmt->execute($insert_values);
} catch (PDOException $e){
    echo $e->getMessage();
}
$pdo->commit();

Although in my test, there was only a 1 sec difference when using multiple inserts and regular prepared inserts with single value.

I agree and have supported your suggestion with some test data below for reference.

A typo, in the explanation above it mentions $datafields although $datafield is used in $sql. Thus copy paste would result in error. Please do rectify. Thanks for this solution though.

Used this for a while then noticed that values with single quotes in them aren't escaped properly. Using double quotes on implosion works like a charm for me: $a[] = '("' . implode(",", $question_marks) . '", NOW())';

array_merge seems more expensive than just using a array_push.

When you say "there was only a 1 sec difference", how many rows a data were you inserting? 1 sec is pretty significant depending on the context.

php - PDO Prepared Inserts multiple rows in single query - Stack Overf...

php pdo insert prepared-statement
Rectangle 27 1

I had the same problem and it was "complicated" by the fact that I redirect all URLs to a single .php file. It turned out all I had to do to solve it was to insert the following piece of code before any html is written to the page.

<?php
if (isset($_POST['mypostvar']) && isset($_SERVER['REQUEST_URI']))
{
    [process the post data in 'mypostvar']
    header ('Location: ' . $_SERVER['REQUEST_URI']);
    exit();
}
?>

This will redirect to the same page after the postdata is processed as you want it. After the redirect the original postdata is vanished and will not trigger the resubmit. The function 'header()' will only work if you insert it before anything is written to the page. exit() is necessary.

You have to process the post data before you place the header().

php forms
Rectangle 27 1

Updated Code With Insert into Database using php if you want

Dropzone.autoDiscover = false;
	jQuery(document).ready(function() {

	  $("div#my-awesome-dropzone").dropzone({
	    url: "/file/post"
	  });

	});
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/dropzone.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/min/basic.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/dropzone.js"></script>


<form action="save2.php" method="POST" class="form-horizontal" role="form">
  <div class="form-group"></div>

  <label for="name">Name :</label>
  <input type="text" name="name" id="input-title" class="form-control">

<br><br>

  <label for="description">Email:</label>
  <input type="text" name="description" id="input-description" class="form-control">
<br><br>
 <label for="File">File: </label>
 <br><br>
  <div class="dropzone dropzone-previews" name="File" id="my-awesome-dropzone"></div>

<br><br>

  <div class="form-group">
    <div class="col-sm-10 col-sm-offset-2">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
  </div>

</form>


 <script type="text/javascript">

Dropzone.autoDiscover = false;
  jQuery(document).ready(function() {

    $("div#my-awesome-dropzone").dropzone({
      url: "/file/post"
    });

  });


 </script>


<!-- Save Data using PHP -->

 <?php
if( isset($_POST['submit']) && isset($_POST['name']) && isset($_POST['email']) && !empty($_FILES)){

  $dbHost = 'localhost';
  $dbUsername = 'root';
  $dbPassword = '';
  $dbName = 'yourdbname';
  //connect with the database
  $conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
  if($mysqli->connect_errno){

    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
  }


  $name = $_POST['name'];
  $email = $_POST['email'];

  $targetDir = "uploads/";
  $fileName = $_FILES['file']['name'];
  $targetFile = $targetDir.$fileName;
  if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
    //insert file information into db table
    $conn->query("INSERT INTO tbl_name (name,email,file_name, uploaded) VALUES('".$name."','".$email."','".$fileName."','".date("Y-m-d H:i:s")."')");
  }

}
else{

$error = "Fill All Details First !!";

if ( isset($_POST['submit']) && isset($error)) {  echo $error;  }

}
?>

you can also upload and store in database this using php easily, i updated the wait.

I have updated my post as well. Do you maybe know why I get [object Object] and server error 419?

@KiraArik wait i have to check it

php - Using Dropzone image uploader as one item in long form - Stack O...

php forms dropzone.js
Rectangle 27 1

Updated Code With Insert into Database using php if you want

Dropzone.autoDiscover = false;
	jQuery(document).ready(function() {

	  $("div#my-awesome-dropzone").dropzone({
	    url: "/file/post"
	  });

	});
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/dropzone.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/min/basic.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/dropzone.js"></script>


<form action="save2.php" method="POST" class="form-horizontal" role="form">
  <div class="form-group"></div>

  <label for="name">Name :</label>
  <input type="text" name="name" id="input-title" class="form-control">

<br><br>

  <label for="description">Email:</label>
  <input type="text" name="description" id="input-description" class="form-control">
<br><br>
 <label for="File">File: </label>
 <br><br>
  <div class="dropzone dropzone-previews" name="File" id="my-awesome-dropzone"></div>

<br><br>

  <div class="form-group">
    <div class="col-sm-10 col-sm-offset-2">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
  </div>

</form>


 <script type="text/javascript">

Dropzone.autoDiscover = false;
  jQuery(document).ready(function() {

    $("div#my-awesome-dropzone").dropzone({
      url: "/file/post"
    });

  });


 </script>


<!-- Save Data using PHP -->

 <?php
if( isset($_POST['submit']) && isset($_POST['name']) && isset($_POST['email']) && !empty($_FILES)){

  $dbHost = 'localhost';
  $dbUsername = 'root';
  $dbPassword = '';
  $dbName = 'yourdbname';
  //connect with the database
  $conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
  if($mysqli->connect_errno){

    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
  }


  $name = $_POST['name'];
  $email = $_POST['email'];

  $targetDir = "uploads/";
  $fileName = $_FILES['file']['name'];
  $targetFile = $targetDir.$fileName;
  if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
    //insert file information into db table
    $conn->query("INSERT INTO tbl_name (name,email,file_name, uploaded) VALUES('".$name."','".$email."','".$fileName."','".date("Y-m-d H:i:s")."')");
  }

}
else{

$error = "Fill All Details First !!";

if ( isset($_POST['submit']) && isset($error)) {  echo $error;  }

}
?>

you can also upload and store in database this using php easily, i updated the wait.

I have updated my post as well. Do you maybe know why I get [object Object] and server error 419?

@KiraArik wait i have to check it

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

php - Using Dropzone image uploader as one item in long form - Stack O...

php forms dropzone.js
Rectangle 27 2

Instead of

$db->prepare("INSERT INTO users(password,email) VALUES ('?','?');");

ps. Order is important: in your bind_param() you have email and password in opposite order than in your query.

mysql - How to insert form data using MySqli/PHP? - Stack Overflow

php mysql forms mysqli
Rectangle 27 2

Instead of

$db->prepare("INSERT INTO users(password,email) VALUES ('?','?');");

ps. Order is important: in your bind_param() you have email and password in opposite order than in your query.

mysql - How to insert form data using MySqli/PHP? - Stack Overflow

php mysql forms mysqli
Rectangle 27 1

You could always use a PDO wrapper class, I use the class below to handle most of my PDO queries:

class DB {
    protected
        // Return from mysql statement
        $data = array(),
        // Used for checking whether something was added to the JSON object and remove it if the table column doens't exist
        $table_cols = array(),
        // Storing the table name we are working with
        $table = '';
    protected static
        // PDO connection to the DB
        $_conn = null,
        // The DB credentials retrieved from the ini file
        $_credentials = array ();
    private
        $_id = -1,
        $_keys = array(),
        $_values = array(),
        $_last_insert_id = -1,
        $_results = array();

    //
    //  PUBLIC FUNCTIONS
    //
    public function __construct () {
        if (self::$_conn === null) {
            self::setCredentials();
            try {
                self::$_conn = new \PDO("mysql:host=" . self::$_credentials['host'] . ";dbname=" . self::$_credentials['dbname'] , self::$_credentials['username'], self::$_credentials['password']);
            } catch (\PDOException $e) {
                DebugLog::instance('DB')->error($e, 'db_connection');
            }
        }
    }

    public function insert ($data) {
        $data = $this->checkCols($data);
        // Allows us to quickly clone data by removing the id and inserting as a new record
        if (isset($data['id'])) {
            unset($data['id']);
        }
        $this->data = $data;
        $this->setDataBinding();
        $sql = "INSERT INTO `" . self::$_credentials['dbname'] . "`.`{$this->table}` (`" . implode('`, `', $this->_keys) . "`) VALUES (:" . implode(', :', $this->_keys) . ");";
        return $this->prepareAndExecute($sql);
    }

    public function update ($data) {
        $data = $this->checkCols($data);
        if (!isset($data['id'])) {
            // Houston we have a problem, there needs to be an id to update a record
            DebugLog::instance('DB')->error("No ID set for Update: " . implode(', ', array_keys($data)), 'db_id_' . $this->table);
        } else {
            // We need to unset the id because it shouldn't be in the data binding
            // But we still hold onto it for the where clause
            $id = $data['id'];
            unset($data['id']);
            $this->data = $data;

            $this->setDataBinding();

            $sql = "UPDATE `" . self::$_credentials['dbname'] . "`.`{$this->table}` SET ";
            $query_string = "";

            foreach ($this->_keys as $i => $key) {
                $query_string .= "`{$key}` = :{$key}, ";
            }

            $query_string = trim($query_string);
            if (substr($query_string, -1) === ',') {
                $query_string = substr($query_string, 0, -1);
            }

            $sql .= $query_string . " WHERE `id` = '{$id}'";
            return $this->prepareAndExecute($sql);
        }
        return false;
    }

    public function remove ($id) {
        $this->rawQuery("DELETE FROM `{$this->table}` WHERE `id` = '{$id}';");
    }

    public function rawQuery ($sql) {
        try {
            $pdo = self::$_conn->query($sql);
            $pdo->setFetchMode(\PDO::FETCH_ASSOC);
        } catch (\PDOException $e) {
            DebugLog::instance('DB')->error($e, 'db_query_' . $this->table);
            return array();
        }
        return $pdo->fetchAll();
    }

    //
    //  GETTERS
    //
    public function getColumns () {
        return $this->table_cols;
    }

    public function getLastInsertID () {
        return $this->_last_insert_id;
    }

    public function getRecord ($id) {
        $this->_id = $id;
        $response = $this->rawQuery("SELECT * FROM `{$this->table}` WHERE `id` = '{$id}'");
        $this->_results = $response[0];
    }

    public function getResults () {
        return $this->_results;
    }

    public function close () {
        $this->setDefaults();
    }

    //
    //  PROTECTED FUNCTIONS
    //
    protected function initColumns () {
        $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" . self::$_credentials['dbname'] . "' AND TABLE_NAME = '{$this->table}';";
        $response = $this->rawQuery($sql);
        if (!empty($response)) {
            return $this->parseColumns($response);
        }
        return array();
    }

    //
    //  PRIVATE FUNCTIONS
    //
    private function setDataBinding () {
        $this->_keys = array_keys($this->data);
        foreach ($this->data as $k => $v) {
            $this->_values[':' . $k] = $v;
        }
    }

    private function prepareAndExecute ($sql) {
        try {
            $q = self::$_conn->prepare($sql);
            $q->setFetchMode(\PDO::FETCH_ASSOC);
            if ($q->execute($this->_values)) {
                while ($r = $q->fetch()) {
                    $this->_results[] = $r;
                }
                $this->_last_insert_id = self::$_conn->lastInsertId();
                return true;
            } else {
                DebugLog::instance('DB')->error('Failed to execute', 'db_' . $this->table);
            }
        } catch (\PDOException $e) {
            DebugLog::instance('DB')->error($e, 'db_' . $this->table);
        }
        return false;
    }

    private function checkCols ($array) {
        foreach ($array as $col => $val) {
            if (!in_array($col, $this->table_cols)) {
                unset($array[$col]);
            }
        }
        return $array;
    }

    private static function setCredentials () {
            // I actually use a config file here, instead of hard coding
            self::$_credentials = array(
                'host' => '',
                'dbname' => '',
                'username' => '',
                'password' => ''
            );
    }

    private function parseColumns ($cols) {
        $array = array();
        foreach ($cols as $index => $col_array) {
            $array[] = $col_array['COLUMN_NAME'];
        }
        return $array;
    }

    private function setDefaults () {
        $this->data = array();
        $this->table_cols = array();
        $this->table = '';
        self::$_conn = null;
        $this->_keys = array();
        $this->_values = array();
        $this->_last_insert_id = -1;
        $this->_results = array();
    }
}

Then for each table, create a class that extends the class above. For example, lets say we have a users table:

class UsersTable extends DB {
    public function __construct () {
        // Parent constructor creates the DB connection
        parent::__construct();
        // Now let's set the desired table based on this class
        $this->table = "users";
        // Set the table columns, for mysql column validation
        $this->table_cols = $this->initColumns();
    }
}

Usage is than as simple as:

$table = new UsersTable();
$table->insert($record);

insert form data with more columns into mysql database from php page u...

php mysql pdo sql-insert html-form
Rectangle 27 1

You could always use a PDO wrapper class, I use the class below to handle most of my PDO queries:

class DB {
    protected
        // Return from mysql statement
        $data = array(),
        // Used for checking whether something was added to the JSON object and remove it if the table column doens't exist
        $table_cols = array(),
        // Storing the table name we are working with
        $table = '';
    protected static
        // PDO connection to the DB
        $_conn = null,
        // The DB credentials retrieved from the ini file
        $_credentials = array ();
    private
        $_id = -1,
        $_keys = array(),
        $_values = array(),
        $_last_insert_id = -1,
        $_results = array();

    //
    //  PUBLIC FUNCTIONS
    //
    public function __construct () {
        if (self::$_conn === null) {
            self::setCredentials();
            try {
                self::$_conn = new \PDO("mysql:host=" . self::$_credentials['host'] . ";dbname=" . self::$_credentials['dbname'] , self::$_credentials['username'], self::$_credentials['password']);
            } catch (\PDOException $e) {
                DebugLog::instance('DB')->error($e, 'db_connection');
            }
        }
    }

    public function insert ($data) {
        $data = $this->checkCols($data);
        // Allows us to quickly clone data by removing the id and inserting as a new record
        if (isset($data['id'])) {
            unset($data['id']);
        }
        $this->data = $data;
        $this->setDataBinding();
        $sql = "INSERT INTO `" . self::$_credentials['dbname'] . "`.`{$this->table}` (`" . implode('`, `', $this->_keys) . "`) VALUES (:" . implode(', :', $this->_keys) . ");";
        return $this->prepareAndExecute($sql);
    }

    public function update ($data) {
        $data = $this->checkCols($data);
        if (!isset($data['id'])) {
            // Houston we have a problem, there needs to be an id to update a record
            DebugLog::instance('DB')->error("No ID set for Update: " . implode(', ', array_keys($data)), 'db_id_' . $this->table);
        } else {
            // We need to unset the id because it shouldn't be in the data binding
            // But we still hold onto it for the where clause
            $id = $data['id'];
            unset($data['id']);
            $this->data = $data;

            $this->setDataBinding();

            $sql = "UPDATE `" . self::$_credentials['dbname'] . "`.`{$this->table}` SET ";
            $query_string = "";

            foreach ($this->_keys as $i => $key) {
                $query_string .= "`{$key}` = :{$key}, ";
            }

            $query_string = trim($query_string);
            if (substr($query_string, -1) === ',') {
                $query_string = substr($query_string, 0, -1);
            }

            $sql .= $query_string . " WHERE `id` = '{$id}'";
            return $this->prepareAndExecute($sql);
        }
        return false;
    }

    public function remove ($id) {
        $this->rawQuery("DELETE FROM `{$this->table}` WHERE `id` = '{$id}';");
    }

    public function rawQuery ($sql) {
        try {
            $pdo = self::$_conn->query($sql);
            $pdo->setFetchMode(\PDO::FETCH_ASSOC);
        } catch (\PDOException $e) {
            DebugLog::instance('DB')->error($e, 'db_query_' . $this->table);
            return array();
        }
        return $pdo->fetchAll();
    }

    //
    //  GETTERS
    //
    public function getColumns () {
        return $this->table_cols;
    }

    public function getLastInsertID () {
        return $this->_last_insert_id;
    }

    public function getRecord ($id) {
        $this->_id = $id;
        $response = $this->rawQuery("SELECT * FROM `{$this->table}` WHERE `id` = '{$id}'");
        $this->_results = $response[0];
    }

    public function getResults () {
        return $this->_results;
    }

    public function close () {
        $this->setDefaults();
    }

    //
    //  PROTECTED FUNCTIONS
    //
    protected function initColumns () {
        $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '" . self::$_credentials['dbname'] . "' AND TABLE_NAME = '{$this->table}';";
        $response = $this->rawQuery($sql);
        if (!empty($response)) {
            return $this->parseColumns($response);
        }
        return array();
    }

    //
    //  PRIVATE FUNCTIONS
    //
    private function setDataBinding () {
        $this->_keys = array_keys($this->data);
        foreach ($this->data as $k => $v) {
            $this->_values[':' . $k] = $v;
        }
    }

    private function prepareAndExecute ($sql) {
        try {
            $q = self::$_conn->prepare($sql);
            $q->setFetchMode(\PDO::FETCH_ASSOC);
            if ($q->execute($this->_values)) {
                while ($r = $q->fetch()) {
                    $this->_results[] = $r;
                }
                $this->_last_insert_id = self::$_conn->lastInsertId();
                return true;
            } else {
                DebugLog::instance('DB')->error('Failed to execute', 'db_' . $this->table);
            }
        } catch (\PDOException $e) {
            DebugLog::instance('DB')->error($e, 'db_' . $this->table);
        }
        return false;
    }

    private function checkCols ($array) {
        foreach ($array as $col => $val) {
            if (!in_array($col, $this->table_cols)) {
                unset($array[$col]);
            }
        }
        return $array;
    }

    private static function setCredentials () {
            // I actually use a config file here, instead of hard coding
            self::$_credentials = array(
                'host' => '',
                'dbname' => '',
                'username' => '',
                'password' => ''
            );
    }

    private function parseColumns ($cols) {
        $array = array();
        foreach ($cols as $index => $col_array) {
            $array[] = $col_array['COLUMN_NAME'];
        }
        return $array;
    }

    private function setDefaults () {
        $this->data = array();
        $this->table_cols = array();
        $this->table = '';
        self::$_conn = null;
        $this->_keys = array();
        $this->_values = array();
        $this->_last_insert_id = -1;
        $this->_results = array();
    }
}

Then for each table, create a class that extends the class above. For example, lets say we have a users table:

class UsersTable extends DB {
    public function __construct () {
        // Parent constructor creates the DB connection
        parent::__construct();
        // Now let's set the desired table based on this class
        $this->table = "users";
        // Set the table columns, for mysql column validation
        $this->table_cols = $this->initColumns();
    }
}

Usage is than as simple as:

$table = new UsersTable();
$table->insert($record);

insert form data with more columns into mysql database from php page u...

php mysql pdo sql-insert html-form
Rectangle 27 1

As long as your array has the 25 values in the same order as the table you can use unnamed parameters and lazy binding See PDO info

$sql ="INSERT INTO table_name VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,)";
$stmt = $dbh->prepare($sql); 
$stmt->execute($array);

insert form data with more columns into mysql database from php page u...

php mysql pdo sql-insert html-form
Rectangle 27 1

As long as your array has the 25 values in the same order as the table you can use unnamed parameters and lazy binding See PDO info

$sql ="INSERT INTO table_name VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,)";
$stmt = $dbh->prepare($sql); 
$stmt->execute($array);

insert form data with more columns into mysql database from php page u...

php mysql pdo sql-insert html-form
Rectangle 27 5

Short description from the page:

This script allows to use images (PNGs or JPGs) with alpha-channels. The alpha-channel can be either supplied as separate 8-bit PNG ("mask"), or, for PNGs, also an internal alpha-channel can be used. For the latter, the GD 2.x extension is required.

Specifying a separate mask image has several advantages: - no GD required. - Better quality (full 8-bit alpha channel, whereas GD internally only supports 7-bit alpha channels) - much faster (extraction of embedded alpha-channel has to be done pixel-wise)

function Image(string file, float x, float y [, float w [, float h [, string type [, mixed link [, boolean isMask [, int maskImg]]]]]])

Same parameters as for original Image()-method, but without a type parameter.

Insert PNG with alpha channel using FPDF (PHP) - Stack Overflow

php png fpdf
Rectangle 27 10

I'm not sure. The web page has to fit into the regular page hierarchy, so I don't think it's possible.

No problem. I should have been more specific and said custom page template. You should be able to then select the template's name from a drop-down list in WP-Admin when you create a new page.

I have implemented it and it works way better than I imagined. I love WordPress.

Inserting custom PHP code into a certain WordPress page - Stack Overfl...

php wordpress content-management-system
Rectangle 27 5

Check that request is post before inserting something:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $type = $_POST["wheretopost"];
    $title = $_POST["title"];
    $body = $_POST["txtarea"];
    $date = date("F j, Y");

    $sql = "INSERT INTO `yoyo`.`posts` (`id`, `type`, `title`, `body`, `date`) VALUES (NULL, '$type', '$title', '$body', '$date');";
    mysql_query($sql);
}

mysql - Refreshing or opening page inserts empty data into my database...

php mysql html forms
Rectangle 27 3

Youre trying to use 2 different MySQL interfaces at the same time. The mysql_* family of functions use the ext/mysql extension... The prepared statement stuff is PDO. You need to choose one or the other. Since PDO is really the way to go ill give you an example with that:

$db = new PDO($dsn, $user, $password);

try {
   $stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
   if($stmt->execute(array(':first_name' => $first_name))) {
      echo "1 record added";
   }

} catch (PDOException $e) {
  die('Error: ' . $e->getMessage());

}

The docs on the Mysql DSN (the first argument to the PDO constructor) can be found here.

Thanks. I'm on my way again. I guess this wasn't mentioned (or it was assumed I'd know) in my post yesterday.

Yeah it was probably assumed youd not just copy and paste, but rather go and investigate the Docs for PDO and then realize its a completely different extension with a different interface from the examples found there.

Why won't this PHP script insert form data in MySQL db? - Stack Overfl...

php mysql
Rectangle 27 3

Youre trying to use 2 different MySQL interfaces at the same time. The mysql_* family of functions use the ext/mysql extension... The prepared statement stuff is PDO. You need to choose one or the other. Since PDO is really the way to go ill give you an example with that:

$db = new PDO($dsn, $user, $password);

try {
   $stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
   if($stmt->execute(array(':first_name' => $first_name))) {
      echo "1 record added";
   }

} catch (PDOException $e) {
  die('Error: ' . $e->getMessage());

}

The docs on the Mysql DSN (the first argument to the PDO constructor) can be found here.

Thanks. I'm on my way again. I guess this wasn't mentioned (or it was assumed I'd know) in my post yesterday.

Yeah it was probably assumed youd not just copy and paste, but rather go and investigate the Docs for PDO and then realize its a completely different extension with a different interface from the examples found there.

Why won't this PHP script insert form data in MySQL db? - Stack Overfl...

php mysql
Rectangle 27 3

Youre trying to use 2 different MySQL interfaces at the same time. The mysql_* family of functions use the ext/mysql extension... The prepared statement stuff is PDO. You need to choose one or the other. Since PDO is really the way to go ill give you an example with that:

$db = new PDO($dsn, $user, $password);

try {
   $stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
   if($stmt->execute(array(':first_name' => $first_name))) {
      echo "1 record added";
   }

} catch (PDOException $e) {
  die('Error: ' . $e->getMessage());

}

The docs on the Mysql DSN (the first argument to the PDO constructor) can be found here.

Thanks. I'm on my way again. I guess this wasn't mentioned (or it was assumed I'd know) in my post yesterday.

Yeah it was probably assumed youd not just copy and paste, but rather go and investigate the Docs for PDO and then realize its a completely different extension with a different interface from the examples found there.

Why won't this PHP script insert form data in MySQL db? - Stack Overfl...

php mysql
Rectangle 27 3

Youre trying to use 2 different MySQL interfaces at the same time. The mysql_* family of functions use the ext/mysql extension... The prepared statement stuff is PDO. You need to choose one or the other. Since PDO is really the way to go ill give you an example with that:

$db = new PDO($dsn, $user, $password);

try {
   $stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
   if($stmt->execute(array(':first_name' => $first_name))) {
      echo "1 record added";
   }

} catch (PDOException $e) {
  die('Error: ' . $e->getMessage());

}

The docs on the Mysql DSN (the first argument to the PDO constructor) can be found here.

Thanks. I'm on my way again. I guess this wasn't mentioned (or it was assumed I'd know) in my post yesterday.

Yeah it was probably assumed youd not just copy and paste, but rather go and investigate the Docs for PDO and then realize its a completely different extension with a different interface from the examples found there.

Why won't this PHP script insert form data in MySQL db? - Stack Overfl...

php mysql
Rectangle 27 4

According to this page you're close. But put all the values into your select. Something like:

insert into scores (score, difficulty, playerid )
    select TheScoreThatImProviding, TheDifficultyThatImProviding, player.id 
      from player where uniqueDeviceId = TheUniqueIdThatImProviding

php - MySQL - Combining INSERT, VALUES, and SELECT? - Stack Overflow

php android mysql