Web Developer
- Joined
- Oct 24, 2009
- Messages
- 536
- Reaction score
- 217
This video shows you exactly how to create your own function to quickly insert data into an MySQL database without having to keep typing out mysql_query( "INSERT..." etc every time.
My cursor can not be seen in the video and I am not sure why.
I hope it helped.
<?php
/*
This function will enable you to quickly insert values into an MySQL database.
DATABASE STRUCTURE:
-------------------------------------------------------------
- FIELD - TYPE - AUTO INCREMENT - EXTRA -
- id - int(11) - YES - PRIMARY KEY -
- user - varchar(25) - NO - -
- pass - varchar(32) - NO - -
- email - varchar(150) - NO - -
-------------------------------------------------------------
Coded by Mark Eriksson
*/
@mysql_connect( "localhost", "root", "markeriksson" ) or die( "Can not connect to MySQL Database." );
@mysql_select_db( "test_insert" ) or die( "Can not find MySQL database." );
function insert( $table, $data )
{
$fields = array_keys( $data );
$values = array_map( "mysql_real_escape_string", array_values( $data ) );
@mysql_query( "INSERT INTO `" . $table . "` (`" . implode( "`,`", $fields ) . "`) VALUES ('" . implode( "','", $values ) . "');" ) or die( "Can not execute MySQL query." );
}
insert( "user", array( "user" => "Mark Eriksson",
"pass" => md5( "markeriksson" ),
"email" => "me@mark-eriksson.com"
) );
echo "<font color=\"green\">User inserted into database successfully!</font>";
?>
<?php
// db() has all mysqli functions.
$db = new db();
$db->conn();
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$username = cleanfordb($username);
// other sanitization functions here
$db->q("INSERT INTO users (username, password, email) VALUES ('$username', md5('$password'), '$email');");
$db->close();
echo "Registration successful.";
?>
I hate to say it, but you're not using a good example of OOP or MySQLi.PHP:<?php // db() has all mysqli functions. $db = new db(); $db->conn(); $username = $_POST['username']; $password = $_POST['password']; $email = $_POST['email']; $username = cleanfordb($username); // other sanitization functions here $db->q("INSERT INTO users (username, password, email) VALUES ('$username', md5('$password'), '$email');"); $db->close(); echo "Registration successful."; ?>
$db = new mysqli('host', 'user', 'pass', 'db_name');
if($stmt = $db->prepare('INSERT INTO users (username, password, email) VALUES(?,?,?)') )
{
$stmt->bind_param('sss', $_POST['username'], md5($_POST['password']), $_POST['email']);
$stmt->execute();
$stmt->close();
}
$db->close();