MySql Insert into.....(error) - php

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.

Related

Why do we check both the value and type when check if a database query was successful?

While I was on w3schools learning about MySQL and PHP, I came across this when on the page about inserting data.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When checking the query was successful, why do we check if both are the same type and equal? Wouldn't it be fine if it was just this?
if ($conn->query($sql) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli::query() returns false on failure, another result will be always not false. You can write without equaling with true if you don't need to use special logic for mysqli_result. docs
if ($conn->query($sql))
{
//
} else
{
//
}
Php supports truthyness do if the function returned 1 then it would be true. It's explicitly checking that the result is the Boolean TRUE.
You do NOT need to check type in THIS case and could just have:
if ($conn->query($sql) == TRUE) {
The author is probably using a defensive programming technique which is to validate exactly what you are expecting.
According to: http://php.net/manual/en/mysqli.query.php
If this is a "SELECT, SHOW, DESCRIBE or EXPLAIN" then you would get an object back. If somebody updated the query to something unexpected, they would hit the error condition and know they had done something wrong. This particular scenario is a little off because it's sample code. In reality you would probably have a test to do the real validation.

Text form can't accept apostrophes

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)."')";

Get value from specific MySql row

On my website, a user's background URL is stored with their data in a database. I need to get this value and store it in a variable.
However, I am having trouble doing so, the code I have right now gives me an error but doesnt tell me what the error is.
My code:
<?php
error_reporting(E_ALL);
include 'config.php';
$pin = $_COOKIE["UID"];
// Create connection
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * from users where pin ='$pin'";
$result = $conn->query($query);
if ($conn->query($query) === TRUE) {
$bg_url = $row[bg_url];
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
echo $bg_url;
mysqli_close($conn);
?>
$query = "SELECT * from users where pin ='$pin'";
$result = $conn->query($query);
Actually yes, the John's answer is correct, you're not using the return values properly, but you are neither accesing the variables properly, for example, I don't see where $row comes from. Try this and change it for array mode if you need to. I'm not very used to mysqli_* API, because I use PDO mostly.
if ($result) {
while($row = $result->fetch_object()) {
$bg_url = $row->bg_url;
}
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
echo $bg_url;

$_GET not inserting into MySQL database

I have a small PHP script which I would like to use to add a value to an SQL table.
When I do something like: http://ipaddress/phptest.php?350
If I just put 350 into the insert statement, it works fine. I have tried to get the result of GET to be added but seem to be unable to after many attempts.
I either get a blank, or "array" added to my table.
Any help would be appreciated.
Also how would I add two values? phptext.php?350&?450 for example?
Thanks
<?php
$servername = "localhost";
$username = "administrator";
$password = "blabla";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
print_r($_GET);
if($_GET["a"] === "") echo "a is an empty string\n";
if($_GET["a"] === false) echo "a is false\n";
if($_GET["a"] === null) echo "a is null\n";
if(isset($_GET["a"])) echo "a is set\n";
if(!empty($_GET[a])) echo "a is not empty";
$sql = "INSERT INTO test.sensor (VALUE) VALUES ('$_GET["a"]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The HTTP specification declares that GET variables are passed like the following example:
url.com/?bar=value&foo=value
So technically you're passing the GET values wrong. As I see, the correction would be:
http://ipaddress/phptest.php?a=350
Also, as an extra pointer, sanitize your variables before submitting to a SQL database, as it will lead to SQL injection vulnerabilities.
You might want to use...
mysqli_real_escape_string();
Or use prepared statements, the more accepted/fail-safe way of working with them.
For more reference,
http://php.net/manual/en/mysqli.real-escape-string.php

I need help identifying why i cant query these $_get variables into sql

<?php
$kundenr = $_GET["kundenr"];
$kundenr = mysql_real_escape_string($kundenr);
$kundenavn = $_GET["kundenavn"];
$kundenavn = mysql_real_escape_string($_GET["kundenavn"]);
$servername = "random";
$username = "random";
$password = "random";
$dbname = "random";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customerbase (kundenr, kundenavn) VALUES('$kundenr','$kundenavn')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
echo "<br>" . $sql;
echo "<br>" . $kundenr;
echo "<br>" . $kundenavn;
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
output of the above is as follows :
New record created successfully
INSERT INTO telefoncentral (kundenr, kundenavn) VALUES('','')
i cant for the love of god figure out why it wont put in the values
can anyone see the error? im going mildy crazy here
URL line it gets is new.php?kundenr=0236&kundenavn=Peter
mysql_real_escape_string() requires a mysql_connect() connection in order to work, since you're only contacting the database later in the script, no such connection will be available. You should only call this function in the place where you are inserting data.
Furthermore you're mixing the mysql_ extension with the mysqli_ extension, you'll want to use something like $conn->escape_string() in your code.
Ideally you should not use real_escape_string at all, but instead read up on what prepared statements are.

Categories