I have a textbox which inserts a new row into the database.
The issue is that if the user inputs a bracket "(" or ")", it doesn't insert the row.
I have tried using $link->real_escape_string($value) but that only seems to fix the issue with apostrophes.
Is there another to use with brackets?
Thanks!
EDIT: The code:
foreach($_POST as $name => $value) {
if(0 === strpos($name, "amenities")){
//print "$name : $value<br>";
$query = "INSERT into content (`type`, `value`, `additional`) VALUES ('amenities', '" .$link->real_escape_string($value) . "', '')" or die("Error in the consult.." . mysqli_error($link));
$result = mysqli_query($link, $query);
}
}
if you got the space in your value try this solution
$query = "INSERT into content (`type`, `value`, `additional`) VALUES ('amenities', '".mysqli_real_escape_string($link,$value)."', '')" or die("Error in the consult.." . mysqli_error($link));
Try instead of
$link->real_escape_string($value)
doing something like:
mysqli_real_escape_string($link, $value)
use mysqli_real_escape_string($link, $value) or just {}... see an exemple:
< ?php
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysqli_query($query);
echo $query;
"SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''"
?>
Related
does the following piece of code face sql injection problems? IF so why and what could be changed to prevent it?
$sql2 = "UPDATE Candidates SET ".$row['Field']."= '$_POST[$tempname]' WHERE ID='".$_GET["id"]."'";
$result2 = mysqli_query($con,$sql2);
if ($con->query($sql2) === TRUE) {
if($_POST['Status']=="Employed"){
$sql3 = "INSERT INTO Employees (AFNumber, CID, Status, Name, DateOfBirth,DateOfEmployment)
VALUES ('".$_POST['AFNumber']."', '".$_POST['ID']."', 'Employed', '".$_POST['FullNameEng']."','".$_POST['DoBasID']."', '".date('d/m/Y')."')";
$result3 = mysqli_query($con,$sql3);
if ($con->query($sql3) === TRUE) {
}else {
echo "Error: " . $sql3 . "<br>" . $con->error;}
echo '<script>swal("Error", "Something went wrong '.$con->error.'", "error");</script>';
}
} else {
echo "Error: " . $sql2 . "<br>" . $con->error;
echo '<script>swal("Error", "Something went wrong '.$con->error.'", "error");</script>';
}
$row['Field'] = "`{$row['Field']}`"; //its better to use ` around field names. there can be 'date', 'begin', 'column' or other reserved keywords http://dev.mysql.com/doc/refman/5.6/en/keywords.html
$_POST[$tempname] = mysqli_real_escape_string($con, $_POST[$tempname]); //have no idea which data type your $row['Field']-column, so lets rely on escaping will be enough http://php.net/manual/en/mysqli.real-escape-string.php
$_GET['id'] = (int)$_GET['id']; //i believe that your `id` is an integer, otherwise you should use mysqli_real_escape_string
$sql2 = "UPDATE Candidates SET ".$row['Field']." = '{$_POST[$tempname]}' WHERE `ID` = '{$_GET['id']}'";
$result2 = mysqli_query($con, $sql2);
if ($con->query($sql2) === TRUE) {
if($_POST['Status']=="Employed") {
$_POST['AFNumber'] = (int)$_POST['AFNumber']; //i believe that your `AFNumber` is an integer, otherwise you should use mysqli_real_escape_string
$_POST['ID'] = (int)$_POST['ID']; //i believe that your `CID` is an integer, otherwise you should use mysqli_real_escape_string
$_POST['FullNameEng'] = mysqli_real_escape_string($con, $_POST['FullNameEng']);
$_POST['DoBasID'] = mysqli_real_escape_string($con, $_POST['DoBasID']); //if DateOfBirth is not a string - u can use (int) instead
$sql3 = "
INSERT INTO Employees
(AFNumber, CID, Status, Name, DateOfBirth, DateOfEmployment)
VALUES
('".$_POST['AFNumber']."', '".$_POST['ID']."', 'Employed', '".$_POST['FullNameEng']."', '".$_POST['DoBasID']."', '".date('d/m/Y')."')
";
//...
The main idea here (also the simplest, minimal) is:
1) if data-type is integer use (int) or intval() on incoming values.
2) if data-type is integer unsingned use abs() on incoming values.
3) othervise (on strings) use mysqli_real_escape_string
Read about Escape Sequences https://dev.mysql.com/doc/refman/5.0/en/string-literals.html
For future read about Prepared Statements https://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html
I have my table setup as shown in the image below.
When I try and run the following code to insert the values into the database I get the error:
FAIL: INSERT INTO Betfairodds
(Horse,Back,Lay,TimeformTR)VALUES( 'Intrepid','5.5', '5.9',
'0')
Would anyone be able to help, as I have tried to debug the code.
//loop through each individual card
foreach ($getdropdown2 as $dropresults) {
$horse = preg_replace('/\h*[^ a-zA-Z].*$/m', '', trim($dropresults->childNodes->item(8)->textContent));
$back = trim(GetBetween($dropresults->childNodes->item(18)->textContent, 'Back', '£'));
$lay = trim(GetBetween($dropresults->childNodes->item(20)->textContent, 'Lay', '£'));
$sql = "INSERT INTO `Betfairodds` (`Horse`,`Back`,`Lay`,`TimeformTR`)VALUES( '$horse','$back', '$lay', '0')";
$res = mysqli_query($db, $sql);
if (!$res) {
echo PHP_EOL . "FAIL: $sql";
trigger_error(mysqli_error($db), E_USER_ERROR);
}
}
I removed the quotes ' from 0 because it is defined as int in the schema and of-course added space right before VALUES ..try this:
$sql = "INSERT INTO `Betfairodds` (`Horse`,`Back`,`Lay`,`TimeformTR`) VALUES( '$horse','$back', '$lay', 0)";
Your statement is wrong. You should not put single quotes on the data fields. so it should be like:
$sql = "INSERT INTO `Betfairodds` (Horse,Back,Lay,TimeformTR)VALUES( '$horse','$back', '$lay', '0')";
Is not giving me any error, I am already linked with server but I am still unable to get it work.
It's still unable to add message, do you see any errors?
function pridaj_tovar() {
if ($link = spoj_s_db()) {
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES".
"('$_POST['nazov']', '$_POST['kategorie']', '$_POST['mesta']',' $_POST['cena']', NULL,'$_POST['popis']')";
$result = mysql_query($sql, $link);
if ($result) {
// unable to add
echo '<p>inserting was successful.</p>'. "\n";
} else {
// unable to add!
echo '<p class="chyba">Nastala chyba pri pridávaní tovaru.</p>' . "\n";
}
mysql_close($link);
} else {
// NEpodarilo sa spojiť s databázovým serverom!
echo '<p class="chyba">NEpodarilo sa spojiť s databázovým serverom!</p>';
}
}
This is how you should handle field and table names with spaces,dashes (etc) :
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES".
"('Something', 'Something1', 'word', '50', NULL, 'anotherword')";
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES". "
('{$_POST['nazov']}', '{$_POST['kategorie']}', '{$_POST['mesta']}','{$_POST['cena']}',
NULL,'{$_POST['popis']}')";
You have several problems in your way of making query.
Firstly, your table name is quite non standard (Auto-Moto) so you might need to add quotes around it.
Secondly, it is always a good practice to add some space on proper locations so you could change:
"VALUES"
with
" VALUES "
But you need to provide which error you have received and your table structure.
You missed a lot of space in your Query :
Copy this :
$sql = "INSERT INTO Auto-Moto ".
"(Tovar, Kategoria, Mesto, Cena, ID, Popis) ".
"VALUES ".
"('Something', 'Something1', 'word', '50', NULL, 'anotherword')";
If you want to see an error message change this line:
$result = mysql_query($sql, $link);
To this:
$result = mysql_query($sql, $link) or die ("Error in query: $query. " . mysql_error());
But you should really learn to use mysqli_* extensions since mysql_* extensions—such as what you are using—will be depreciated in PHP 5.5. So change that to this:
$result = mysqli_query($sql, $link) or die ("Error in query: $query. " . mysqli_error());
And be sure to change any other mysqli_* extensions you code might have in place, such as in the spoj_s_db() function you are calling as the $link for a DB connection.
Additionally, your $sql has a few formatting errors. Try this instead:
$sql = "INSERT INTO Auto-Moto"
. " (Tovar, Kategoria, Mesto, Cena, ID, Popis)"
. " VALUES"
. " ('Something', 'Something1', 'word', '50', NULL, 'anotherword')"
;
Note the spaces in the query around the . " concatenation strings. In your original query the formatting had no spaces at all. Which would cause MySQL to choke on the query.
what's wrong with my code? I'm sure $_POST['item'] has valid value
<?php
$data = $_POST['item'];
$conn = mysqli_connect("localhost","root","");
mysqli_select_db($conn, "ajaxexample");
$q = INSERT INTO user (userList) VALUES ('$data');
if(mysqli_query($conn, $q)){
echo 1;
}
?>
put INSERT INTO user (userList) VALUES ('$data'); in double quotes.
eg:
$q = "INSERT INTO user (userList) VALUES ('$data')";
PHP string literals need to be in quotes.
To fix this by changing just one line:
$q = "INSERT INTO user (userList) VALUES ('" . mysqli_real_escape_string($data . "')";
<?php
$data = $_POST['item'];
$conn = mysqli_connect("localhost","root","", "ajaxexample");
$q = INSERT INTO user (userList) VALUES ('$data');
if(mysqli_query($conn, $q)){
echo 1;
}
?>
Not mysqli_select_db
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