The query below is not inserting the variables into MySQL. I know that the function valid_email2 works because I put a non-email address into $inviteeemail and it redirected per the code below.
I know that I have the right MySQL connection string.
Any idea why nothing is being put into MySQL?
$invitorname = $_POST['invitorname'];
$inviteename = $_POST['inviteename'];
$inviteeemail = $_POST['inviteeemail'];
$uid = $_POST['uid'];
$subcheck = (isset($_POST['subcheckinvite'])) ? 1 : 0;
if ( ! valid_email2($inviteeemail))
{
session_write_close();
header("Location:http://www...com/.../file.php");
exit;
}
else
{
mysql_query("INSERT INTO invites VALUES (NULL, '$uid', '$inviteeemail', '$invitorname', '$inviteename', NULL, '$subcheckinvite', NULL)");
}
In your query you have $subcheckinvite but you're setting it as $subcheck at the beginning of your script. Maybe that's it.
Does the fields that you insert NULL for, can be null?
Check the return value of mysql_query. If it is false, then the query was not valid, and you can print mysql_error() to see the error message.
It's not unlikely that this stems from the fact that you're not escaping any of the user input. Aside from allowing someone to completely change your query by carefully crafting the form inputs, your query will simply fail if any of the fields contain a single quote mark.
Besides fixing your error, you should consider improving the quality of your code.
You use variables that don't exist ($checksubinvite)
You insert NULLs into columns rather than simply specifying which columns you do want to insert into
You do not validate all of the inputs
You have single quotes around what are likely numeric columns
You have enormous amounts of whitespace and inconsistent indentation
...etc.
Related
The code below is very simple. PHP uses POST to collect a string from a form, which I am then looking to trim and run a preg_replace function which will strip any special characters except a single quote or a hyphen. Bare in mind that the entire code works fine without the involvement of the quotes or hyphen in the regex expression.
preg_replace("/[^\w\s'-]/", '', $raw_lemurName);
Those clean variables are then inserted into a database. Apache/2.4.37. MariaDB.
When I make lemurName a string like "Diademed Sifaka<>!", it works, and returns 'Diademed Sifaka'.
When I make it a string including a single quote, however, like "Coquerel's Sifaka" the operation doesn't complete and no information is inserted.
I have tested the regex expression on its own and it works fine, it seems that when you begin to involve SQL and databases that it ceases to work.
Worth noting:
using phpMyAdmin. If I insert the string on there it works fine so my database can hold those values.
Tried using mysqli_real_escape_string() in various places, but have had no luck, perhaps doing it wrong.
Reading around, I think it has something to do with SQL not allowing strings with single quotes being inserted and that the server automatically escapes single quotes in the post method.
Any ideas?
Much appreciated.
$raw_lemurName = isset($_POST['lemurName']) ? $_POST['lemurName'] : null;
$raw_lemurLat = isset($_POST['lemurLat']) ? $_POST['lemurLat'] : null;
$raw_family = isset($_POST['family']) ? $_POST['family'] : null;
//the regex expression below seems to be messing something up
$c_lemurName = trim(preg_replace("/[^\w\s'-]/", '', $raw_lemurName));
$c_lemurLat = strtolower(trim(preg_replace('/[^\w\s]/', '', $raw_lemurLat)));
$c_family = trim(preg_replace('/[^\w\s]/', '', $raw_family));
if (isset($_POST['submit'])) {
$query1 = "INSERT INTO `lemurs` (`id`, `lemur`, `latin`, `family`) VALUES (NULL, '$c_lemurName','$c_lemurLat','$c_family')";
$run_query = mysqli_query($connection, $query1);
if($run_query){
echo "Data has been inserted";
} else {
echo "Operation Unsuccessful";
}
header("location: index.php");
return;
}
This is a standard SQL injection problem. The issue stems from the way you are getting these variables into your query:
$query1 = "INSERT INTO `lemurs` (`id`, `lemur`, `latin`, `family`) VALUES (NULL, '$c_lemurName','$c_lemurLat','$c_family')";
Think about exactly what is happening here, all you are doing is concatonating strings together, so if $c_lemurName is ' - then your SQL will become:
[...] VALUES (NULL, ''', '[...]
This actually really opens you up to what is called an "injection attack". Basically, a malicious user could set $c_family to something like... ');drop table lemurs;-- - you are now executing an insert statement, and then a drop table statement, with the rest of your SQL being a comment.
There are several ways to combat this, the most frequently advised way is to look into paramaterised queries - which for the mysqli library have to be done through prepared statements. There's an example of this on the PHP docs page.
replace the single quotation marks from 2nd params area as well. use this.
preg_replace("/[^\w\s'-]/", "", $raw_lemurName);
hope it will work
$q = "INSERT INTO subjects (menu_name, position, visible) VALUES ('{$mname}', {$pos}, {$vis}) ";
if(mysql_query($q)) {
header("Location: content.php");
}
else {
echo mysql_error();
}
Here, $mname is a string. $pos and $vis are integers.
Where is the mistake?
try to use only single quote to query variable rather pseudo(i think pseudo variable needs to be also quoted for query) like
$q= "INSERT INTO subjects (menu_name, position, visible) VALUES ('$mname', '$pos', '$vis')";
If you're going to use braces to try and prevent the greedy nature of variable expansion, you should use them properly.
The string "{$pos}", when $pos is 42, will give you "{42}", which is clearly not a valid integer in terms of your SQL statement. What you're looking for is instead:
${pos}
In this case, of course, you don't actually need the braces since the characters following the variable name cannot be part of a variable name - they are, respectively, ', , and ).
You only need to use braces when the following character could be part of a variable name. For example, consider:
$var = "pax";
$vara = "diablo";
In that case, $vara will give you diablo while ${var}a will give you paxa.
And I give you the same advice I seem to give weekly here :-) If you have a query that's not working, print it out! You'll find that the problem will usually become immediately obvious once you see the query in the final form you're passing to the DBMS.
And, as per best practices, I'll advise against using this method of creating queries. Anyone that's investigated SQL injection attacks (google for sql injection or, my favourite, little bobby tables) soon learns that they should use parameterised queries to prevent such attacks.
you are missing ' sign as the error says.
$q = "INSERT INTO subjects (menu_name, position, visible) VALUES ('$mname', '$pos', '$vis') ";
The value will be stored to table. Just make datatype to int in mysql table if you want it to be integer and make validation not to enter string while inserting.
You cannot name a column name whenever you run something through MySQL. One way to check is to run the query within HeidiSQL. MySQL functions will be highlighted blue, so you know if the column name becomes blue to not use it. Also; Here's a quick run of PDO to make things a little bit better; I'd suggest looking further into it as well.
public function MakeMenu() {
$q = <<<SQL
INSERT INTO subjects (menu_name,_position,visible)
VALUES(":menu_name","_position","visible")
SQL;
$resource = $this->db->prepare( $query );
$resource->execute( array (
'menu_name' => $_POST['menu_name'],
'_position' => $_POST['position'],
'visible' => $_POST['visible'],
));
}
To make things easy enough you can just make a call.php page as well. Make the calls.php page require your class page and add a hidden input to your form. IE
<input type=hidden" id="process" value="make_menu">
Then within the calls.php page add
if ( isset($_POST['process']) )
{
switch ($_POST['process'])
{
case 'make_menu':
$class->MakeMenu();
break;
I know this isn't just a quick answer, but I'm hoping you'll look further into what's happening here and move away from mysql functions. I have seen posts from people running IIS servers and not having any luck with any of the deprecated functions. Not sure how long it will be until Apache follows suite, but don't waste your time with something that's being deprecated as we speak.
I have a login script in which I also execute a query to log when and from where people try to log in to my site. This little piece of code doesn't return any errors and the header works, but the query doesn't work for some reason. Does anyone have any idea what I'm doing wrong?
if($count==1){
$securityquery = "INSERT INTO security_kk (action,datetime,country,IP,Affected table,comment) VALUES (:action,:datetime,:country,:IP,:Affected_table,:comment)";
$q = $db->prepare($securityquery);
$q->execute(array(':action'=>"Login",
':datetime'=>$datetime,
':country'=>$country,
':IP'=>$_SERVER['REMOTE_ADDR'],
':Affected_table'=>"members",
':comment'=>"Authenticated as ".$myusername));
$_SESSION['username'] = $myusername;
$_SESSION['privileges'] = $row['privileges'];
$_SESSION['email'] = $row['email'];
header("location:index.php");
}
I'm a beginner at PDO, but since there are no errors. I don't know where to look.
datetime is a data type in MySQL. Wrap that column identifier in ticks. Also, column identifiers with spaces in their name must be wrapped in ticks.
$securityquery = "INSERT INTO security_kk (`action`,`datetime`,`country`,`IP`,`Affected table`,`comment`) VALUES (:action,:datetime,:country,:IP,:Affected_table,:meta)";
Your error (or possibly one of the errors) is the difference between
:meta // your query contains this
and
':comment'=>"Authenticated as ".$myusername;
Your array has no value for the placeholder named :meta
It doesn't hurt to check for errors using the error checking functions though, rather than having others try to figure out a simple typo.
while there aren't any errors
Because you aren't checking for them.
DateTime is a datatype of mysql.
check your Affected table column name - No space in column name
best way to use like below.
$securityquery = "INSERT INTO security_kk (action,[datetime],country,IP,Affected table,comment) VALUES (:action,:datetime,:country,:IP,:Affected_table,:meta)";
I have a database. I had created a a table containing only one row in DB if it wasn't constructed before.
Why it has only 1 row is that I just use it to keep some info.
There is a field of TYPE NVARCHAR(100) which I want to use it to store session id,
and here comes the headache for me:
It seems that I can't even properly INSERT(I use phpmyadmin to check and it's blank) and UPDATE(syntax error...) it with a session id obtained from session_id(), which is returned as a string.
Here is the portion of my code relating to my action:
//uamip,uamport is in URL;I use $_GET[]
$_SESSION[uamport] = $_GET['uamport'];
$_SESSION[uamip] = $_GET['uamip'];
**$_SESSION[sid] = session_id();**
//construct
$sql="CREATE TABLE trans_vector(
`index` INT NOT NULL AUTO_INCREMENT,
`sid` NVARCHAR(100),
`uamip` CHAR(15),
`uamport` INT,
PRIMARY KEY (`index`)
)" ;
mysql_query($sql);
//insert(first time, so not constructed)
$sql="INSERT INTO trans_vector (sid,uamip,uamport) VALUES(
'$_SESSION[sid]',
'$_SESSION[myuamip]',
'$_SESSION[myuamport]'
)";
mysql_query($sql);
//update(from 2nd time and later, table exists, so I want to update the sid part)
$sql="UPDATE trans_vector SET sid="**.**$_SESSION[sid];
mysql_query($sql)
Now, when I use phpmyadmin to check the sid field after INSERT or UPDATE, It is blank;
But if I do this:
$vector=mysql_fetch_array(mysql_query("SELECT TABLES LIKE 'trans_vector'"));
and echo $vector[sid] ,then it's printed on webpage.
Another question is:
With the UPDATE statement above, I always get such error:
"Unknown column xxxxxx....(some session id returned, it seems it always translate it first and put it in the SQL statement, ** treating it as a column NAME** that's not what I want!)"
I tried some TYPE in CREATE statement, and also lots of syntax of the UPDATE statement(everything!!!) but it always give this error.
I am dealing trouble with ' and string representation containing a variable where the latter's value is actually what I want... and maybe the problem arise from type in CREATE and string representation in UPDATE statement?
Should CAST() statement helpful for me?
Wish you can help me deal with this...and probably list some real reference of such issue in PHP?
Thanks so much!!
$insert = "INSERT INTO trans_vector (`sid`, `uamip`, `uamport`) VALUES(
'".$_SESSION["sid"]."',
'".$_SESSION["myuamip"]."',
'".$_SESSION["myuamport"]."'
)";
this should solve at least some warnings, if not errors.
and for update...
$update = "UPDATE trans_vector SET `sid`='".$_SESSION["sid"]."';";
Notes about your code:
Array values have to be put into the string with operator '.' and cannot be inserted directly. Array indexes must be strings (note the ") or integers.
Column names should have `` around them. To insert a string with SQL, you have to put string into ''s, so the parser knows what is string and what column name. Without ''s parser is assuming you are stating a column.
and for mysql_escape_string, I assumed you handle that before storing data to sessions. Without those, you might can get unwanted SQL injections. And in case you did not do that, you can either do that (before you create queries):
foreach($_SESSION as $key => $value)
$_SESSION[$key] = mysql_escape_string($value);
or manually escape strings when you create a query.
As for the update statement, it’s clear that there are apostrophes missing. You always need apostrophes, when you want to insert a string value into the database. Moreover, you should use mysql_real_escape_string.
However, I think standard mysql is deprecated and has been removed in newer versions of PHP in favor of MySQLi and PDO. Thus you should switch to MySQLi or PDO soon.
You should also use apostrophes when referencing values within $_SESSION. Otherwise PHP will try to find a constanst with the name sid and later fallback to the string 'sid'. You will get into trouble if there once really is a constant called sid defined.
Here, the corrected update statement in mysql library:
$sql = "UPDATE trans_vector SET sid='" . mysql_real_escape_string($_SESSION['sid']) . "'";
Even better:
$sql = "UPDATE `trans_vector` SET `sid`='" . mysql_real_escape_string($_SESSION['sid']) . "'";
Using backticks makes clear for MySQL that this is a column name. Sometimes you will have column names that are called like reserved keywords in SQL. Then you will need apostrophes. A common example is a column called order for the sequence of entries.
I've got the following code:
<?php
if(!empty($error_msg))
print("$error_msg");
else
{
require_once("../include/db.php");
$link = mysql_connect($host,$user,$pass);
if (!$link)
print('Could not connect: ' . mysql_error());
else
{
$sql = "insert into languages values(NULL,'$_POST[language]','$_POST[country_code]');";
$res = mysql_query($sql);
print("$sql<br>\n");
print_r("RES: $res");
mysql_close($link);
}
}
?>
In one word: it does not work. mysql_query doesn't return anything. If I try the same
query within php_myadmin, it works. It does not insert anything either. Also tried it as
user root, nothing either. Never had this before. Using mysql 5.1 and PHP 5.2.
Any ideas?
mysql_query will return a boolean for INSERT queries. If you var_dump $res you should see a boolean value being printed. It will return TRUE for a successful query, or FALSE on error. In no cases it ever returns NULL.
In addition, never pass input data (e.g.: $_POST) directly to an SQL query. This is a recipe for SQL injection. Use mysql_real_escape_string on it first:
$language = mysql_real_escape_string($_POST['language']);
$sql = "INSERT INTO language SET language='$language'";
And don't forget to quote your array indices (e.g.: $_POST['language'] instead of $_POST[language]) to prevent E_NOTICE errors.
You need to specify a database so the system knows which database to run the query on...
http://php.net/manual/en/function.mysql-select-db.php
Without selecting a database, your data will not be inserted
mysql_query returns a boolean for INSERT queries. If used in string context, such as echo "$res", true will be displayed as 1 and false as an empty string. A query error has possibly occured. Use mysql_error() to find out why the query has failed.
$sql = "insert into languages values(NULL,'$_POST[language]','$_POST[country_code]');";
This is very bad practise, as a malicious user can send crafted messages to your server (see SQL Injection).
You should at least escape the input. Assuming your column names are named 'language' and 'country_code', this is a better replacement for the above code:
$sql = sprintf('INSERT INTO LANGUAGES (language, country_code) VALUES ("%s","%s")',
mysql_real_escape_string($_POST['language']),
mysql_real_escape_string($_POST['country_code'])
);
For a description of the mysql_real_escape_string function, see the PHP Manual. For beginners and experienced programmers, this is still the best resource for getting information about PHP functions.
Instead of using $_POST directly, I suggest using the filter_input() function instead. It's available as of PHP 5.2.
With an INSERT query, mysql_query returns true or false according as the query succeeded or not. Here it is most likely returning false. Change the line print_r("RES: $res"); to print_r("RES: ".(int)$res); and most likely you will see it print RES: 0.
The problem may be that MySQL expects a list of column names before the VALUES keyword.
Also, you appear to be inserting POST variables directly into SQL - you should read up on SQL injection to see why this is a bad idea.
--I retract the quote comment, but still not good to directly insert $_POST values.--
Second, I don't think i've seen print_r quite used like that, try just using an echo.
And mysql_query is only expected a boolean back on an INSERT, what are you expecting?
Now ive got this:
$language = mysql_real_escape_string($_POST['language']);
$country_code = mysql_real_escape_string($_POST['country_code']);
$sql = "insert into shared_content.languages (id,language,country_code) values(NULL,$language,$country_code);";
$res = mysql_query($sql);
print("$sql<br>\n");
var_dump($res);
print(mysql_error());
mysql_close($link);
And the output:
insert into shared_content.languages (id,language,country_code) values(NULL,NETHERLANDS,NL);
bool(false) Unknown column 'NETHERLANDS' in 'field list'