What I am Trying to do
What I am attempting to do is, pass values from my python application to my web api where it gets saved to my database.
The problem
The reason why I am posting is because, I can send integers, 1,2,3 to my database from my python and that saves fine. But If I send "test","ape","tree" nothing is placed in the database. (PS, the data type is varchar(6) )
I can also pass string into the database (using post) from the browser and it works.
What have done
I have created my API , database and python script that passes the data around.
Python.
import requests
load={'par':'ape12'} //This doesnt save "ape" to the database
#load={'par':'3'} //This saves "3" to the database
r=requests.post("http://my-server.com/load.php",data=load)
PHP
<?php
//Connect to DB
include ("connectDB.php");
$loadgot=$_POST['load'];
mysqli_query($con,"INSERT INTO detect(l_result)
VALUES ($loadgot)");
mysqli_close($con);
?>
Hoping someone could assist me in this regard.
Thank you
You need to pass a properly formed query to mysql. The value needs to be surrounded by quotes, but also needs to escape any characters which will break out from the quoted environment. In practice, the best solution these days is to use parametrised queries (see example) like:
$stmt = mysqli_prepare($con, "INSERT INTO detect(l_result) VALUES (?)");
mysqli_stmt_bind_param($stmt, $loadgot);
mysqli_stmt_execute($stmt);
Or if you really want to use text query (you really shouldn't), you can do:
$loadgot_safe = mysqli_real_escape_string($con, $loadgot);
mysqli_query($con,"INSERT INTO detect(l_result) VALUES ('$loadgot_safe')");
The reason why you MUST NOT use:
mysqli_query($con, "INSERT INTO detect(l_result) VALUES ('$loadgot')");
is that anyone can submit multiple values - for example value1'), ('value2 will expand to INSERT INTO detect(l_result) VALUES ('value1'), ('value2') - which is definitely not what you want.
Modify the 'ape12' to "'ape12'".
Because, in MySQL we give the query like this
INSERT INTO detect(l_result) VALUES 'Value1';
So pass the values to MySQL with quotes. But no need for the integers.
From #e4c5 comment. Users wont give the quotes while entering the input. So we ensure the query inside the script. So try to changed the code like this
mysqli_query($con,"INSERT INTO detect(l_result) VALUES ('$loadgot')");
Related
So I am trying to send data entered in a single form to multiple tables using multiple queries but it is not working. I have the connection thing working right and this way it works fine for one query but the problem comes when I try to use multiple tables, like getting data and sending it to multiple tables
What I have done so far is:
$qry= "INSERT INTO register VALUES (DEFAULT, '".$email."', '".$passw."')";
$qry = "INSERT INTO personalinformation VALUES (DEFAULT, '".$name."',
'".$fname."', '".$age."', '".$gender."', '".$cnic."',
'".$mobileno."','".$address."', '".$appearencestatus."')";
Kindly help.
Thank you so much
With PDO you'd do something like:
$stmt = $db->prepare("INSERT INTO register (email, password) VALUES (:email, passw)";
$stmt->execute(array('name' => $name, 'email' => $email))
Once for each query. It's important to always specify the columns you're inserting against, it avoids ambiguity when your schema changes for some reason plus the crufty DEFAULT junk in there.
Try to prepare directly from a string, don't make intermediate variables for this sort of stuff. Those can easily get confused, over-written, and tangled up in your code.
Did you create a database connection? And did you execute the query with mysqli_query ? Try troubleshooting by echoing out the composed query, and copy pasting it in mysql console or in php myadmin.
Here is a sample:
$con = mysqli_connect('hostname', 'username', 'password', 'dbname');
Your queries composition code: Then
mysqli_query($con, $queryvariablename);
--
P.S make sure you use different variable names for different queries or else the second one will overrite the previous one.
I am trying to insert a data from a form which has about 1990 characters into mysql. How ever the insert is not working. when i var_damp the content of the variable is shows the correct content. When i set it to an empty string the insert works. I have done my research and still can't get ti to work. I am not trying to upload a file. This characters are from a textarea in my form.
Below is the insert code:
if (isset($_POST['val'])) {
$score = $_POST['val'];
$course = $_POST['course'];
$mysqli->query("INSERT INTO `evaluate` (`id`, `course`, `score`) VALUES (Null, '$course', '$score')");
Note: is score column has type TEXT in the database.
This is a common problem because most introductions to mysqli don't cover it right away even when it should be the first thing you learn. Inserting into any database, especially SQL, requires carefully escaping the values you're supplying. The way these are escaped varies depending on the platform, but the good news is that mysqli can handle it for you.
The key is using prepared statements:
$stmt = $mysqli->prepare("INSERT INTO evaluate (course, score) VALUES (?,?)");
$stmt->bind_param('ss', $_POST['course'], $_POST['val']);
$stmt->execute();
Now it's best to enable exceptions so that any errors are not ignored. Once in a while we all make little mistakes that can be a giant pain to track down if there isn't any warning about them. Exceptions make a lot of noise.
If you're just getting started with PHP and databases, you might want to evaluate using PDO which is significantly better than mysqli for a number of reasons, or a higher level database layer like Doctrine or
Propel which make using the database a lot more pleasant.
I have a single quote (') in the text and not escaping it meant that the SQL statement was been interpreted wrongly
The correct way to go, and you must always do this, is:
$score = $mysqli->real_escape_string($_POST['val']);
$course = $mysqli->real_escape_string($_POST['course']);
$mysqli->query("INSERT INTOevaluate(id,course,score)VALUES (Null, '$course', '$score')");
Hi I'm trying to post values from a page into a MySQL DB, however the password field has to be encrypted via the encrypt command.
So far I have this -
$sql="INSERT INTO `ftpuser` (`userid`, `passwd`, `uid`, `gid`, `homedir`, `shell`, `count`, `accessed`, `modified`)
VALUES
('$_POST[userid]', encrypt(".$_POST['passwd']."),'$_POST[uid]','$_POST[gid]','$_POST[homedir]','$_POST[shell]','$_POST[count]','$_POST[accessed]','$_POST[modified]')";
The script connects to the DB fine, however the output is "Error: Unknown column 'test34' in 'field list'"
Thanks.
This statement:
encrypt(".$_POST['passwd'].")
doesn't have any quotes around the value, so mysql gets it as a column name. For example, if your password is test123, this part of query would look like:
encrypt(test123)
while what you really need is
encrypt('test123')
So, you can fix this problem just by adding single quotes
$sql="INSERT INTO `ftpuser` (`userid`, `passwd`, `uid`, `gid`, `homedir`, `shell`, `count`, `accessed`, `modified`)
VALUES
('$_POST[userid]', encrypt('".$_POST['passwd']."'),'$_POST[uid]','$_POST[gid]','$_POST[homedir]','$_POST[shell]','$_POST[count]','$_POST[accessed]','$_POST[modified]')"
However, there is much bigger problem in this code. You don't escape the values, therefore open an SQL injection. Just think what would happen if your password contains a single quote, such as test'123:
encode('test'123')
This is obviously a syntax error. In fact it allows anyone to execute arbitrary SQL expressions by crafting special parameters in $_POST.
So what you really should do is either escape everything you put into query or use PDO with placeholders. Check for example, this tutorial http://www.phpeveryday.com/articles/PDO-Positional-and-Named-Placeholders-P551.html
I have been writing a script in PHP to take values from a form and store them in a MySQL table I created in the code, like this:
mysql_query("CREATE TABLE `userdetails` ( userid VARCHAR(10), field1 CHAR(33), field2 CHAR(33), field3 VARCHAR(34)");
This only executes once, as I don't have access to the site's cPanel or phpMyAdmin, just the FTP server details. I collect strings from three text boxes, and then delete the current contents.
mysql_query("DELETE FROM `userdetails` WHERE userid=$userid");
Next, I upload the strings to the MySQL server like this:
mysql_query("INSERT INTO `userdetails` (`userid`, `field1`, `field2`, `field3`) VALUES ($userid, $field1, $field2, $field3)")
With this script, I can get numbers to go on the database fine, but whenever I use a letter in the text box, it doesn't upload and the database field returns to NULL, I think.
From a little debugging, I can tell that the strings are storing the text box data fine, I can echo them and they display, with letters. It just doesn't upload. I have tried making a new table and trying again, that didn't work.
You are vulnerable to SQL injection attacks, and are building an incorrect query.
Consider:
$userid = 'foo';
produces
mysql_query("DELETE .... WHERE user=foo");
You probably don't have a field named foo in your database, so the query fails. Since you obviously lack ANY kind of error handling, you'll never see the database spit your query back out at you with the syntax error highlighted.
At bare minimum, you need
mysql_query("DELETE ... WHERE user='$userid'"); // note the quotes
and some error handling
$result = mysql_query(...) or die(mysql_error());
And you really should go read http://bobby-tables.com before someone pwns your server via your badly written scripts.
I have a PHP cart that was pre developed by a company, while ordering, I added an extra field for extra information, the $_POST value of it simply gets added onto the variable $post['attr'], however when that gets serialised and put into a DB it errors if it contains things like %, !, $, etc. well it doesnt error, it sends out pending order email, takes them to paypal, lets them pay, and never verifies that the prder is actually in the DB, which its not if it had special chars in it...
I have tried different ways and read that base64 encoding can help, however that would mean scraping a lot of pre existing orders and re doing a lot of the system, anyone could help?
Thank you!
The problem you're having is that the data isn't be escaped. I'm guessing you're doing something like:
$sql = "INSERT INTO mytable (something) VALUES ('". $something ."')";
$result = mysql_query($sql);
What you need to do is escape the variable first:
$sql = "INSERT INTO mytable (something) VALUES ('". mysql_real_escape_string($something) ."')";
$result = mysql_query($sql);
My example uses MySQL, but similar functions exist for all supported databases.
Use the correct function for your database. Do not just use url encoding, or generic string escaping. The characters that need to be quoted are database-specific.