Improve sql query function performance - php

I'm new to PHP, and was wondering if anyone could give an example of how to improve this code?
public function createContent($title, $content, $category_id){
try {
$user_id = $_SESSION["user_id"];
if(!$user_id){
return(false);
}
$sql = "INSERT INTO content (title, content, user_id, category_id)
VALUES (:title, :content, :user_id, :category_id)";
$query = $this->_db->prepare($sql);
$execute_array = array(
':title' => $title,
':content' => $content,
':user_id' => $user_id,
':category_id' => $category_id
);
$query->execute($execute_array);
}
catch(PDOException $e){
echo $e->getMessage();
}
}

what do you mean with improve??
if your table only have "title, content, user_id, category" you can do it like:
"insert into content (:title, :content,:user_id, :category)";
but the best advice is to prepare statement, that will help you to avoid sql-injection

Related

Query conditions to insert data from a form

What I'm trying to do is:
If the age input in my form = 28, 30, 25 or 21 then I want to auto insert value 8 in the column (VE), else keep it empty. Is this the right way to do that?
if($form_data->action == 'Insert')
{
$age=array(28, 30, 25, 21);
$age_str=implode("','", $age);
if($form_data->age == $age_str){
$query="INSERT INTO tbl
(VE) VALUE ('8') WHERE id= '".$form_data->id."'
";
$statement = $connect->prepare($query);
$statement->execute();
}
$data = array(
':date' => $date,
':first_name' => $first_name,
':last_name' => $last_name,
':age' => $age
);
$query = "
INSERT INTO tbl
(date, first_name, last_name, age) VALUES
(:date, :first_name, :last_name, :age)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$message = 'Data Inserted';
}
}
Also, how do I insert the new row with the row id from the other form data going into tbl?
Use php's in_array instead of trying to compare a string. To get the id of the query where you insert the form data, you can return the id of the insert row from your prepared statement.
if ($form_data->action == 'Insert') {
// assuming $age, $date, $first_name, $last_name
// already declared prior to this block
$data = array(
':date' => $date,
':first_name' => $first_name,
':last_name' => $last_name,
':age' => $age
);
$query = "
INSERT INTO tbl
(date, first_name, last_name, age) VALUES
(:date, :first_name, :last_name, :age)
";
$statement = $connect->prepare($query);
if ($statement->execute($data)) {
$message = 'Data Inserted';
// $id is the last inserted id for (tbl)
$id = $connect->lastInsertID();
// NOW you can insert your child row in the other table
$ages_to_insert = array(28, 30, 25, 21);
// in_array uses your array...so you don't need
// if($form_data->age == $age_str){
if (in_array($form_data->age, $ages_to_insert)) {
$query="UPDATE tbl SER VE = '8' WHERE id= '".$id."'";
$statement2 = $connect->prepare($query);
$statement2->execute();
}
}
}

SQL database insert with select

