Add data into php mysql with single quotes - php

This is my code:
$q=mysql_query("SELECT * FROM `table1` WHERE name like '%$searchText%'");
while($e=mysql_fetch_assoc($q))
//$output[]=$e;
//echo $e['NAME'];
{
$name = $e['NAME'];
$brand = $e['BRAND'];
$category = $e['CATEGORY'];
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
$result = mysql_query($query) or die("Unable to insert because : " . mysql_error());
}
Since in "BRAND", there may be some data like "First's Choice".
In this case, I cannot insert to database due to error.
How can I insert data that contain single quotes?
Thx

you need to use mysql_real_escape_string on the value, which you should be doing anyway. That should properly escape your value for insertion.
$name = mysql_real_escape_string($e['NAME']);
$brand = mysql_real_escape_string($e['BRAND']);
$category = mysql_real_escape_string($e['CATEGORY']);
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";

Use mysql_real_escape_string

You must use :
$brand = mysql_real_escape_string($brand)
See PHP Documentation.
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )
Escapes special characters in
the unescaped_string, taking into account the current character set of
the connection so that it is safe to place it in a mysql_query(). If
binary data is to be inserted, this function must be used. (..)

Try below code
$q=mysql_query("SELECT * FROM `table1` WHERE name like '%$searchText%'");
while($e=mysql_fetch_assoc($q))
//$output[]=$e;
//echo $e['NAME'];
{
$name = $e['NAME'];
$brand = mysql_real_escape_string($e['BRAND']);
$category = $e['CATEGORY'];
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
$result = mysql_query($query) or die("Unable to insert because : " . mysql_error());
}

There are two ways of accomplishing that. You can first run an escape string on it:
$newbrand = mysql_real_escape_string($brand);
and insert $newbrand. When you call it, you have to do strpslashes($newbrand);
OR you could do:
$search = array("'");
$newbrand = str_replace($search,'',$brand);

I was pulling my hair to solve this, finally i am ok with this solution. Try this

Related

SQL - Insert INTO results in nothing

