PHP Mysqli Interpreting Array Value As Mathematical Equation - php

I can't seem to escape an array value when attempting to upload an array value into a database. PHP is interpreting it as a mathematical equation instead of the 'minus' symbol to which is what I wish to upload. It's resulting in error and failing to upload instead.
$aDataTableDetailHTML[0]['OTG'] prints out as the minus symbol: -
$sql = "INSERT INTO MYTABLE (status) VALUES (".$aDataTableDetailHTML[0][OTG].")";
My understanding is that I need to 'escape' the specific value in order for PHP to ignore processing it as a math value, however, when I do this it resolves as blank or nothing.
$OTG = mysqli_real_escape_string($con, $aDataTableDetailHTML[0]['OTG']);
I'm guessing this is painfully easy and I'm missing something obvious. Any suggestions?

It's not PHP mis-interpreting your value, it's MySQL. You query as currently written will get sent to MySQL as:
INSERT INTO MYTABLE (status) VALUES (-)
which is invalid MySQL. You just need to put the value into quotes:
$sql = "INSERT INTO MYTABLE (status) VALUES ('".$aDataTableDetailHTML[0][OTG]."')";
That will prevent MySQL interpreting it as anything other than a string.

Related

INSERT INTO sql query is using variable string rather than field name

Getting really confused surrounding this INSERT INTO. It should insert three fields into the table, userID, activateKey and isActivated.
The activateKey is a 25 letter randomly generated key such as 63n20kw24ba1mlox34e8n2awv
The userID comes from another table and is set by auto_increment.
The isActivated is always 0 at this stage.
It seems like quite a simple INSERT statement
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES (".$userID.",".$activateKey.",'0')"))
{
echo("Error description: " . mysqli_error($con));
}
However it doesn't work when I include the $activateKey field. What it does is try to search the string variable $activateKey as a column name. The error I get is:
Error description: Unknown column '63n20kw24ba1mlox34e8n2awv' in 'field list'
Of course there is no such column as 63n20kw24ba1mlox34e8n2awv, this is the data I'm trying to insert, hence why it's in the VALUES section. Any ideas why it's trying to search this as the column name?
Edit to clarify: the var is activateKey, the column name is activationKey
I would put the query in a different variable to avoid confusion, and PHP automatically substitutes variable names in strings in double quotes.
Try this:
<?php
$query = "INSERT INTO activations (userID,activationKey,isActivated) VALUES($userID,'$activateKey','0')
if (!mysqli_query($con,$query)
{
echo("Error description: " . mysqli_error($con));
}
You are not surrounding the values with quotes, that's why they get interpreted as variable names.
Use single quotes, like this:
"INSERT INTO activations (userID,activationKey,isActivated) VALUES
('".$userID."','".$activateKey."','0')"
However, be aware that stringing together query strings exposes you to SQL injection attacks, if that's a concern in your code you should use parameterized queries. In fact, using parameterized queries is always better.
Change your query to this:
"INSERT INTO activations
(userID,activationKey,isActivated)
VALUES ('$userID','$activateKey','0')"
You dont need to use the concatenation (.) operator as variables will be interpolated into the string.
The single quotes tell mysql to treat the variables as literals instead of column names.
As a side note you would be better to use parameterized queries. See How can I prevent SQL injection in PHP?
Solved!
It was a case of not properly wrapping the dynamic fields (the vars in the VALUES section) in ticks:
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES ('".$userID."','".$activateKey."','0')"))
Instead of
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated) VALUES (".$userID.",".$activateKey.",'0')"))
Might be a difficult one to spot. The variables still need to be 'in ticks' or they won't register as strings.
As activationKey is a string column, you must use single quotes for $activationKey.
Try with:
if (!mysqli_query($con,"INSERT INTO activations (userID,activationKey,isActivated)
VALUES (".$userID.",'".$activateKey."','0')"))

update the session field in database

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.

Displaying fields from MySQL table but no field with quotes being printed

I am fetching data from a MySQL table to display it on a page. The script is displaying the information, but in my table normal quotes we're inserted as another type of quote characters such as. ( ’ ) and ( β€œ ” ) which are automatically formatted this way when something is typed in Microsoft Word 2010, which was used to type most of the entries in the table. So my guess are those are special characters. But whenever i test out displaying a field with actual single quotes ( ' ) and ( " " ) i receive a mysql_fetch_row expects parameter 1 to be a resource, boolean given error. This is the code i use:
$result = mysql_query("SELECT `question` FROM {$db_table_alt}");
while($field = mysql_fetch_row($result)) {
foreach($field as $fields) {
//build a unique section ID based on the ID that the Question belongs to
$uid = mysql_query("SELECT `id` FROM `questions` WHERE `question` LIKE '%$fields%'");
while($uidfield = mysql_fetch_row($uid)) {
But whenever i use this line
$fields = mysql_real_escape_string(stripslashes($fields));
The field with real quotes will display, but with forward slashes before the quote.
Can somebody help me find a solution to this please?
If mysql_fetch_row() is complaining about a boolean that means mysql_query either returned no rows or the SQL had an error (mysql_error() will tell you which).
If you're getting backslashes before the quotes in your returned data, then they are getting put in the database. That sounds like magic_quotes are enabled. You really want to turn that off as it's an obsolete and broken solution to a problem.
Also, I think you're going to have to learn about character encodings. A default MySQL install will be not be UTF8, I'm afraid, it will probably be ISO-8859-15. Word used to like writing text in Windows-1252 which is not the same. And then it gets more complicated with whatever browser, website and other things that talk to the database use. I believe PhpMyAdmin tries to run in UTF8, so data will get converted into your tables if they're not UTF8. This will also affect your queries looking for the "smart quotes".
You seem to have two distinct problems here.
One where $result is evaluating to a boolean, which means there is an error in the query generated (SELECT question FROM {$db_table_alt}). Try echoing that query out and manually running it. It may be that the table/view named by {$db_table_alt} does not exist.
The second is a string escaping problem. I expect the quotes are escaped in the database - using mysql_real_escape_string on the query will not alter whether the returned results are escaped or not.
Also, if your data in the database is escaped by slashes, you should read up on magic quotes and what to do about them: PHP docs on magic quotes. You should not have to do any string escaping when pulling data out of the DB.

Why is my query finding field entries that are numbers, but not number/letter combinations

Newbie here. The following function works fine when $color refers to an entry in the "style" field that is numberic e.g. "5000". But if the entry is "5000B" or letters entirely, it can't find it. Is this an indexing problem?
function get_shirt_colors_by_style($color)
{
db_connect();
$query = "SELECT style,sanmar_mainframe_color,unique_key,color_square_image
FROM sanmar_products WHERE style=$color
GROUP BY style ORDER BY style";
$result = mysql_query($query);
$data = mysql_fetch_array($result);
return $data;
}
It is failing to find alphanumeric comnbinations because the string is not quoted:
$query = "SELECT style,sanmar_mainframe_color,unique_key,color_square_image FROM sanmar_products WHERE style='$color' GROUP BY style ORDER BY style";
//-----------------------------------------------------------------------------------------------------------^^^^^^^^^
Numeric values need not be quoted in a MySQL query, but string values must always be surrounded in single quotes like '5000B'.
We assume the value of $color has already been escaped against SQL injection:
// Hopefully this happened already.
// If not, do it before running mysql_query()
$color = mysql_real_escape_string($color);
Is this an indexing problem?
No its a really bad coding problem.
Non-numeric values should be enclosed in quotes - actually literal values should always be enclosed in quotes when the underlying column type is numeric - otherwise you're likely to run into performance issues. You've also got a problem with managing errors in your code - if a query containing "WHERE style=5000B" is sent to the database it will always return an error - that you have no visibility of this error means that you've got a lot of important functionality missing from your site. Indeed, since content representations whould always be validated / changed at the point where the value leaves PHP, that also implies that your code is probably wide open to SQL injection attacks.
...and then there's the database design issues evident here: 'style' implies a non-unique identifier yet you are returning a single row from your query without any explicit ordering other than on the field you've selected on (i.e. even if it were unique, its very innefficient).
try using single quotes here:
WHERE style='$color'

PHP Query to Insert Variables into MySQL not working

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.

Categories