I understand that there is a way to insert a constant from select statement which i found the source from here such as:
INSERT INTO MyTable(ColA,ColB,ColC)
SELECT 1,colBB,colCC FROM MyTable2
But is it possible to add an user input values (using php) instead of a constant value as well? If possible provide with example. Thanks in advance.
UPDATED:
I tried to create a simple web page however there are some syntax error that i have no idea to solve it:
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\webservice\result.php on line 10
Below are my codes:
<?php
//start a session
require("config.inc.php");
$username = $_SESSION["username"];
if(!empty($_POST)){
//check if user choose non-required drop down list
if(empty($_POST['subcategory'])){
if(empty($_POST['yearofstudy'])) {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty";
$query_params = array(
':faculty' => $_POST['category'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
else {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty AND year_of_study = :yearofstudy";
$query_params = array(
':faculty' => $_POST['category'],
'yearofstudy' => $_POST['yearofstudy'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
}
else {
if(empty($_POST['yearofstudy'])) {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty AND course = :course";
$query_params = array(
':faculty' => $_POST['category'],
':course' => $_POST['subcategory'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
else {
$query = "INSERT INTO comments ( username, title, message, tousername )
SELECT :username, :title, :message, username
FROM utarstudents WHERE faculty = :faculty AND year_of_study = :yearofstudy AND course = :course";
$query_params = array(
':faculty' => $_POST['category'],
'yearofstudy' => $_POST['yearofstudy'],
':course' => $_POST['subcetagory'],
':username' =>$username,
':title' =>$_POST['title'],
'message' =>$_POST['message']
);
}
}
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
}
Here is an edited code snippet of mine that accomplishes what you are trying to. So in my form file I have something like this for contributing to a project:
<form name="contribute" method="post" action="contribute-dbquery.php" onsubmit="return validateForm()">
First Name:
<input name="nameValue" type="text" size="40" maxlength="12" required/>
<input name="Submit" type="submit" value="Add"/>
</form>
So what it says is when Add is goto Tcontribute-dbquery.php with the value of nameValue. Then in my contribute-dbquery.php I assign nameValue from the form to $name and then assign inset it into my database. I assigned it to a variable because I used it on that page as well. You can inset it right into the database if you want.
$name = $_POST['nameValue'];
$insert_sql = "INSERT INTO mastertable (name) VALUES (' " . $name . " ')";
If this helps mark it as answered. Let me know if you need any help.

How to bind PHP prepare and execute statement properly?

I have a function that inserts or updates a value in the database.
I am using a prepare and execute statement and I want to match my function's ELSE-clause to match the prepared statement.
In my ELSE-clause I have one more value (i.e. $id), so I'm not sure if I can assign it in the execute array.
function insert_value($item_name, $description, $supplier_code, $cost, $sell_price,$num_on_hand, $reorder_point, $back_order, $id=0)
{
$connection = db_connect();
if($id==0)
{
$sql = 'INSERT INTO inventory (itemName, description, supplierCode, cost, price, onHand, reorderPoint, backOrder)
VALUES(:itemName, :description, :supplierCode, :cost, :price, :onHand, :reorderPoint, :backOrder);';
}
else
{
//NEED TO CHANGE THIS PART
$sql = "UPDATE inventory SET itemName='$item_name', description='$description', supplierCode='$supplier_code',
cost='$cost', price='$sell_price', onHand='$num_on_hand', reorderPoint='$reorder_point', backOrder='$back_order'
WHERE id='$id'";
}
$prepare = $connection->prepare($sql);
$prepare->execute(array( // AND THIS PART
":itemName" => $item_name,
":description" => $description,
":supplierCode" => $supplier_code,
":cost" => $cost,
":price" => $sell_price,
":onHand" => $num_on_hand,
":reorderPoint" => $reorder_point,
":backOrder" => $back_order,
));
}
Something like:
function insert_value($item_name, $description, $supplier_code, $cost, $sell_price,$num_on_hand, $reorder_point, $back_order, $id=0){
$connection = db_connect();
$arr = array(":itemName" => $item_name,
":description" => $description,
":supplierCode" => $supplier_code,
":cost" => $cost,
":price" => $sell_price,
":onHand" => $num_on_hand,
":reorderPoint" => $reorder_point,
":backOrder" => $back_order);
if($id==0){
$sql = 'INSERT INTO inventory (itemName, description, supplierCode, cost, price, onHand, reorderPoint, backOrder)
VALUES(:itemName, :description, :supplierCode, :cost, :price, :onHand, :reorderPoint, :backOrder)';
}else{
$sql = "UPDATE inventory SET itemName=:itemName, description=:description, supplierCode=:supplierCode,
cost=:cost, price=:price, onHand=:onHand, reorderPoint=:reorderPoint, backOrder=:backOrder
WHERE id=:id";
$arr[":id"] = $id;
}
$prepare = $connection->prepare($sql);
$prepare->execute($arr);
}
Also you might want to check (if you don't do this already) to see if $connection is valid otherwise you might get errors once it gets to prepare/execute.

How to insert data using wpdb

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', )");

pdo prepared inserts failing

I cannot get the code below to insert data.
<?php
$xml_gsm = null;
try {
// normally an include
$data = new PDO(MYSQL_DSN, MYSQL_USERNAME, MYSQL_PASSWORD);
$data->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$stmt = $data->prepare("INSERT INTO tbl_sms_queue VALUES (fk_userId, fk_campaignId, message_content, gsm) VALUES (:userId, :campId, :message, :gsm);");
foreach($gsms as $number):
$xml_gsm .= "<gsm messageId='" . $data->lastInsertId() . "'>$number</gsm>";
$stmt->execute(array(':userId'=>$userId, ':campId'=>$campId, ':message'=>$message, ':gsm'=>$number));
print_r($data->errorInfo());
endforeach;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
PDO errorInfo reports 00000 but nothing is inserted, the user has full crud permissions, $gsms is an array of numbers.
I have looked at other answers and nothing applies, i am now stuck on this one and any help is appreciated.
Fixed:
I had:
$stmt = $data->prepare("INSERT INTO tbl_sms_queue VALUES (fk_userId, fk_campaignId, message_content, gsm) VALUES (:userId, :campId, :message, :gsm);");
instead of:
$stmt = $data->prepare("INSERT INTO tbl_sms_queue (fk_userId, fk_campaignId, message_content, gsm) VALUES (:userId, :campId, :message, :gsm);");

Categories