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
Related
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.
Good day,i am trying to insert data into mysql table using php its kinda working but i can't see data in phpmyadmin
<?php
$con=mysqli_connect('localhost','root','');
if(!$con)
{
echo("not connected");
}
if(!mysqli_select_db($con,'exam'))
{
echo 'db not selected';
}
$header = $_POST['header'];
$date = $_POST['date'];
$categ = $_POST['categ'];
$moder = $_POST['moder'];
$posttxt = $_POST['posttxt'];
$theme = $_POST['theme'];
$author = $_POST['author'];
$sql = "INSERT INTO postex (header,date,categ,moder,posttxt,theme,author) VALUES ('$header','$date','$categ','$moder','$posttxt','$theme','$author')";
if
(empty($header) || empty($date) || empty($categ) || empty($moder) || empty($posttxt) || empty($theme) || empty($author))
{
echo "<Br>feel the fields!!!";
}
else{
echo("<br>added,wait for redirect");
}
?>
Ok, before anymore wrong answers come up using mysql_, it's mysqli_query($con, $sql) that wasn't used to execute the query.
RTM http://php.net/manual/en/mysqli.query.php
and take care of that sql injection that you're leaving yourself open to, if/when you go live with this.
https://en.wikipedia.org/wiki/SQL_injection
with a prepared statement
https://en.wikipedia.org/wiki/Prepared_statement
while making sure the POST arrays do contain values (and the form uses a POST method with matching named inputs) and that there are no characters passing through that MySQL could complain about, for example: apostrophes.
Escape the data going in, in any respect.
Check for errors via PHP and the query:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
Nota:
You should first check if any of the fields are (not) empty, then execute the query.
I.e. and pseudo conditionals:
if(none empty and good to go){
// execute the query
}
else{
// do something else
}
Plus, if you're using your entire code inside the same file, being the form and php/mysql, then you should check if any of the POST arrays are set/not empty first. That will throw a few errors and give you undesired results.
<?php
function db(){
$servername = "servername";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = new mysqli($servername, $username, $password,$database);
$conn->query("SET CHARACTER SET utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
return $conn;
}
}
$data=db();
$insert="INSERT INTO movies (bla1, bla2, bla3) VALUES (blavalue1, blavalue2, blavalue3)";
$dotaz=mysqli_query($data,$insert);
if($dotaz){
echo "OK";
}else{
echo "Wrong";
}
?>
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.
In my code, there are two different queries. The first one is working - by which I mean it goes to the if path. The problem is with the second one which goes to the else path.
$adding_user_email=$arr[1];
$sessionuserid=$_SESSION['login_user_id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO modes (userid,modename) VALUES ('$sessionuserid','".$arr[0]."')";
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='".$arr[1]."'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='$adding_user_email'";
if ($conn->query($sqlmodeid_uderid) === TRUE) {
echo "userid fetched successfully";
} else {
echo "Error: " . $sqlmodeid_uderid . "<br>" . $conn->error;
}
$conn->close();
Help me out. (query is working fine)
The condition is a problem:
$conn->query($sqlmodeid_uderid) === TRUE
If we consult the documentation for the query function we will see:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
As you are dealing with a SELECT query, this call will never return true. It will return a mysqli_result object on success, and false on failure.
Instead you could rewrite this condition in a number of ways.
Check the query does not return false.
if ($conn->query($sqlmodeid_uderid) !== FALSE) {
Use == instead of ===. The first will cast between two different types (and the mysqli_result object will equate to true when casted to bool) whereas === performs a typesafe comparison, meaning the condition will only be satisfied if both operands are of the same type and have the same value.
if ($conn->query($sqlmodeid_uderid) == TRUE) {
The same logic in point 2 can be wrote in a few different ways:
if ($conn->query($sqlmodeid_uderid)) {
if ((bool)$conn->query($sqlmodeid_uderid)) {
I would look at the php.net documentation on comparison operators for more info on this:
http://php.net/manual/en/language.operators.comparison.php
Use code like this...
$adding_user_email=$arr[1];
$sessionuserid=$_SESSION['login_user_id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO modes (userid,modename) VALUES ('$sessionuserid','".$arr[0]."')";
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='".$arr[1]."'";
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='$adding_user_email'";
For the second query, I think you should do like this instead of doing "=== TRUE"
$sqlmodeid_uderid = "SELECT userid FROM register where useremail='$adding_user_email'";
/* Select queries return a resultset */
if ($result = $conn->query($sqlmodeid_uderid)) {
echo "userid fetched successfully";
} else {
echo "Error: " . $sqlmodeid_uderid . "<br>" . $conn->error;
}
Look at the examples in the doc : http://php.net/manual/en/mysqli.query.php
<?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.