mysql not accepting apostrophe ' - php

need help inputs are not inserted to db when there is an apostrophe in the textfield values, im trying to use the codes below to escape the ' but its not working,
function myaddslashes($string){
if(get_magic_quotes_gpc() == 1){
return $string;
} else {
return str_replace("'", "''", $string);
}
}
ive used this as well to no avail:
function check_input($value)
{
// Stripslashes
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote if not a number
if (!is_numeric($value))
{
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
here is my php code:
<?php
error_reporting(0);
require 'include/DB_Open.php';
$RemedyTicketNo = $_POST['RemedyTicketNo'];
$PhoneNumber = $_POST['PhoneNumber'];
$Category2 = $_POST['Category2'];
$Category3 = $_POST['Category3'];
$Status = $_POST['Status'];
$Createdate = $_POST['Createdate'];
$Date = $_POST['Date'];
$Severity = $_POST['Severity'];
$BanType = $_POST['BanType'];
$XiD = $_POST['XiD'];
$Ticket = $_POST['Ticket'];
if (isset($RemedyTicketNo))
{
$sql="INSERT into tbl_main (ars_no, phone_number, category_1, category_2, status, create_date, resolved_date, trouble_type_priority, ban_type, employee_id_name)
VALUES ('".$RemedyTicketNo."', '".$PhoneNumber."', '".$Category2."', '".$Category3."', '".$Status."', '".$Createdate."', '".$Date."', '".$Severity."', '".$BanType."', '".$XiD."')";
$result=mysql_query($sql);
header("Location: wireless_new.php");
}
?>
P.S...im new to php and sql so im still trying to learn to use sqli...

All strings should be escaped using a database-specific function. In your case mysql_real_escape_string
If you're learning, you're better off starting with MySQLi as the MySQL extension is deprecated as of PHP 5.5.0. It's no more difficult than the one you're using.

Use query parameters or whatever the php equivalent is called. Escaping quotes is one of the good things they do for you.

Mysqli will happily accept a single quote if it gets properly escaped.
but for some reason you don't actually apply none of your functions to the input. So, that's the only your problem.
Also note that error_reporting should always be E_ALL, not 0

i was able to fixed it by adding mysql_real_escape_string the field which has ' value
$RemedyTicketNo = $_POST['RemedyTicketNo'];
$PhoneNumber = $_POST['PhoneNumber'];
$Category2 = $_POST['Category2'];
$Category3 = **mysql_real_escape_string** ($_POST['Category3']);
$Status = $_POST['Status'];
$Createdate = $_POST['Createdate'];
$Date = $_POST['Date'];
$Severity = $_POST['Severity'];
$BanType = $_POST['BanType'];
$XiD = $_POST['XiD'];
$Ticket = $_POST['Ticket'];

if you are using
(all book's are available) as $subject and you are trying to insert in to mysql
use this
$subject=$_POST['subject'];
$disc_str = addslashes($subject);
"INSERT INTO table name (subject) value('$disc_str')";
it works for me in Textarea with tinymce also

Related

Alpha Numeric values xcannot be retrieved in PHP

I am currently working on this project. Data can be retrieved from database with this code, if certificateNumber is numeric, but it does not search person if certificateNumber field has alphanumeric data.
Where am I wrong with this?
<?php
$flag = 0;
$reg=$_REQUEST["cerf"];
echo ($reg);
$con = mysqli_connect('localhost','neoncom_db','12345','neoncom_std');
$qur = 'select * from student where certificateNumber = '.$reg;
$check = mysqli_query($con,$qur);
while($row=mysqli_fetch_array($check))
{
if($reg==$row["certificateNumber"])
{
$flag++;
$first = $row["first"];
$last=$row["last"];
$num = $row["certificateNumber"];
$name = $first ." ".$last;
$course = $row["course"];
$date = $row["signupDate"];
echo($row["certificateNumber"]);
echo($row["first"]);
echo($row["last"]);
}
}
if(count==0)
{
echo("NOT FOUND");
}
?>
You need to encapsulate $reg in quotes. So your query string $qur should be like this:
$qur = "select * from student where certificateNumber = '" . $reg . "'";
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.

How do I ensure null is sent instead of 0 for empty form fields

I have a table with columns that allow null values and has a default null value. On update, if the field is empty (not data inserted) my script inserts 0 instead of null. I have gone through similar questions as mine and i have tried the advice given but am still not able to fix my issue. Here's my code
<?php
if (isset($_POST['submit'])) {
# process the form
$student_id = $_POST["student_id"];
$subject_id = $_POST['subject_id'];
if (is_null($_POST["test1"])){$test1 = null;} else {$test1 = $_POST["test1"];}
if (is_null($_POST["test2"])){$test2 = null;} else {$test2 = $_POST["test2"];}
if (is_null($_POST["test3"])){$test3 = null;} else {$test3 = $_POST["test3"];}
for($i=0; $i < count($student_id); $i++) {
$studentid = mysqli_real_escape_string($connection, $student_id[$i]);
$subjectid = mysqli_real_escape_string($connection, $subject_id);
$test_1 = mysqli_real_escape_string($connection, $test1[$i]);
$test_2 = mysqli_real_escape_string($connection, $test2[$i]);
$test_3 = mysqli_real_escape_string($connection, $test3[$i]);
$query = "UPDATE fullresult SET test1='{$test_1}', test2='{$test_2}', test3='{$test_3}' WHERE student_id={$studentid} AND subject_id={$subjectid}";
$result = mysqli_query($connection, $query);
}
}
?>
When i echo the query, this is what i see and am wondering why i still get 0 inserted
UPDATE fullresult SET test1=' 10', test2=' ', test3=' ' WHERE student_id=51 AND subject_id=2
is_null does not return true for an empty string. Try changing your if statements to something like this:
$test1 = trim($_POST["test1"])
if (!strlen($test1)) $test3 = null;
You could use
ctype_digit
to check if there are numeric characters in it.
The function
mysqli::real_escape_string -- mysqli_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
(Source: http://php.net/manual/en/mysqli.real-escape-string.php)
Since you want to have null inside the database you should rewrite the code
if (is_null($_POST["test1"])){$test1 = null;} else {$test1 = mysqli_real_escape_string($connection, $_POST["test1"]);}
to have the values escaped only if needed (which is in case you have a value in $_POST)
What about
if (isset($_POST['submit'])) {
# process the form
$student_id = $_POST["student_id"];
$subject_id = $_POST['subject_id'];
# only retrieve FILLED IN answers
$tests = array();
if(isset($_POST["test1"]) && strlen($_POST["test1"])) $tests['test1'] = $_POST["test1"];
if(isset($_POST["test2"]) && strlen($_POST["test2"])) $tests['test2'] = $_POST["test2"];
if(isset($_POST["test3"]) && strlen($_POST["test3"])) $tests['test3'] = $_POST["test3"];
if(!empty($tests)){ # if there were no answers, there's no point in updating the database
for($i=0; $i < count($student_id); $i++) {
$studentid = mysqli_real_escape_string($connection, $student_id[$i]);
$subjectid = mysqli_real_escape_string($connection, $subject_id);
# now let's build the "SET" part of the query
$set = array();
foreach($tests as $key => $value) $set[]=mysqli_real_escape_string($key)."='".mysqli_real_escape_string($value)."'";
$set = implode(', ',$set);
# ...and finally update
$query = "UPDATE fullresult SET {$set} WHERE student_id={$studentid} AND subject_id={$subjectid}";
$result = mysqli_query($connection, $query);
}
}
}
The point of this approach is that if you don't include a key=>value pair in your UPDATE query, it will be filled in with its default value.
You must set 'null' word, not null value.
if (is_null($_POST["test1"])){$test1 = 'null';} else {$test1 = $_POST["test1"];}
if (is_null($_POST["test2"])){$test2 = 'null';} else {$test2 = $_POST["test2"];}
if (is_null($_POST["test3"])){$test3 = 'null';} else {$test3 = $_POST["test3"];}

How to solve cannot use string offset as an array error in PHP?

I want to add multiple data into table at once but my code gives an error saying 'cannot use string offset as an array'. I have attached my code. Can anyone help me to solve this?
$issuedate=$_POST['issuedate'];
$member=$_POST['member'];
$bno[0]['TitleNo'] = $_POST['bno'];
$bno[1]['TitleNo'] = $_POST['bno1'];
$bno[2]['TitleNo'] = $_POST['bno2'];
$bno[3]['TitleNo'] = $_POST['bno4'];
$returndate = $_POST['returndate'];
for($i=0; $i<4; $i++)
{
$sql5 = mysqli_query($db, "INSERT INTO borrow(TitleNo,MemberID,IssueDate,dueDate,ReturnDate) VALUES ('".$bno[$i]['TitleNo']."','$member','$issuedate','$returndate')");
}
if ($sql5)
{
echo '<h4 class="message">Add New Book Copies! </h4>'; // echo $test;
}
else
{
echo 'Fail.';
}
You are probably assigning string to $bno variable thus it dynamically becomes of type string. More info here. Regarding the example you should
$bno = array();
Escape all your DB inputs (or even better, use prepared statements)
It makes more sense to put the if..else inside the for loop
Thus
$bno = array();
$mysqli_conn = mysqli_connect("localhost", "user", "password", "schema");
$issuedate = mysqli_real_escape_string($mysqli_conn, $_POST['issuedate']);
$member = mysqli_real_escape_string($mysqli_conn, $_POST['member']);
$bno[0]['TitleNo'] = mysqli_real_escape_string($mysqli_conn, $_POST['bno']);
$bno[1]['TitleNo'] = mysqli_real_escape_string($mysqli_conn, $_POST['bno1']);
$bno[2]['TitleNo'] = mysqli_real_escape_string($mysqli_conn, $_POST['bno2']);
$bno[3]['TitleNo'] = mysqli_real_escape_string($mysqli_conn, $_POST['bno4']);
$returndate = mysqli_real_escape_string($mysqli_conn, $_POST['returndate']);
for($i=0; $i<4; $i++)
{
$sql = mysqli_query($db, "INSERT INTO borrow(TitleNo,MemberID,IssueDate,dueDate,ReturnDate) VALUES ('".$bno[$i]['TitleNo']."','".$member."','".$issuedate."','".$returndate."')");
if ($sql)
{
echo '<h4 class="message">Add New Book Copies! </h4>'; // echo $test;
}
else
{
echo 'Fail.';
}
}
You have set $bno as string in some previous code.
What you can do for a quick fix is:
change $bno to somehing else, for example $book
$book[0]['TitleNo'] = $_POST['bno'];
$book[1]['TitleNo'] = $_POST['bno1'];
//..
set $bno to a new array and then assign the values
$bno = array();
$bno[0]['TitleNo'] = $_POST['bno'];
$bno[1]['TitleNo'] = $_POST['bno1'];
//...
Additional Notes
By the way it's better to escape somehow the values you enter in your DB. You can use mysqli_real_escape_string
Just assign do this for all the values:
$bno[0]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno']);
Sources to read
http://php.net/manual/en/mysqli.real-escape-string.php
You should have a look att prepared statements and bind params. When you're doing the insert statements you select five columns and only inserts four values.
$sql5 = mysqli_query($db, "INSERT INTO borrow(TitleNo,MemberID,IssueDate,dueDate,ReturnDate) VALUES ('".$bno[$i]['TitleNo']."','$member','$issuedate','$returndate')");
And as #jeroen mentioned, your code has sql-injection problems, read more about sql-injection here.
I've created and exampel using prepared statements and bind params. Note:
$stmt->bind_param('sssss',$bno[$i]['TitleNo'], $member, $issuedate, $dueDate, $returndate);
'sssss' are just for demo purpose, I assume dueDate and returndate columns are datetime something simular.
$DBServer = 'localhost';
$DBUser = 'root';
$DBPass = 'root';
$DBName = 'borrow';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$sql = ' INSERT INTO borrow (TitleNo,MemberID,IssueDate,dueDate,ReturnDate) VALUES (?,?,?,?,?)';
$TitleNo = $bno[0]['TitleNo'];
$member = 'MemberID';
$issuedate = 'issuedate';
$dueDate = 'dueDate';
$returndate = 'returndate';
/* Prepare statement */
$stmt = $conn->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
}
for( $i= 0; $i < count($bno); $i++){
/* Bind parameters. s = string, i = integer, d = double,  b = blob */
$stmt->bind_param('sssss',$bno[$i]['TitleNo'], $member, $issuedate, $dueDate, $returndate);
/* Execute statement */
$stmt->execute();
}
if( $stmt->affected_rows > 0 ){
echo '<h4 class="message">Add New Book Copies!</h4>';
}
$stmt->close();
However im not sure if it's best practice to do a mass insert to db using a for-loop.
Initialising your array (ie, $bno was probably initialised to a string in your code which caused the error you are seeing), escaping the input and doing a single INSERT (rather than 4, where you only check the results of the last one):-
<?php
$bno = array();
$sql_array = array();
$issuedate = mysqli_real_escape_string($db, $_POST['issuedate']);
$member = mysqli_real_escape_string($db, $_POST['member']);
$bno[0]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno']);
$bno[1]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno1']);
$bno[2]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno2']);
$bno[3]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno4']);
$returndate = mysqli_real_escape_string($db, $_POST['returndate']);
foreach($bno AS $abno)
{
$sql_array = "('".$bno['TitleNo']."','$member','$issuedate','$returndate')"
}
$sql5 = mysqli_query($db, "INSERT INTO borrow(TitleNo,MemberID,IssueDate,dueDate,ReturnDate)
VALUES ".implode(', ', $sql_array));
if ($sql5)
{
echo '<h4 class="message">Add New Book Copies!</h4>';
// echo $test;
}
else
{
echo 'Fail.';
}
This does suggest that the database could be further normalised, as you have multiple rows being inserted that are identical except for one value.

Cannot insert character into mysql column from array

I have following code in order to capture data from the previous page. Its working fine, the data is passing true, just the problem is the only variable that has characters ($itemName).
I simply cannot insert in mysql column. Its not type setting or character set. I suspecting its something to with a fact that the text is coming from array. Any ideas?
if(isset($_POST["cantidad"]) && count($_POST['cantidad'])>0) {
foreach($_POST["cantidad"] as $key => $value) {
$cantidad = $value;
$value = $_POST["cantidad"][$key];
$idItem = $_POST['hiddenField'][$key];
$itemName = $_POST['hiddenName'][$key];
$query = "INSERT INTO `inventarioStat` SET `fecha` = $timestamp, `idItem` = $idItem, `nombreItem` = $itemName, `cantidad` = $value";
///// this section is to check do data pass true and they do
echo "<br>";
echo "value:" . $value . "<br>";
echo "id:" . $idItem . "<br>";
echo "name:" . $itemName . "<br>";
mysql_query($query);
}
}
echo "<br>";
$query = "INSERT INTO `inventarioStat` SET `fecha` = $timestamp, `idItem` = $idItem, `nombreItem` = $itemName, `cantidad` = $value";
This line is incorrect and extremely unsafe. The issue is that you are not quoting your strings in the SQL query. You need quotes around the $itemName value.
You also need to be escaping the values here. This code is wide open to SQL injection. If you use it, you will probably get hacked.
Try this:
foreach($_POST["cantidad"] as $key => $value) {
$cantidad = $value;
$value = mysql_real_escape_string($_POST["cantidad"][$key]);
$idItem = mysql_real_escape_string($_POST['hiddenField'][$key]);
$itemName = mysql_real_escape_string($_POST['hiddenName'][$key]);
$query = "INSERT INTO `inventarioStat` SET `fecha` = '$timestamp', `idItem` = '$idItem', `nombreItem` = '$itemName', `cantidad` = '$value'";
mysql_query($query);
}
This code is better, but not perfect. It's safer, but not 100% safe.
You should upgrade to using PDO or MySQLi and prepared statements (PDO docs or MySQLi docs).

Large Forms = Large PHP/mySql Query Strings... Is There a Good Solution?

I've got a CMS I'm building where I've got a rather large form full of data to add to my database. This is where I collect my variables....
$orgName = $_POST['orgName'];
$impact = $_POST['impact'];
$headline = $_POST['headline'];
$content = $_POST['content'];
$subContent = $_POST['subContent'];
$meterText = $_POST['meterText'];
$month = $_POST['month'];
$shopLink = $_POST['shopLink'];
$blurbTitle = $_POST['blurbTitle'];
$blurb = $_POST['blurb'];
$logoURL = $_POST['logoURL'];
$buttonURL = $_POST['buttonURL'];
$blurbURL = $_POST['blurbURL'];
$POMURL = $_POST['POMURL'];
$horizontalURL = $_POST['horizontalURL'];
$statURL = $_POST['statURL'];
$stats = $_POST['stats'];
here I sql escape, validate and send to my function (omitted validation for space)...
require_once 'DB_Connect.php';
$connection = new DB_Connect();
$connection->insertPartner(
$index,
mysql_real_escape_string($orgName),
mysql_real_escape_string($impact),
mysql_real_escape_string($headline),
mysql_real_escape_string($content),
mysql_real_escape_string($subContent),
$month,
mysql_real_escape_string($shopLink),
mysql_real_escape_string($blurbTitle),
mysql_real_escape_string($meterText),
mysql_real_escape_string($blurb),
mysql_real_escape_string($stats),
mysql_real_escape_string($logoURL),
mysql_real_escape_string($buttonURL),
mysql_real_escape_string($blurbURL),
mysql_real_escape_string($POMURL),
mysql_real_escape_string($horizontalURL),
mysql_real_escape_string($statURL)
))
and finally the function...
public function insertPartner(
$orgName = '',
$impact = '',
$headline = '',
$content = '',
$subContent = '',
$month = '',
$shopLink = '',
$blurbTitle = '',
$blurb = '',
$stats = '',
$logoURL = '',
$buttonURL = '',
$blurbURL = '',
$POMURL = '',
$horizontalURL = '',
$statURL = '')
{
$query="INSERT INTO `hupcap_FCE`.`fce_partners` (
`index`,
`organization_name`,
`impact`,
`headline`,
`content`,
`sub_content`,
`blurb_title`,
`blurb`,
`stats`,
`month`,
`meter_number`,
`meter_text`,
`shop_link`,
`button_img_url`,
`blurb_img_url`,
`logo_url`,
`month_img_url`,
`horizontal_logo_url`,
`stat_img_url`,
`util`
) VALUES (
'',
'$orgName',
'$impact',
'$headline',
'$content',
'$subContent',
'$blurbTitle',
'$blurb',
'$stats',
'$month',
0,
'',
'$shopLink',
'$buttonURL',
'$blurbURL',
'$logoURL',
'$POMURL',
'$horizontalURL',
'$statURL',
0)";
if(mysql_query($query)){
return true;
}else{
die("failed to insert record" . mysql_error());
}
}
There has GOT to be a slicker way of doing this.
Who's got the best method?
Thanks -J
Option #1
Use an ORM like Doctrine to handle CRUD in your PHP apps.
Option #2
If using an ORM is too big of a paradigm shift try something like this:
// Alias $_POST fields to SQL columns
$sql_columns= array(
'post_field1'=> 'sql_column1',
'post_field2'=> 'sql_column2',
'post_field3'=> 'sql_column3');
// Encode $_POST data for use in SQL
$sql_a= array();
foreach ($sql_columns as $k=> $k2) {
if (isset($_POST[$k])) {
$sql_a[]= sprintf("`%s` = '%s'", $k2, mysql_real_escape_string($_POST[$k]));
}
}
// Build SQL string to execute
$sql= sprintf('INSERT INTO table_name SET %s', implode(', ', $sql_a));
var_dump($sql);
This can easily be extended into a function or a class to handle different tables, columns and SQL statements.
do a foreach to run all over the params array, so you can check the value. Do some magic inside the final function so you can check if any of them is empty or something...
If you have 16 columns in your table, you're going to have a long insert statement.
You should use one of the database wrapper classes (like PDO). Firstly, it gives you a convenient way use prepared statements (avoiding SQL injection, and adding type checking). Secondly, it makes adding parameters more readable, since you don't have to concatenate one huge string.
function insert_stuff($col1, $col2, $col3) {
$conn = new PDO($connectionString);
$query = "insert into my_table (col1, col2, col3) values (:col1, :col2, :col3)";
$statement = $conn->prepare($query);
$statement->bindValue(":col1", $col1);
$statement->bindValue(":col2", $col2);
$statement->bindValue(":col3", $col3);
$statement->execute();
// etc.
}
If you're really bothered by all the typing, you can use your database to generate some of the code for you:
select
concat('$statement->bindValue(":', column_name, '", $', column_name, ');'
from
information_schema.columns
where
table_schema = 'my_database_name'
and table_name = 'my_table_name';
Something like this would work:
$insertArray() = array();
foreach ($_POST as $key=> $name)
{
$insertArray[$name] = mysql_real_escape_string($_POST[$name]);
}
$query = "INSERT INTO `hupcap_FCE`.`fce_partners` (" . implode(',', array_keys($insertArray)) VALUES '" . implode("','", $insertArray) . "'";
//...
THIS IS NOT SECURE BUT IT WOULD WORK :)
Yes it seems to be how it should be for the most part, however, you can save your life to a great extent by doing this:
Instead of writing:
$orgName = $_POST['orgName'];
$impact = $_POST['impact'];
$headline = $_POST['headline'];
$content = $_POST['content'];
$subContent = $_POST['subContent'];
$meterText = $_POST['meterText'];
$month = $_POST['month'];
$shopLink = $_POST['shopLink'];
$blurbTitle = $_POST['blurbTitle'];
$blurb = $_POST['blurb'];
$logoURL = $_POST['logoURL'];
$buttonURL = $_POST['buttonURL'];
$blurbURL = $_POST['blurbURL'];
$POMURL = $_POST['POMURL'];
$horizontalURL = $_POST['horizontalURL'];
$statURL = $_POST['statURL'];
$stats = $_POST['stats'];
You could simply write this line:
extract($_POST, EXTR_SKIP);
And now you have all the same variables available like what you did with so many lines above, for example, now you can use them or echo them:
echo $orgName;
echo $impact;
echo $headline;
To Add: I am not sure whether using extract is good practice in terms of security, however, i have been using this without any problems so far :)

Categories