Text form can't accept apostrophes - php

My text forms won't allow single " ' " to occur in the input fields. I get an sql syntax error. Is there any good way to allow single apostrophes to be allowed in my text field?
here's my code
html
<input class='what' type='text' name='one' required>
<textarea name='two' required></textarea>
<input type='submit'>
</form>
My database
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO whatsgood (one, two)
VALUES ('$one', '$two')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
any help would be very appreciated. Thank you!

Use addslashes PHP function (It Quote string with slashes)
$sql = "INSERT INTO whatsgood (one, two) VALUES ('".addslashes($one)."', '".addslashes($two)."')";
Example:
<?php
$str = "Is your name O'Reilly?";
// Outputs: Is your name O\'Reilly?
echo addslashes($str);
?>
You can also use 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)
$sql = "INSERT INTO whatsgood (one, two) VALUES ('".mysqli_real_escape_string($conn,$one)."', '".mysqli_real_escape_string($conn,$two)."')";

Use prepared statements this is much safer against SQL-Injections than just escaping.
Change this:
$sql = "INSERT INTO whatsgood (one, two)
VALUES ('$one', '$two')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
To this:
$stmt = $conn->prepare("INSERT INTO whatsgood(`one` , `two`) VALUES ( ? , ? )");
$stmt->bind_param("ss", $one , $two);
if($stmt->execute()){
echo "New record created successfully";
}
else{
echo "Error: " . $stmt->error;
}

Use mysqli_real_escape_string during INSERT to escape values.
$sql = "INSERT INTO whatsgood (one, two)
VALUES ('".mysqli_real_escape_string($conn, $one)."', '".mysqli_real_escape_string($conn, $two)."')";

Related

Why does the following not appear to open an SQL connection?

I find that the folowing script hangs for some reason. It will load and PHP doesn't see any errors, but it will not process the data (noting that we are in a context where I have a seperate login database open.)
In process.php we have the following:
<? PHP
//Process the POST data in prepration to write to SQL database.
$_POST['chat_input'] = $input;
$time = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_SESSION['username'];
$servername = "localhost";
$username = "id3263427_chat_user";
$password = "Itudmenif1!Itudmenif1!";
$dbname = "id3263427_chat_user";
$id = "NULL";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = 'INSERT INTO `chat` (`id`, `username`, `ip`, `timestamp`,
`message`) VALUES ('$id','$name', '$ip', '$time', '$input')';
if(mysqli_query($link, $sql)){
mysqli_close($conn);
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
the html form passed to the script above is as follows:
<form action="/process.php" method="post" id="chat">
<b> Send A Message (500 Character Max):</b><br>
<textarea name="chat_input" form="chat" size="500"></textarea>
<input type="submit" value=submit>
</form>
Not sure what's going on with this.
You got the syntax error because you're closing the $sql string before $id with your '.
What is this about your $id variable? With your current code you will insert the String "NULL". If you want to set the sql value null you should use $id = null; or just don't insert any value.
If you want your database to set an id, also leave it blank.
$input = $_POST['chat_input'];
$id = null;
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("ERROR: Could not connect. " . $conn->connect_error);
}
First solution
If this isn't a production code, you could insert the variables directly into the statement, but you should use " instead of ' for your sql string, so you can insert variables and ' without closing the string.
$sql = "INSERT INTO chat (id, username, ip, timestamp, message) VALUES ('$id', '$name', '$ip', '$time', '$input')";
if($conn->query($sql) === true) {
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " .$conn->error;
$conn->close();
}
Second solution
A better approach would be a prepared statement.
$stmt = $conn->prepare('INSERT INTO chat (username, ip, timestamp, message) VALUES (?, ?, ?, ?)');
$stmt->bind_param("ssss", $username, $ip, $time, $input);
if($stmt->execute()) {
$stmt->close();
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $stmt. " . $conn->error;
$stmt->close();
$conn->close();
}
The "s" in bind_param() defines a string at the given position, if you want to insert an integer, use "i" instead.
e.g. bindParam("sis", $string, $integer, $string);

MySql Insert into.....(error)

