How to insert data using wpdb - php

I have wriiten as following
$name="Kumkum";
$email="kumkum#gmail.com";
$phone="3456734567";
$country="India";
$course="Database";
$message="hello i want to read db";
$now = new DateTime();
$datesent=$now->format('Y-m-d H:i:s');
global $wpdb;
$sql = $wpdb->prepare(
"INSERT INTO `wp_submitted_form` (`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`) values ("
$name, $email, $phone, $country, $course, $message, $datesent. ')")';
$wpdb->query($sql);
It's not working... It throws error... Please help me in correcting it.

Use $wpdb->insert().
$wpdb->insert('wp_submitted_form', array(
'name' => 'Kumkum',
'email' => 'kumkum#gmail.com',
'phone' => '3456734567', // ... and so on
));
Addition from #mastrianni:
$wpdb->insert sanitizes your data for you, unlike $wpdb->query which requires you to sanitize your query with $wpdb->prepare. The difference between the two is $wpdb->query allows you to write your own SQL statement, where $wpdb->insert accepts an array and takes care of sanitizing/sql for you.

Just use wpdb->insert(tablename, coloumn, format) and wp will prepare that's query
<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
"name" => $name,
"email" => $email,
"phone" => $phone,
"country" => $country,
"course" => $course,
"message" => $message,
"datesent" => $now ,
));
?>

Try this
I recently leaned about $wpdb->prepare HERE and added into our Free Class Booking plugin, plugin approved on wordpress.org and will live soon:
global $wpdb;
$tablename = $wpdb->prefix . "submitted_form";
$name = "Kumkum"; //string value use: %s
$email = "kumkum#gmail.com"; //string value use: %s
$phone = "3456734567"; //numeric value use: %d
$country = "India"; //string value use: %s
$course = "Database"; //string value use: %s
$message = "hello i want to read db"; //string value use: %s
$now = new DateTime(); //string value use: %s
$datesent = $now->format('Y-m-d H:i:s'); //string value use: %s
$sql = $wpdb->prepare("INSERT INTO `$tablename` (`name`, `email`, `phone`, `country`, `course`, `message`, `datesent`) values (%s, %s, %d, %s, %s, %s, %s)", $name, $email, $phone, $country, $course, $message, $datesent);
$wpdb->query($sql);
Thanks
-Frank

The recommended way (as noted in codex):
$wpdb->insert( $table_name, array('column_name_1'=>'hello', 'other'=> 123), array( '%s', '%d' ) );
So, you'd better to sanitize values - ALWAYS CONSIDER THE SECURITY.

You have to check your quotes properly,
$sql = $wpdb->prepare(
"INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ($name, $email, $phone, $country, $course, $message, $datesent)");
$wpdb->query($sql);
OR you can use like,
$sql = "INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ($name, $email, $phone, $country, $course, $message, $datesent)";
$wpdb->query($sql);
Read http://codex.wordpress.org/Class_Reference/wpdb

Problem in your SQL :
You can construct your sql like this :
$wpdb->prepare(
"INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ('$name', '$email', '$phone', '$country',
'$course', '$message', '$datesent')"
);
You can also use $wpdb->insert()
$wpdb->insert('table_name', input_array())

global $wpdb;
$insert = $wpdb->query("INSERT INTO `front-post`(`id`, `content`) VALUES ('$id', '$content')");

$wpdb->query("insert into ".$table_name." (name, email, country, country, course, message, datesent) values ('$name','$email', '$phone', '$country', '$course', '$message', )");

Related

How to bind multiple params to prepare statement [duplicate]

