Using variable names as column names - php

I am creating an website where i am using user specified values as the column name of my table and it works fine but, when it comes to update it am unable to do it in the same process
here are my codes to create a column name from user specified value
mysqli_query($sql,"ALTER TABLE `cmpcheck` ADD `$emailID` VARCHAR( 100 ) NOT NULL ");
Here are my codes to update the above column
mysqli_query($sql,"UPDATE cmpcheck SET `$emailID` = `".$q."` LIMIT 1 ");
Any Help?

You are using the wrong quotes for your value:
mysqli_query($sql,"UPDATE cmpcheck SET `$emailID` = '".$q."' LIMIT 1 ");
^ ^
With a backtick (`) you are referencing to a column-name.
Besides that: make sure to properly escape both $emailID and $q

Backticks go around table and column names. You should use single quotes around string values.
mysqli_query($sql,"UPDATE cmpcheck SET `$emailID` = '$q' LIMIT 1 ");
Also, there's no reason to switch from variable substitution (as you do for $emailID) to concatenation with ..
It would be even better to use a prepared statement to substitute $q, instead of variable substitution into the query. But you can't do that for the column name.

You could try :
mysqli_query($sql,"UPDATE cmpcheck SET `".$emailID."` = '".$q."' LIMIT 1 ");
Also look at preparing your statements.

Related

How to force int as string in prepared statement

I'm working on syncing two PostgreSQL databases using a PHP script. I am not able to query the entire table so I have to use an id column to grab records in batches.
The id column is a string column, not numeric. However, there are numerical ids in the column. This is where I'm having an issue.
When I prepare the SQL statement in PHP, when I happen to get an id that is numeric, when I bind it to the statement, it doesn't put quotes around the value because it thinks its an int, not a string.
How do I force it to be a string and always put single quotes around the id??
If I put the quotes around the ? in the query it treats it as text and the parameter doesn't get bound to the statement.
As you can see in the code I also tried casting the $start variable as a string. $start contains the starting id.
Here is the code:
$sql = "select id from properties where id > ? order by id limit ?";
$params = [(string) $start, 50000];
$rows = $this->wolfnet->select($sql, $params);

Removing/disabling backticks on variable in Active Record query in CodeIgniter

I'm trying to make a "between" query on my database using the Query Class of CodeIgniter, however, when adding a variable to the where clause, it adds backticks to the variable.
$this->db->select(TABLE_DISCOUNTSCARRIER.'.discount')->select(TABLE_DISCOUNTSCARRIER.'.idCarrier')
$this->db->from(TABLE_DISCOUNTSCARRIER);
$this->db->join(TABLE_DISCOUNTS, TABLE_DISCOUNTSCARRIER.'.idDiscount='.TABLE_DISCOUNTS.'.idDiscount');
$this->db->where(TABLE_DISCOUNTSCARRIER.'.idCarrier', $carrier);
$this->db->where($data['from'].' BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to');
$this->db->or_where($data['to'].' BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to');
Which is being parsed into this (the last two lines)
SELECT
discountbycarrier.discount,
discountbycarrier.idCarrier
FROM (discountbycarrier)
JOIN discounts
ON discountbycarrier.idDiscount=discounts.idDiscount
WHERE `discountbycarrier`.`idCarrier` = '6'
AND `5` BETWEEN discounts.from AND discounts.to
OR `10` BETWEEN discounts.from AND discounts.to
Already tried setting the $this->db->_protect_identifiers=false; but it removes the backticks on the rest of the statements but not the variables. Already tried using the intval() of the variable but neither this works.
As you can see the variable $carrier is correctly being parsed as integer.
Any ideas? Thanks in advance.
Change this
discounts.from
to
discounts.`from`
Or better (best practice) don't use reserved keywords for table columns, the word FROM is part of the query language, in other words.
Backticks are used to escape reserved keywords and spaces.
UPDATE
Something like this ( although I didn't look the documentation )
$this->db->where('? BETWEEN '.TABLE_DISCOUNTS.'.from AND '.TABLE_DISCOUNTS.'.to', $data['from']);
add this before the query
$this->db->_protect_identifiers=false;

Double quotes in PHP

I don't know PHP at all, so I am struggling through this. I need to add an or section to a MySQL query, but the values I'm searching have double quotes. I need to figure out how to add them in PHP so they are passed in to MySQL. The current query looks like:
$query = 'SELECT * FROM ' .$tableName.' WHERE allowed_countries LIKE "%'.$regionId.'%" and skurules REGEXP "i:'.$secondlastdigit.';" and status = 1 ORDER BY id DESC LIMIT 1';
But I need to add an or statement to search for string values that looks like:
$query = 'SELECT * FROM ' .$tableName.' WHERE allowed_countries LIKE "%'.$regionId.'%" and skurules REGEXP "i:'.$secondlastdigit.';" or skurules REGEXP "s:1:'.$secondlastdigit.';" and status = 1 ORDER BY id DESC LIMIT 1';
with double quotes surrounding the second instance of '.$secondlastdigit.'; when passed into MySQL.
My JSON string I'm searching looks like this:
a:12:{i:1;s:2:"15";i:2;s:2:"10";i:3;s:2:"30";i:4;s:2:"50";i:5;s:3:"120";i:6;s:3:"240";i:7;s:3:"480";i:8;s:3:"960";i:9;s:4:"3786";s:1:"A";s:3:"100";s:1:"C";s:2:"60";s:1:"B";s:5:"18930";}
First of all: DON'T.
If you still want to, then...REALLY DO NOT.
Making SQL queries on serialized arrays is just hell. You should try to avoid it at all costs.
Either:
Convert the serialized column into a standard SQL table
or select the column into a PHP variable, unserialize it and search through it.
Example:
$properPhpArray = unserialize($sqlResult['column_name']);
Agreed, searching serialized string is not the best solution and what the developer did despite having a bottle_size table available. I needed a quick fix and no time/skill to rewrite a tax calculation magento extension so I used replace in the query to solve my problem for now.
Since "s:1:X" will always be just one alpha character after the 1 and will not match anything else. I change the query to:
$query = 'SELECT * FROM ' .$tableName.' WHERE allowed_countries LIKE "%'.$regionId.'%" and skurules REGEXP "i:'.$secondlastdigit.';" or replace(skurules,char(34),0) REGEXP "s:1:0'.$secondlastdigit.'0;" and status = 1 ORDER BY id DESC LIMIT 1';
Very hackish fix but gets me out of a bind for now..
Mark

'IN' clause with multiple 'AND' Condition

I have a SQL query which is returning me an incorrect result.
" SELECT * FROM directory WHERE '".$_REQUEST['occupation']."' IN (occupation,pro_cat1,pro_cat2,pro_cat3,pro_cat4,pro_cat5) AND state = '".$_REQUEST['state']."' AND city = '".$_REQUEST['city']."' AND status = 1 ORDER BY rand() "
Here I want to check if occupation is one of the 6 values provided in the IN clause (while also adding some more clauses in the WHERE concatenated with an AND).
It does return me a result, however it is incorrect. Where have I gone wrong?
If the values you are looking for are strings, you need to quote them:
... IN ('occupation','pro_cat1','pro_cat2','pro_cat3','pro_cat4','pro_cat5') ...
^ here ^ etc.
You should also never inject variables directly into a query. Instead you should use a prepared statement with placeholders for your variables.
Also, column names should not be quoted (unless they are reserved words, contain spaces, etc.) but if you need to quote them, you should use back-ticks:
... directory where `".$_REQUEST['occupation']."` IN ...
^ here ^
Also note that table- and column names cannot be prepared so they always have to be white-listed before you inject them into your query.

MySQL - adding 1 to column with name in backticks

I'm having trouble adding 1 to a column value in MySQL. I've used backticks on the column name and value isn't incrementing. Here is my query:
$update = $connectdb->prepare("UPDATE `strings` SET posted=posted, `response-comment`=`response-comment` + 1 WHERE `id`=?");
$update->execute(array($id));
Why isn't my query working? The value $id is correct, the column response-comment should increase by 1.
Try using this for your SQL statement (presuming strings is the name of your table:
UPDATE `strings` SET `response-comment`=`response-comment` + 1 WHERE `id`=?
Be careful with tick marks
If improperly coded you can end up with quotes which is going to transform you integer value into a string and thus changing the behavior of your request.
Have you tried with out , justresponse-comment = response-comment + 1`

Categories