I've been trying to get this INSERT to work correctly, so I worked through the undefined variable and index problems and now I think I am nearly there.
Below is the code:
<?php
session_start();
require "../dbconn.php";
$username = $_SESSION['username'];
$query1 = "SELECT user_table.user_id FROM user_table WHERE user_table.username ='".$username."'";
$query2 = "SELECT department.department_id FROM department, user_table, inventory
WHERE user_table.user_id = department.user_id
AND department.department_id = inventory.department_id";
//Copy the variables that the form placed in the URL
//into these three variables
$item_id = NULL;
$category = $_GET['category'];
$item_name = $_GET['item_name'];
$item_description = $_GET['item_description'];
$item_quantity = $_GET['quantity'];
$item_quality = $_GET['quality'];
$item_status = NULL;
$order_date = $_GET['order_date'];
$invoice_attachment = NULL;
$edit_url = 'Edit';
$ordered_by = $username;
$user_id = mysql_query($query1) or die(mysql_error());
$department_id = mysql_query($query2) or die(mysql_error());
$price = $_GET['price'];
$vat = $_GET['vat%'];
$vat_amount = $_GET['vat_amount'];
$create_date = date("D M d, Y G:i");
$change_date = NULL;
//set up the query using the values that were passed via the URL from the form
$query2 = mysql_query("INSERT INTO inventory (item_id, category, item_name, item_description, item_quantity, item_quality, item_status, order_date,
invoice_attachment, edit_url, ordered_by, user_id, department_id, price, vat, vat_amount, create_date, change_date VALUES(
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$item_quantity."',
'".$item_quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$user_id."',
'".$department_id."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
header( 'Location:../myorders.php');
?>
Error:
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 'VALUES( '', 'adasd', 'dsadsa', 'dsad', 'sadsad', '' at line 2
Could anyone please let me know where I am going wrong? :(
Been staring at this for 3-5 hours already :(
You are not actually trying to insert any data into your table. You only craft and assign the query in string form to a variable. You need to use the function mysql_query to actually run the code.
As pointed out you will also have to specify the columns you are inserting data into in the MySQL query if you don't supply data for every column (in the correct order). Here you can look at the MySQL insert syntax.
I would also urge you to look into using the MySQLi or the MySQL PDO extensions for communicating with your MySQL database since the MySQL extension is deprecated. Look here for additional information and comparisons.
Here, you only assign the values to the $query var:
$query = "INSERT INTO inventory VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')"
or die("Error: ".mysql_error());
You do not actually run the query.
try:
$query = mysql_query("INSERT INTO inventory (column_name1, column_name 2, column_name3 ... the column name for each field you insert) VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
Also, you should use mysqli_* or any other PDO as the mysql_* functions are deprecated
If you are not inserting in all columns you need to specify the columns you are going to insert. Like this:
INSERT INTO Table(Column1, Column6) VALUES (Value1, Value6)
You are missing the column names in your INSERT

INSERT INTO TABLE .. php - variable in sql query

I have php script containing following SQL query (working oK):
$query = 'INSERT INTO persons'.
'(name,
surname
)'.'VALUES
( "'.$_REQUEST["name"].'",
"'.$_REQUEST["surname"].'"
)';
Where $_REQUEST["name"] and $_REQUEST["name"] are variables passed from html form.
usin php 4.5 and MariaDB 5.5
Problem rises when i try to substitute persons by variable - eg. $table:
$table = "persons";
$query = 'INSERT INTO '.$table.''.
'(name,
surname
)'.'VALUES
( "'.$_REQUEST["name"].'",
"'.$_REQUEST["surname"].'"
)';
I have been trying different variations with double qutes/single qutes/dots :). But still struggling with this..
Thx for possible answer.
Its a simply case of knowing how the single and double quote works in PHP
Try this
$table = 'persons';
$query = "INSERT INTO $table (name,surname)
VALUES ( '{$_REQUEST['name']}',
'{$_REQUEST['surname']}' )";
Now of course you should not be using the mysql_* extension anymore but if you have to you should at least try and sanitize the input values before you use them
So the code becomes
// do at least this to sanitize the inputs
$_REQUEST['name'] = mysql_real_escape_string($_REQUEST['name']);
$_REQUEST['surname'] = mysql_real_escape_string($_REQUEST['surname']);
$query = "INSERT INTO $table (name,surname)
VALUES ( '{$_REQUEST['name']}',
'{$_REQUEST['surname']}' )";
$table_name = 'persons';
$query = "insert into ".$table_name." (name,surname) values ('".$_REQUEST['name']."','".$_REQUEST['surname']."') ";

MySQL query mishandling date field

I've got a PHP/MySQL script that is yielding strange results on a date field. All along the process, my dates are fine until the very end. The final result has every entry in the date field as '0000-00-00'. I'm totally stuck and don't know what else to do. I can tell that this is an issue with PHP not interpreting this as a date, but I don't know how to fix it. Here is my code:
$sql = "CREATE TABLE temp_workouts (my_date date, sg_id int(11), loc_id int(11))";
$result = mysql_query($sql);
if (!$result) {
$tag_success = "failure";
$tag_message = mysql_error();
echo encodeJSON($tag_success, $tag_message);
die();
}
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$my_date = $row['my_date'];
echo $my_date . " "; //<--this output looks perfect
$sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
$result2 = mysql_query($sql);
}
die();
When I flip over to MyPHPAdmin and look at the table, the entire column my_date contains '0000-00-00'. How can I get PHP to recognize this as a 'Y-m-d' formatted date? Thanks. I appreciate any help.
I suspect the issue is that you haven't enclosed a string literal in single quotes:
INSERT INTO temp_table (my_date) VALUES ('$my_date')
^--- ^--- string literals in single quotes
Otherwise, the statement is probably something like:
... VALUES (2013-08-22)
MySQL isn't converting that into a valid date, issuing a warning message, and inserting a "zero" date.
Your immediate problem is that you don't use quotes around date values in your insert statement.
Change
$sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
to
$sql = "INSERT INTO temp_table (my_date) VALUES ('$my_date')";
^ ^
Now, you can just use INSERT ... SELECT syntax to achieve your goal in one go
INSERT INTO temp_table (my_date)
SELECT my_date
FROM my_table
Therefore this part of your code
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$my_date = $row['my_date'];
echo $my_date . " "; //<--this output looks perfect
$sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
$result2 = mysql_query($sql);
}
can be changed to
$sql = "INSERT INTO temp_table (my_date)
SELECT my_date FROM my_table";
$result2 = mysql_query($sql);
On a side note: Consider switching to either PDO or MySQLi and use prepared statements.
Try this one...This will re-convert it to date, and then save..
$dt = strtotime($row['my_date']);
$date = date("Y-m-d",$dt);
$sql = "INSERT INTO temp_table (my_date) VALUES ({$date})";

insert php array into mySql