Is there's an easy way of binding multiple values in PDO without repitition ? Take a look at the following code :
$result_set = $pdo->prepare("INSERT INTO `users` (`username`, `password`, `first_name`, `last_name`) VALUES (:username, :password, :first_name, :last_name)");
$result_set->bindValue(':username', '~user');
$result_set->bindValue(':password', '~pass');
$result_set->bindValue(':first_name', '~John');
$result_set->bindValue(':last_name', '~Doe');
$result_set->execute();
Here, I binded values in a repepeated way which is 4 times. So is there's an easy way of binding multiple values in PDO ?
You can always bind values within the arguments of execute() as long as you're fine with the values being treated as PDO::PARAM_STR (string).
$result_set = $pdo->prepare("INSERT INTO `users` (`username`, `password`, `first_name`, `last_name`) VALUES (:username, :password, :first_name, :last_name)");
$result_set->execute(array(
':username' => '~user',
':password' => '~pass',
':first_name' => '~John',
':last_name' => '~Doe'
));
You can use the array passed just like any array:
$user = "Nile";
$pdo->execute(array(":user" => $user));
If you want to bind based on type (string, int, etc), then no. If you're fine with binding everything as a string:
$stmt = $db->prepare("...");
$stmt->execute(array(
'foo' => 'bar',
'something' => 'else',
'third' => 'thing',
));
To truly never type anything twice, you can use an array to supply the data, and use a function on that same array to output the binding portion of the MySQL query. For example:
function bindFields($fields){
end($fields); $lastField = key($fields);
$bindString = ' ';
foreach($fields as $field => $data){
$bindString .= $field . '=:' . $field;
$bindString .= ($field === $lastField ? ' ' : ',');
}
return $bindString;
}
The data and column names come from a single associative array ($data). Then, use bindFields($data) to generate a string of column = :column pairs to concatenate into the MySQL query:
$data = array(
'a_column_name' => 'column data string',
'another_column_name' => 'another column data string'
);
$query = "INSERT INTO tablename SET" . bindFields($data);
$result = $PDO->prepare($query);
$result->execute($data);
bindFields($data) output:
a_column_name=:a_column_name,another_column_name=:another_column_name

PHP Can't get the ID of Last Record Inserted