I'm getting an insert error when I'm trying to insert data from a form to my database. the error is as follows :
Error: INSERT INTO users (firstname) VALUES ('a')
This is the code:
if ( isset($_POST['submit']) ) {
$registerfirstname = $_POST['firstname'];
$query = "INSERT INTO users (firstname) VALUES ('$registerfirstname')";
if(mysqli_query($conn, $query)){
echo "New user created";
}else{
echo "Error: " .$query. "<br>" . mysqli_error($conn);
}
}
You are making a little mistake here. You have to pass the variable data through the mysqli_real_escape_string() through first. An example would be ,
$registerfirstname = mysqli_real_escape_string($registerfirstname);
And after that you can use it in sql like that. This way it is more sanitized. I hope this will solve your problem.
Firstly, you should use Mysql Workbenck to prepare sql statements. If, The statements properly work on workbench.Paste into the php script.
On php side, you should use mysql_real_escape_string() function before set your variable.
Like;
$registerfirstname = mysql_real_escape_string($_POST['firstname']);
Try this:
// Create connection
$connection = new mysqli('localhost', 'username', 'password', 'dbname');
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$firstname = "John";
$firstname = mysqli_real_escape_string($firstname);
$sql = "INSERT INTO users (firstname) VALUES ('$firstname')";
if ($connection->query($sql) === TRUE) {
echo "New user created";
} else {
echo "Error: " . $sql . "<br>" . $connection->error;
}
// Close connection
$connection->close();
It should work, but if it doesn't just give us what errors are shown.

MySQLi insert statement to executing

I am writing a simple code in PHP to test my MySql server by , inserting data to my database server
i am executing the file from the internet
URL of executing : Scores2.php?n=asdad&l=345&s=241
PHP Code:
<?php
$servername = "sql3.freesqldatabase.com";
$username = "MY USERNAME";
$password = "MY PASSWORD";
$dbname = "MY DBNAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = (string)$_GET['n'];
$score = (int)$_GET['s'];
$level = (int)$_GET['l'];
$sql = "INSERT INTO HighScores (name, score, level)
VALUES ($name, $score, $level)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When i execute the file , the browser shows this error :
Error: INSERT INTO HighScores (name, score, level) VALUES (asdad, 241, 345)
Unknown column 'asdad' in 'field list'
I checked the Control Panel in phpMyAdmin and executed the same statement but without variables , and it worked
Rows Types :
name : text
score : int(11)
level : int (11)
Learn how to prepare the query it's not that difficult.
You will avoid sql injection and missing quotes
Use num_rows to check if the record is inserted
Use $conn->error if the prepare() call return false.
$name = (string)$_GET['n'];
$score = (int)$_GET['s'];
$level = (int)$_GET['l'];
$sql = "INSERT INTO HighScores (name, score, level)
VALUES (?, ?, ?)";
if ($stmt = $conn ->prepare($sql)) {
$stmt->bind_param("s", $name);
$stmt->bind_param("i", $score);
$stmt->bind_param("i", $level);
$stmt->execute();
if($stmt->num_rows > 0){
echo "New record created successfully";
}else{
echo "no rows affected";
}
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn ->close();
$sql = "INSERT INTO HighScores (name, score, level)
VALUES ('$name', '$score', '$level')";
change query like this

How to search a database with the name of a var

So, I have this code right here, and all it does is error a... 404???? (Just a glitch, but still. Using remote HTTP access it does not work. It should)
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO $user(Username, Password, Membership)
VALUES ($usn, $psw, $membership)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Why wouldn't you try:
$sql = "INSERT INTO " . $user . "(Username, Password, Membership) VALUES (" . $usn . "," . $psw . "," . $membership. ")"
You probably meant to write either:
$sql = "INSERT INTO ".$user."(Username, Password, Membership)
VALUES
('".$usn."', '".$psw."', '".$membership."')";
or
$sql = "INSERT INTO user(Username, Password, Membership)
VALUES
('".$usn."', '".$psw."', '".$membership."')";
Escaping your input and adding a real_escape_string() call would be even better.
So I would write it in a way that the values are escaped as strings and the query handles them as strings:
$sql = "INSERT INTO user(Username, Password, Membership)
VALUES
('".$conn->real_escape_string($usn)."',
'".$conn->real_escape_string($psw)."',
'".$conn->real_escape_string($membership)."'
)";
I hope that helped at least a little.

Display error if the email address entered in form already exists

How do I use "emailaddress" as the only duplicate entry that provides a error?
A lot of the answers I've found use mysql_query but I want to use mysqli.
<?php
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
WARNING! the posted code and this answer (as i am only addressing the question now) contain big SQL injection leaks. Please read up on SQL injection and use escaping or prepared statements.
<?php
$con = mysqli_connect("localhost", "", "", "");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$existsQuery = "select count(*) as count from entry where emailaddress like '".$_POST[emailaddress]."'";
$existsResult = mysqli_query($con, $existsQuery);
if($existsResult->fetch_object()->count > 0)
{
echo "email already exist";
}
else
{
$sql = "INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
mysqli_close($con);
?>
simply make emailaddress unique in your table.

Categories