I am looking for some guidance.
I have a data form field which I am inserting into a table and am looking to association the data with the id's of other relevant data. I was wondering if there was recommended way to insert an array of relevant Id's in relation to the information I am referring too.
Below is what Im thinking...
Eg. php reads
<?php
$name = $_POST['name'];
$info = $_POST['information'];
$id = $_POST['id'];
$family = array();
?>
<?php
$select = "SELECT *
FROM `names_family`
WHERE `name` LIKE '$name'
LIMIT 0 , 30";
$selected = mysql_query($select, $connection);
if(!$selected){
die("Hal 9000 says: Dave the select family name ID query failed " . mysql_error());}
while($row = mysql_fetch_array($selected)){
$familyId = $row[0];
$familyName = $row[1];
array_push($family, $familyName => $familyId);
}
$insertInfo = "INSERT INTO `family_info`.`info`
(`name`, `info`, `family`)
VALUES (
'$name', '$info', '$family');";
$insertedInfo = mysql_query($insertInfo, $connection);
if(!$insertedInfo){
die("Hal 9000 says: Dave the insert info query failed " . mysql_error());}
?>
Is this a recommended way to relate information? Or is another way to achieve the same result?
What data type is the "family" column in MySQL?
I'm pretty sure you can't straight up insert php arrays like that into MySQL.
If it's possible, guess it's one of those things I didn't know because I never even tried.
The easiest way to do this is to encode your php array into a JSON string and decode it back into a php array when you read it.
$family = array();
...
$familyJsonString = json_encode($family);
...
$insertInfo = "INSERT INTO `family_info`.`info`
(`name`, `info`, `family`)
VALUES (
'$name', '$info', '$familyJsonString');";
...
$queryString = "SELECT * FROM family_info WHERE name = '$someName'";
$query = mysql_query($queryString, $connection);
$familyData = mysql_fetch_assoc($query);
$decodedFamilyArray = json_decode($familyData['family']);
where the family column should be a varchar or text type depending on how long the family array gets.
A more robust way to do this is to create a separate table to store your family data and use a MySQL JOIN statement to get the values associated to one entry in the family_info table.
here is some info on joins
Joining two tables without returning unwanted row
http://dev.mysql.com/doc/refman/5.0/en/join.html
there is another way
$family=array()
while($row = mysql_fetch_array($selected)){
$familyId = $row[0];
$familyName = $row[1];
$family[]=$familyName.$familyId;
}
$insertInfo = "INSERT INTO `family_info`.`info`
(`name`, `info`, `family`)
VALUES (
'$name', '$info', '$family');";

MySQL and PHP - insert NULL rather than empty string

I have a MySQL statement that inserts some variables into the database. I recently added 2 fields which are optional ($intLat, $intLng). Right now, if these values are not entered I pass along an empty string as a value. How do I pass an explicit NULL value to MySQL (if empty)?
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long',
'$intLat', '$intLng')";
mysql_query($query);
To pass a NULL to MySQL, you do just that.
INSERT INTO table (field,field2) VALUES (NULL,3)
So, in your code, check if $intLat, $intLng are empty, if they are, use NULL instead of '$intLat' or '$intLng'.
$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long',
$intLat, $intLng)";
This works just fine for me:
INSERT INTO table VALUES ('', NULLIF('$date',''))
(first '' increments id field)
If you don't pass values, you'll get nulls for defaults.
But you can just pass the word NULL without quotes.
All you have to do is: $variable =NULL; // and pass it in the insert query. This will store the value as NULL in mysql db
Normally, you add regular values to mySQL, from PHP like this:
function addValues($val1, $val2) {
db_open(); // just some code ot open the DB
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES ('$val1', '$val2')";
$result = mysql_query($query);
db_close(); // just some code to close the DB
}
When your values are empty/null ($val1=="" or $val1==NULL), and you want NULL to be added to SQL and not 0 or empty string, to the following:
function addValues($val1, $val2) {
db_open(); // just some code ot open the DB
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
(($val1=='')?"NULL":("'".$val1."'")) . ", ".
(($val2=='')?"NULL":("'".$val2."'")) .
")";
$result = mysql_query($query);
db_close(); // just some code to close the DB
}
Note that null must be added as "NULL" and not as "'NULL'" . The non-null values must be added as "'".$val1."'", etc.
Hope this helps, I just had to use this for some hardware data loggers, some of them collecting temperature and radiation, others only radiation. For those without the temperature sensor I needed NULL and not 0, for obvious reasons ( 0 is an accepted temperature value also).
For some reason, radhoo's solution wouldn't work for me. When I used the following expression:
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
(($val1=='')?"NULL":("'".$val1."'")) . ", ".
(($val2=='')?"NULL":("'".$val2."'")) .
")";
'null' (with quotes) was inserted instead of null without quotes, making it a string instead of an integer. So I finally tried:
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
(($val1=='')? :("'".$val1."'")) . ", ".
(($val2=='')? :("'".$val2."'")) .
")";
The blank resulted in the correct null (unquoted) being inserted into the query.
your query can go as follows:
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$lng', '" . ($lat == '')?NULL:$lat . "', '" . ($long == '')?NULL:$long . "')";
mysql_query($query);
Check the variables before building the query, if they are empty, change them to the string NULL
you can do it for example with
UPDATE `table` SET `date`='', `newdate`=NULL WHERE id='$id'
2022 | PHP 7.3 | MySQL 5.7
Accepted answer by Rocket Hazmat gives me "NULL" as a string. So I change it to:
$intLat = !empty($intLat) ? "'$intLat'" : NULL;
$intLng = !empty($intLng) ? "'$intLng'" : NULL;

Categories