I have this variables :
$cliente = mysqli_real_escape_string($conn, htmlentities($_GET["cliente"]));
$metatickt = mysqli_real_escape_string($conn, htmlentities($_GET["metatickt"]));
$metaext = mysqli_real_escape_string($conn, htmlentities($_GET["metaext"]));
$metaenc = mysqli_real_escape_string($conn, htmlentities($_GET["metaenc"]));
$uf = mysqli_real_escape_string($conn, htmlentities($_GET["estado"]));
And I'm trying to do this query :
$queryInst = "INSERT meta_control (mes,cliente,meta_exit,meta_tickt,meta_enc,uf)"
. " VALUES (MONTH(NOW()),'" . $cliente . "','" . $metaext . "','" . $metatickt . "','" . $metaenc . "','" . $uf . "')";
mysqli_query($conn, $queryInst);
But when I check my db the only column that is not NULL is mes. What could be the cause to this?
You should have to use proper query. INSERT INTO
$queryInst = "INSERT INTO meta_control (mes,cliente,meta_exit,meta_tickt,meta_enc,uf)"
. " VALUES (MONTH(NOW()),'" . $cliente . "','" . $metaext . "','" . $metatickt . "','" . $metaenc . "','" . $uf . "')";
mysqli_query($conn, $queryInst);
You are probably getting an SQL error.
You should check for such errors using mysqli_error($conn) - http://php.net/manual/en/mysqli.error.php. In this case you probably have an error caused by the absence of the INTO keyword in your SQL query, which should be INSERT INTO ....
http://dev.mysql.com/doc/refman/5.7/en/insert.html
Related
It couldn't store the data to mysql. What to do? All variable and file name are correct.
<?php
require 'connection.php';
$conn = Connect();
$id =$conn->real_escape_string ($_POST['id']);
$name = $conn->real_escape_string ($_POST['name']);
$phone = $conn->real_escape_string ($_POST['phone']);
$address = $conn->real_escape_string ($_POST['address']);
$city = $conn->real_escape_string ($_POST['city']);
$zip = $conn->real_escape_string ($_POST['zip']);
$state = $conn->real_escape_string ($_POST['state']);
$item = $conn->real_escape_string ($_POST['item']);
$status = $conn->real_escape_string ($_POST['status']);
$enquiry_date = $conn->real_escape_string ($_POST['enquiry_date']);
$enquiry_user = $conn->real_escape_string ($_POST['enquiry_user']);
$query = "INSERT into enquiry
(id, name, phone, address, city, zip, state, item, status, enquiry_date, enquiry_user)
VALUES('" . $id . "','" . $name . "','" . $phone . "','" . $address . "','" . $city . "','" . $zip . "','" . $state . "','" . $item . "','" . $status . "','" . $enquiry_date . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo "Thank You For Contacting Us <br>";
$conn->close();
?>
As #Jeff said:
$query = "INSERT into enquiry
(id, name, phone, address, city,
zip, state, item, status, enquiry_date, enquiry_user)
VALUES('" . $id . "','" . $name . "','" . $phone . "','" . $address . "','"
. $city . "','" . $zip . "','" . $state . "','" . $item . "','"
$status . "','" . $enquiry_date . "','" . $enquiry_user . "')";
You were missing . "','" . $enquiry_user
I am fetching some row from mysql table and after fetch it I am inserting it in another database with similar type table. I want little changes in one filed of row and want insert fixed value in it instead of value that I have fetched first.
My current query is like below
while ($row = mysqli_fetch_array($questions))
$cat=1;
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `questions` (`option1`, `option2`, `option3`, `option4`, `correctans`, `question_text`, `cat_id`, `sub_cat_id`, `level_id`, `quesimage`) VALUES ('" . $row['option1'] . "', '" . $row['option2'] . "', '" . $row['option3'] . "','" . $row['option4'] . "','" . $row['correctans'] . "','" . $row['question_text'] . "','" . $row['cat_id'] . "','" . $row['sub_cat_id'] . "','" . $row['level_id'] . "','" . $row['quesimage'] . "');");
}
Now if I want put value 1 for $row['cat_id'] what should I change it in my code ? I have tried to use variable for it but its not working. Thanks
I'm trying to show an error while entering duplicates using php and mysql, but i'm not getting how to complete, please give an solution........
this is my code:
mysql_query(
"INSERT INTO productcost (product, productCategory, model, purchasePrice, mrp, customerPrice, marginCustomer, dealerPrice, marginDealer)
VALUES ('" . $_POST["product"] . "','" . $_POST["productCategory"] . "','" . $_POST["model"] . "','" . $_POST["purchasePrice"] . "','" . $_POST["mrp"] . "','" . $_POST["customerPrice"] . "','" . $_POST["marginCustomer"] . "','" . $_POST["dealerPrice"] . "', '" . $_POST["marginDealer"] . "')");
$current_id = mysql_insert_id();
if(!empty($current_id)) {
$message = "New Product Added Successfully";
}
}
You have to create unique key in productcost table , using unique fields like (product, productCategory, model). Now execute insert query, if there is a recode in the table return error . now you can handle error and give message.
try{
mysql_query("INSERT INTO productcost (product_key_id,product, productCategory,model,purchasePrice, mrp, customerPrice, marginCustomer, dealerPrice, marginDealer)
VALUES
('" . $_POST["created_product_id"] . "','" . $_POST["product"] . "','".$_POST["productCategory"] . "','" . $_POST["model"] . "','".$_POST["purchasePrice"] . "','" . $_POST["mrp"] . "','".$_POST["customerPrice"] . "','" . $_POST["marginCustomer"] . "','".$_POST["dealerPrice"] . "', '" . $_POST["marginDealer"] . "')");
return TRUE;
}
catch(Exception $e){
return FALSE;
}
or you can check is there a recode in table before insert
select count(*) as cc from doc_upload where product_key_id = $_POST["created_product_id"];
To show an error message while entering duplicates:
// First check there are same data available or not using a query by counting the row
$sqlCheck = "SELECT COUNT(`id`) WHERE product = '" . $_POST["product"] . "' AND productCategory = '" . $_POST["productCategory"] . "' AND model = '" . $_POST["model"] . "'"; // You have to add mroe thing in where clause
$CheckQuery = mysql_query($sqlCheck);
// if there is no duplicate data
//
if ($CheckQuery > 0) {
# code...
mysql_query(
"INSERT INTO productcost (product, productCategory, model, purchasePrice, mrp, customerPrice, marginCustomer, dealerPrice, marginDealer)
VALUES ('" . $_POST["product"] . "','" . $_POST["productCategory"] . "','" . $_POST["model"] . "','" . $_POST["purchasePrice"] . "','" . $_POST["mrp"] . "','" . $_POST["customerPrice"] . "','" . $_POST["marginCustomer"] . "','" . $_POST["dealerPrice"] . "', '" . $_POST["marginDealer"] . "')");
$current_id = mysql_insert_id();
if(!empty($current_id)) {
$message = "New Product Added Successfully";
}
} else {
$message = "Data is Duplicated";
}
Note : I'm Giving you an Example . this is how you have to check
duplicate data
I've got a syntax error in the following code, but I can't find it:
$tableSelect = $_POST["tableSelect"];
$companyName = $_POST["companyName"];
$telephone = $_POST["telephone"];
$fax = $_POST["fax"];
$email = $_POST["email"];
$address = $_POST["address"];
$postcode = $_POST["postcode"];
$category = $_POST["category"];
$contact = $_POST["contact"];
$contactTel = $_POST["contactTel"];
$contactEmail = $_POST["contactEmail"];
$sql = "INSERT INTO '" . $tableSelect . "' ('" . $companyName . "', '" . $telephone . "', '"
. $fax . "', '" . $email . "', '" . $address . "','" . $postcode . "', '" . $category . "',
'" . $contact . "', '" . $contactTel . "', '" . $contactEmail . "')";
mysqli_query($con,$sql);
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
Cheers!
EDIT: I have modified the code to this:
$sql = "INSERT INTO `" . $tableSelect . "` (name, telephone, fax, email, address, postcode, category,
contact, contactTel, contactEmail) VALUES (`" . $companyName . "`, `" . $telephone . "`, `"
. $fax . "`, `" . $email . "`, `" . $address . "`,`" . $postcode . "`, `" . $category . "`,
`" . $contact . "`, `" . $contactTel . "`, `" . $contactEmail . "`)";
and now have the error "Error: Unknown column [companyName] in 'field list'", where [companyName] is the value submitted through the form. But surely I've defined the column as "name"?
Edit 2: Thanks, I'm now aware of the injection issue. I'd like to get it working, then I'll change it to using prepared statements.
You need either a values statement or a select statement:
"INSERT INTO '" . $tableSelect . "' VALUES ('" . $companyName . "', '" . $telephone . "', '"
. $fax . "', '" . $email . "', '" . $address . "','" . $postcode . "', '" . $category . "',
'" . $contact . "', '" . $contactTel . "', '" . $contactEmail . "')";
However, I would also recommend that you include the column names in the insert statement:
"INSERT INTO '" . $tableSelect ."(companyname, telephone, fax, email, address, postcode, category, contact, contactTel, contactEmail) ".
"' VALUES ('" . $companyName . "', '" . $telephone . "', '"
. $fax . "', '" . $email . "', '" . $address . "','" . $postcode . "', '" . $category . "',
'" . $contact . "', '" . $contactTel . "', '" . $contactEmail . "')";
I'm not sure if those are the correct names.
Ignoring injection issues...
$sql = "
INSERT INTO $tableSelect
(name
,telephone
,fax
,email
,address
,postcode
,category
,contact
,contactTel
,contactEmail
) VALUES
('$companyName'
,'$telephone'
,'$fax'
,'$email'
,'$address'
,'$postcode'
,'$category'
,'$contact'
,'$contactTel'
,'$contactEmail'
);
";
Incidentally, in my (limited) experience, the practice of calling the variable (e.g. '$companyName') and the column (e.g. name) two (slightly) different things can get very confusing.
Use backquotes: ` instead of straight quotes when quoting table names:
instead of:
'" . $companyName . "'
this:
`" . $companyName . "`
Use prepared statements instead of putting the variables into the query directly. And check, that the tables names are correct, cause now you are open to SQL injection.
How can I prevent SQL injection in PHP?
please check insert query syntax
you are missing values in your program:
Follow the below Syntax:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
try query like this
$query="insert into abc (a,b,c) values ('a','b','c')
and first check your all variables using isset()
Please try below query:
$sql = "INSERT INTO $tableSelect ('" . $companyName."', '".$telephone."',
'".$fax."', '".$email."', '".$address."', '".$postcode."', '".$category."',
'".$contact."', '".$contactTel."', '".$contactEmail."')";
If still getting error, then you should use mysql_real_escape_string() function.
Data may contain special characters.
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Best way to stop SQL Injection in PHP
In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?
Yesterday I asked a question with regards to a script not working, whilst I in the end solved the issue myself. There was talk of SQL Injections risks.
So what I'm asking today is, with the code I have inserted below, how would one prevent SQL Injections?
So any advice of guidence. I know I can read the internet about SQL injections but there is so many conflicting articles on it, I don't know which is correct or not.
Here is the code, this is all put in a page of it's own lets say 'form-process.php' which the form then submits the data to e.g
<?
session_start();
$_SESSION['Title'] = stripslashes($_REQUEST['Title']);
$_SESSION['ShortTitle'] = stripslashes($_REQUEST['Title']);
$_SESSION['Category'] = stripslashes($_REQUEST['Category']);
$_SESSION['Story'] = stripslashes($_REQUEST['Story']);
$_SESSION['FrontPage'] = stripslashes($_REQUEST['FrontPage']);
$_SESSION['imagefilename'] = ($_FILES['image']['name']);
if (empty($_REQUEST['Title'])) {
header("Location: ". $_SERVER['HTTP_REFERER'] ."?message=0");
exit;
} elseif (empty($_REQUEST['ShortTitle'])) {
header("Location: ". $_SERVER['HTTP_REFERER'] ."?message=1");
exit;
} elseif (strlen($_REQUEST['Category']) < 1) {
header("Location: ". $_SERVER['HTTP_REFERER'] ."?message=2");
exit;
} elseif (empty($_REQUEST['Story'])) {
header("Location: ". $_SERVER['HTTP_REFERER'] ."?message=3");
exit;
} else {
include("settings.php");
include("dbconnect.php");
if($_POST['btnSubmit'] == 'Publish'){
$target = "../../../images/matchreports/uploaded/";
$target = $target . time() . '-' . basename( $_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
$image=time() . '-' . basename( $_FILES['image']['name']);
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "INSERT INTO " . $match_reports_table . " (Title,ShortTitle,Story,FrontPage,active,image,date,user_ip) VALUES('" . addslashes($_REQUEST['Title']) . "','" . addslashes($_REQUEST['ShortTitle']) . "','" . addslashes($_REQUEST['Story']) . "','" . addslashes($_REQUEST['FrontPage']) . "','" . addslashes(y) . "','$image','$newdate','" . addslashes($_SERVER['REMOTE_ADDR']) . "')";
$result = #mysql_query($SQL) or die("Error Publishing 1");
header("Location: /cms/matchreports/index.php?message=4");
exit;
} else {
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "INSERT INTO " . $match_reports_table . " (Title,ShortTitle,Story,FrontPage,active,date,user_ip) VALUES('" . addslashes($_REQUEST['Title']) . "','" . addslashes($_REQUEST['ShortTitle']) . "','" . addslashes($_REQUEST['Story']) . "','" . addslashes($_REQUEST['FrontPage']) . "','" . addslashes(n) . "','$newdate','" . addslashes($_SERVER['REMOTE_ADDR']) . "')";
$result = #mysql_query($SQL) or die("Error Publishing 2");
header("Location: /cms/matchreports/index.php?message=5");
exit;}}
if($_POST['btnSubmit'] == 'Save draft'){
$target = "../../../images/matchreports/uploaded/";
$target = $target . time() . '-' . basename( $_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
$image=time() . '-' . basename( $_FILES['image']['name']);
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "INSERT INTO " . $match_reports_table . " (Title,ShortTitle,Story,FrontPage,active,image,date,user_ip) VALUES('" . addslashes($_REQUEST['Title']) . "','" . addslashes($_REQUEST['ShortTitle']) . "','" . addslashes($_REQUEST['Story']) . "','" . addslashes($_REQUEST['FrontPage']) . "','" . addslashes(n) . "','$image','$newdate','" . addslashes($_SERVER['REMOTE_ADDR']) . "')";
$result = #mysql_query($SQL) or die("Error Saving Draft 1");
header("Location: /cms/matchreports/index.php?message=6");
exit;
} else {
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "INSERT INTO " . $match_reports_table . " (Title,ShortTitle,Story,FrontPage,active,date,user_ip) VALUES('" . addslashes($_REQUEST['Title']) . "','" . addslashes($_REQUEST['ShortTitle']) . "','" . addslashes($_REQUEST['Story']) . "','" . addslashes($_REQUEST['FrontPage']) . "','" . addslashes(n) . "','$newdate','" . addslashes($_SERVER['REMOTE_ADDR']) . "')";
$result = #mysql_query($SQL) or die("Error Saving Draft 2");
header("Location: /cms/matchreports/index.php?message=7");
exit;}}
if($_POST['btnSubmit'] == 'Publish changes'){
//This gets all the other information from the form
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "UPDATE " . $match_reports_table . " SET Title='" . addslashes($_REQUEST['Title']) . "',ShortTitle='" . addslashes($_REQUEST['ShortTitle']) . "',Story='" . addslashes($_REQUEST['Story']) . "',Category='" . addslashes($_REQUEST['Category']) . "',FrontPage='" . addslashes($_REQUEST['FrontPage']) . "',active = '" . y . "',date='$newdate' WHERE ID=" . $_REQUEST['ID'] . "";
$result = #mysql_query($SQL) or die("Error Updating News");
header("Location: /cms/matchreports/index.php?message=8");
exit;}
if($_POST['btnSubmit'] == 'Publish draft to website'){
//This gets all the other information from the form
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "UPDATE " . $match_reports_table . " SET Title='" . addslashes($_REQUEST['Title']) . "',ShortTitle='" . addslashes($_REQUEST['ShortTitle']) . "',Story='" . addslashes($_REQUEST['Story']) . "',Category='" . addslashes($_REQUEST['Category']) . "',FrontPage='" . addslashes($_REQUEST['FrontPage']) . "',active = '" . y . "',date='$newdate' WHERE ID=" . $_REQUEST['ID'] . "";
$result = #mysql_query($SQL) or die("Error Updating News");
header("Location: /cms/matchreports/index.php?message=9");
exit;}
if($_POST['btnSubmit'] == 'Save changes to draft'){
//This gets all the other information from the form
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "UPDATE " . $match_reports_table . " SET Title='" . addslashes($_REQUEST ['Title']) . "',ShortTitle='" . addslashes($_REQUEST['ShortTitle']) . "',Story='" . addslashes($_REQUEST['Story']) . "',Category='" . addslashes($_REQUEST['Category']) . "',FrontPage='" . addslashes($_REQUEST['FrontPage']) . "',active = '" . n . "',date='$newdate' WHERE ID=" . $_REQUEST['ID'] . "";
$result = #mysql_query($SQL) or die("Error Updating News");
header("Location: /cms/matchreports/index.php?message=10");
exit;}
}?>
Use PDO and prepared statements.
A simple, universal rule I like to apply is this:
Always store data raw, and escape it for the appropriate application when needed.
This means, get rid of nebulous stripslashes(), and:
for string values in SQL statements, use the database's appropriate escape function, e.g. mysqli_real_escape_string(),
for system()-type command names, use escapeshellcmd(), for arguments use escapeshellarg(),
for manually assembling GET request URLs, use urlencode(), and finally
for printing content in an HTML structure, use htmlentities().
There's no point in blindly using some sort of mangling and hoping it'll filter out bad things. Be conscious of what you're doing, and do the appropriate thing at every step.
Example: To print a link with a user-provided GET parameter, you'd do
print("<a href='" . htmlentities($BASEURL . "?data=" . urlencode($untrusted)) . "'>click</a>");
Important note: For SQL queries, it is generally preferable to use prepared statements rather than building queries by hand. This is a different technology from what you're used to, so it's not the straight "how do I fix this" answer, but it is by far the better solution.
I strongly suggest this article generally on escaping (google-translated from czech language)