I'm trying to get the ID of the last record inserted in my phpMyAdmin table, but I only get 0's so far.
I have tried almost everything (for example the solution on this answer: a link or what this page recommend : a link ) but I can't get it working.
My table has a column id that is the primary key and is marked as AUTO_INCREMENT.
I use a function query that make the connection to the database and then execute the queries:
function query($sql) {
$conn = mysqli_connect ( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
// Check connection
if (mysqli_connect_errno ()) {
echo 'connection failed: ' . mysqli_connect_error ();
}
// Check if the server is alive
if (mysqli_ping ( $conn )) {
// echo 'Connection is ok';
} else {
echo 'Error: ' . mysqli_error ( $dbc );
}
$sql = mysqli_query ( $conn, $sql );
$last_id = mysqli_insert_id( $conn );
$num_rows = mysqli_num_rows ( $sql );
$result = mysqli_fetch_assoc ( $sql );
return array (
"num_rows" => $num_rows,
"result" => $result,
"sql" => $sql,
"last_id" => $last_id
);
mysqli_close($conn);
}
Then I have another function from where I called the first one to execute the query:
function reg_shp_add($address_type, $company_name, $country, $state, $city, $zip, $street_name, $street_number, $tel){
if($address_type=="residential"){
$my_address_type = "r";
}else{
$my_address_type = "c";
}
$this->query ( "INSERT INTO `Addresses` (`company_name`, `street_address`, `address_two`, `zip_code`, `city_name`, `state_id`, `country_id`, `phone_number`, `res_comm_add`, `date_entered`) VALUES ('$company_name', '$street_name', '$street_number', '$zip', '$city', '$state', '$country', '$tel', '$my_address_type', CURRENT_TIMESTAMP)" );
$address_id = $sql ['user_id'];
$customer_id = $_COOKIE['userId'];
$this->query ( "INSERT INTO `Cust_address_type` (`cust_id`, ` mail_address_id`, `address_type`) VALUES ('$customer_id', '$address_id', 'Shipping')" );
return 'Address was saved.';
}
I first tried to retrieve the last id from my reg_shp_add function, but I guess it must be done from the first one.
Can anybody help me please?
I test your code and the function mysqli_insert_id work correctly with me ( ["last_id"]=> int(8) ). But the problem is in your second function, on the data retrieval ;
$this->query ( "INSERT INTO `Addresses` (`company_name`, `street_address`, `address_two`, `zip_code`, `city_name`, `state_id`, `country_id`, `phone_number`, `res_comm_add`, `date_entered`) VALUES ('$company_name', '$street_name', '$street_number', '$zip', '$city', '$state', '$country', '$tel', '$my_address_type', CURRENT_TIMESTAMP)" );
$address_id = $sql ['user_id'];
Here the $sql variable is undefined, you miss to store the return value into $sql, like that :
$sql = $this->query ( "INSERT INTO `Addresses` (`company_name`, `street_address`, `address_two`, `zip_code`, `city_name`, `state_id`, `country_id`, `phone_number`, `res_comm_add`, `date_entered`) VALUES ('$company_name', '$street_name', '$street_number', '$zip', '$city', '$state', '$country', '$tel', '$my_address_type', CURRENT_TIMESTAMP)" );
$address_id = $sql ['user_id'];

bind_param() Issues

I am getting issues with the bind_param function. I will post all the information below.
Error:
Fatal error: Call to a member function bind_param() on a non-object in /home4/lunar/public_html/casino/blogpost.php on line 88
MySQL Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':user, :title, :message, :image, :category, NOW())' at line 1
Query:
$user = $_COOKIE['user'];
$title = $_POST['title'];
$message = $_POST['message'];
$image = $_POST['image'];
$category = $_POST['category'];
$stmt = $mysqli->prepare("INSERT INTO `lunar_casino`.`posts` (`id`, `by`, `title`, `message`, `image`, `category`, `date`) VALUES(NULL, :user, :title, :message, :image, :category, NOW())");
echo $mysqli->error;
$stmt->bind_param(":user", $user);
$stmt->bind_param(":title", $title);
$stmt->bind_param(":message", $message);
$stmt->bind_param(":image", $image);
$stmt->bind_param(":category", $category);
$stmt->execute();
if(!$stmt){
echo "<font color='red'><b>There has been an error with our database! Please contact the website administrator!</b></font><br /><br />";
echo $mysqli->error;
} else {
echo "<font color='green'><b>You have successfully added a blog post!</b></font><br /><br />";
}
Any ideas why its like this?
As Rocket Hazmat mentioned you can only use question marks as bind parameter place holder.
You should do something similar:
$stmt = $mysqli->prepare("INSERT INTO `lunar_casino`.`posts` (`id`, `by`, `title`, `message`, `image`, `category`, `date`) VALUES(NULL, ?, ?, ?, ?, ?, NOW())");
$stmt->bind_param("sssss", $user, $title, $message, $image, $category);
More details: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
$stmt->bind_param("sssss", $user, $title, $message, $image, $category);
on the first argument the s = string and i = integer. You need to specify which type of value you want to add to the database. If you want to add 5 values that are strings to the database then write 'sssss' if you want to insert 5 integers then write 'iiiii' if you have some integers values and some string values then you can adjust accordingly.
//so if your values are all strings then this would be correct :
$stmt->bind_param("sssss", $user, $title, $message, $image, $category);
//so if your values are all integers then this would be correct :
$stmt->bind_param("iiiii", $user, $title, $message, $image, $category);
//if the first 2 are integers and the other 3 strings then this would be correct :
$stmt->bind_param("iisss", $user, $title, $message, $image, $category);
and so on.

PDO prepare statement for inserting array into db issue

I am creating a user registration system using PDO, and am attempting to insert the users form data into a database table. Very simple, however the wrong value is entered into the database. The values entered into the database are :username, :password, :email_address, :city, etc, rather than the value passed to the function from my form. Any idea as to what I am doing wrong? I tried using bindParam and bindValue but had similar results, and based on other posts I concluded that using an array is the best way to do it. help!
function add_user($username, $password, $email, $fName, $lName, $address, $city, $state, $zip, $phone ) {
global $db;
$sql = "INSERT INTO alumni_user_info
(username, password, email_address, first, last, address, city, state, zip_code, phone)
VALUES
(':username', ':password', ':email_address', ':first', ':last', ':address', ':city', ':state', ':zip_code', ':phone')";
$sth = $db->prepare($sql);
$result = $sth -> execute(array(':username' => $username, ':password' => $password, ':email_address' => $email, ':first' => $fName, ':last' => $lName, ':address' => $address, ':city' => $city, ':state' => $state, ':zip_code' => $zip, ':phone' => $phone));
if ($sth->execute()) {
$success = "Registration successful";
return $success;
} else {
var_dump($result->errorInfo());
$success = "Registration failed";
return $success;
}
Do not use quotes for parameters. It will be escaped because you're binding parameters already.
$sql = "INSERT INTO alumni_user_info
(username, password, email_address, first, last, address, city, state, zip_code, phone)
VALUES
(:username, :password, :email_address, :first, :last, :address, :city, :state, :zip_code, :phone)";
If you do something like this ':username' PDO will treat it as string.

why email value stored as %email in mysql database?

I am so new in making project, so please don't mind. i created a code using php, html, css to store some data into mysql database. Everything is fine but the email value is stored as %email in the database. Can anybody help me please.
html code for email field:
<div class="row">
<div class="label">Email Id</div>
<div class="inputaddr">
<input type="text" id="email" required="required" class="detail" name="email"/>
</div>
<div class="label">Category</div>
<div class="inputmobile">
<input type="text" id="category" required="required" class="shortdetail" name="category"/>
</div>
</div> <!-- end of 5th row -->
.php file:
<?php
$conn = mysql_connect("localhost", "root", "");
$db = mysql_select_db('ssitdashboard', $conn) or die(mysql_error());
if(isset($_REQUEST['submit'])){
$fullname = $_POST['fullname'];
$fname = $_POST['fname'];
$mname = $_POST['mname'];
$raddr = $_POST['raddr'];
$laddr = $_POST['laddr'];
$email = $_POST['email'];
$sex = $_POST['sex'];
$dob = $_POST['dob'];
$bloodgroup = $_POST['bloodgroup'];
$mobile = $_POST['mobile'];
$rmobile = $_POST['rmobile'];
$category = $_POST['category'];
$usn = $_POST['usn'];
$branch = $_POST['branch'];
$sem = $_POST['sem'];
$eca = $_POST['eca'];
$year = $_POST['years'];
$quota = $_POST['quota'];
$que = "INSERT INTO personal_details(name, fname, mname, raddr, laddr, email, sex, dob, blood_group, mobile, rmobile, category, usn, branch, sem, eca, year, quota) VALUES ('$fullname', '$fname', '$mname', '$raddr', '$laddr', '%email', '$sex', '$dob', '$bloodgroup', '$mobile', '$rmobile', '$category', '$usn', '$branch', '$sem', '$eca', '$year', '$quota')";
if(mysql_query($que)){
// echo "<script>alert('You have registered successfully')</script>";
// echo "<script>window.open('http://www.ssit.edu.in')</script>";
header("Location:thankyou.html");
exit;
}
}
?>
In database the email field is taken as varchar(30)
You have a typo in your query, %email where you intended $email.
That being said, you should rip out all of this code and replace it with something that doesn't have gigantic SQL injection bugs in it. Either you must use mysql_real_escape_string on each and every $_POST value being inserted, or you should be using PDO.
Mistakes like this are a lot harder to make if you have parameterized queries. An example in PDO is:
# Using named data placeholders here
$pdo->prepare(
"INSERT INTO personal_details(name, fname, mname, raddr, laddr,
email, sex, dob, blood_group, mobile, rmobile, category, usn,
branch, sem, eca, year, quota)
VALUES (:fullname, :fname, :mname, :raddr, :laddr,
:email, :sex, :dob, :bloodgroup, :mobile, :rmobile, :category, :usn,
:branch, :sem, :eca, :year, :quota)";
# When executing you specify the data to be used. The same prepared statement can be
# executed many times with different data.
$pdo->execute(array('fullname' => $_POST['fullname'], 'fname' => $_POST['fname'], ...));
Try changing %email to $email in your SQL statement.
But, in addition, look into PDO, as this implementation is vulnerable to SQL Injection.
To elaborate on the PDO implementation, you could do something like this for your situation:
$username = "root";
$password = "";
$host = "localhost";
$dbname = "ssitdashboard";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}catch(PDOException $ex){
die("Failed to connect: ".$ex->getMessage());
}
Now you have a PDO connection stored in $db which you can query through. You may want to account for magic quotes if you're not using PHP 5.4, so keep that in mind.
Otherwise, create your query statement like so..
$query = "INSERT INTO personal_details ( name, fname, mname, raddr, laddr, email, sex, dob, blood_group, mobile, rmobile, category, usn, branch, sem, eca, year, quota ) VALUES ( :name, :fname, :mname, :raddr, :laddr, :email, :sex, :dob, :blood_group, :mobile, :rmobile, :category, :usn, :branch, :sem, :eca, :year, :quota )"
Afterwards, you want to bind the values from the $_POST variables to the parameters that have : in front of them (like :name). You do that like so:
$query_params = array( ':name' => $_POST['fullname'], ':fname' => $_POST['fname'], ':mname' => $_POST['mname'], ':raddr' => $_POST['raddr'], ':laddr' => $_POST['laddr'], ':email' => $_POST['email'], ':sex' => $_POST['sex'], ':dob' => $_POST['dob'], ':blood_group' => $_POST['bloodgroup'], ':mobile' => $_POST['mobile'], ':rmobile' => $_POST['rmobile'], ':category' => $_POST['category'], ':usn' => $_POST['usn'], ':branch' => $_POST['branch'], ':sem' => $_POST['sem'], ':eca' => $_POST['eca'], ':year' => $_POST['years'], ':quota' => $_POST['quota']);
Finally, now that you have the statement and the parameters, use the previously created $db variable to prepare and execute the statement.
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
Since we're just INSERTing variables into the database, that should be all that's needed. If you were SELECTing data though, you could do something like this AFTER you've done the above...
$rows = $statement->fetchAll();
And now you could refer to column headers within each $row of the database table by utilizing a foreach statement.
$bloodArray = array();
foreach($rows as $row){
if(isset($row['blood_group'])){
$bloodArray[] = $row['blood_group'];
}
}
Hope that helps out, sorry for the delay!
mistake is that i used %email in the query...

Categories