Sorry if the title is strangely worded. This is my first time asking anything here, and I'm pretty new to PHP so I'm having a tough time figuring this out.
Basically, I am trying to write a PHP script that will allow me to change the rules for a certain game instance from our website, so I don't have to go into the database and run a SQL query every time.
This is what I have so far:
public function update_rules()
{
$rules = $this->input->post('rules');
$domains = $this->input->post('domains_multiselect');
$qarr = array();
$sql = "
UPDATE domains
SET rules = ?
WHERE domain_id = ?
";
$qarr[] = $rules;
$qarr[] = $domain_id;
$query = $this->db->query($sql,$qarr);
redirect ("admin/insert_rules");
}
I am unsure how to to a substr_replace() to change the "?" placeholders in the query to be able to input both the manually typed rules and the domain_id, which I think will be generated when the domain name is selected.
I could be completely off-base here, but if anyone could point me in some kind of direction, that'd be great. thank you.
you can use either named placeholder or position dependent placeholders...
//Position dependent:
$stmt = $this->db->prepare("UPDATE domains SET rules = ? WHERE domain_id = ?");
$stmt->bindParam(1, $rules);
$stmt->bindParam(2, $domain_id);
$stmt->execute();
//Named Placeholder:
$stmt = $this->db->prepare("UPDATE domains SET rules = :rules WHERE domain_id = :domain");
$stmt->bindParam(':rules', $rules);
$stmt->bindParam(':domain', $domain_id);
$stmt->execute();
Related
I have a php search form with two fields. One for $code another for '$name'.The user uses one or the other, not both.
The submit sends via $_POST.
In the receiving php file I have:
SELECT * FROM list WHERE code = '$code' OR name = '$name' ORDER BY code"
Everything works fine, however I would like that $code is an exact search while $name is wild.
When I try:
SELECT * FROM list WHERE code = '$code' OR name = '%$name%' ORDER BY code
Only $code works while $name gives nothing. I have tried multiple ways. Changing = to LIKE, putting in parentheses etc. But only one way or the other works.
Is there a way I can do this? Or do I have to take another approach?
Thanks
If you only want to accept one or the other, then only add the one you want to test.
Also, when making wild card searches in MySQL, you use LIKE instead of =. We also don't want to add that condition if the value is empty since it would become LIKE '%%', which would match everything.
You should also use parameterized prepared statements instead of injection data directly into your queries.
I've used PDO in my example since it's the easiest database API to use and you didn't mention which you're using. The same can be done with mysqli with some tweaks.
I'm using $pdo as if it contains the PDO instance (database connection) in the below code:
// This will contain the where condition to use
$condition = '';
// This is where we add the values we're matching against
// (this is specifically so we can use prepared statements)
$params = [];
if (!empty($_POST['code'])) {
// We have a value, let's match with code then
$condition = "code = ?";
$params[] = $_POST['code'];
} else if (!empty($_POST['name'])){
// We have a value, let's match with name then
$condition = "name LIKE ?";
// We need to add the wild cards to the value
$params[] = '%' . $_POST['name'] . '%';
}
// Variable to store the results in, if we get any
$results = [];
if ($condition != '') {
// We have a condition, let's prepare the query
$stmt = $pdo->prepare("SELECT * FROM list WHERE " . $condition);
// Let's execute the prepared statement and send in the value:
$stmt->execute($params);
// Get the results as associative arrays
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
The variable $results will now contain the values based on the conditions, or an empty array if no values were passed.
Notice
I haven't tested this exact code IRL, but the logic should be sound.
I'm trying to implement a pretty basic search engine for my database where the user may include different kinds of information. The search itself consists of a couple of a union selects where the results are always merged into 3 columns.
The returning data however is being fetched from different tables.
Each query uses $term for matchmaking, and I've bound it to ":term" as a prepared parameter.
Now, the manual says:
You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name twice in a prepared statement.
I figured that instead of replacing each :term parameter with :termX (x for term = n++) there must be a be a better solution?
Or do I just have to bind X number of :termX?
Edit Posting my solution to this:
$query = "SELECT ... FROM table WHERE name LIKE :term OR number LIKE :term";
$term = "hello world";
$termX = 0;
$query = preg_replace_callback("/\:term/", function ($matches) use (&$termX) { $termX++; return $matches[0] . ($termX - 1); }, $query);
$pdo->prepare($query);
for ($i = 0; $i < $termX; $i++)
$pdo->bindValue(":term$i", "%$term%", PDO::PARAM_STR);
Alright, here is a sample. I don't have time for sqlfiddle but I will add one later if it is necessary.
(
SELECT
t1.`name` AS resultText
FROM table1 AS t1
WHERE
t1.parent = :userID
AND
(
t1.`name` LIKE :term
OR
t1.`number` LIKE :term
AND
t1.`status` = :flagStatus
)
)
UNION
(
SELECT
t2.`name` AS resultText
FROM table2 AS t2
WHERE
t2.parent = :userParentID
AND
(
t2.`name` LIKE :term
OR
t2.`ticket` LIKE :term
AND
t1.`state` = :flagTicket
)
)
I have ran over the same problem a couple of times now and I think i have found a pretty simple and good solution. In case i want to use parameters multiple times, I just store them to a MySQL User-Defined Variable.
This makes the code much more readable and you don't need any additional functions in PHP:
$sql = "SET #term = :term";
try
{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(":term", "%$term%", PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
// error handling
}
$sql = "SELECT ... FROM table WHERE name LIKE #term OR number LIKE #term";
try
{
$stmt = $dbh->prepare($sql);
$stmt->execute();
$stmt->fetchAll();
}
catch(PDOException $e)
{
//error handling
}
The only downside might be that you need to do an additional MySQL query - but imho it's totally worth it.
Since User-Defined Variables are session-bound in MySQL there is also no need to worry about the variable #term causing side-effects in multi-user environments.
I created two functions to solve the problem by renaming double used terms. One for renaming the SQL and one for renaming the bindings.
/**
* Changes double bindings to seperate ones appended with numbers in bindings array
* example: :term will become :term_1, :term_2, .. when used multiple times.
*
* #param string $pstrSql
* #param array $paBindings
* #return array
*/
private function prepareParamtersForMultipleBindings($pstrSql, array $paBindings = array())
{
foreach($paBindings as $lstrBinding => $lmValue)
{
// $lnTermCount= substr_count($pstrSql, ':'.$lstrBinding);
preg_match_all("/:".$lstrBinding."\b/", $pstrSql, $laMatches);
$lnTermCount= (isset($laMatches[0])) ? count($laMatches[0]) : 0;
if($lnTermCount > 1)
{
for($lnIndex = 1; $lnIndex <= $lnTermCount; $lnIndex++)
{
$paBindings[$lstrBinding.'_'.$lnIndex] = $lmValue;
}
unset($paBindings[$lstrBinding]);
}
}
return $paBindings;
}
/**
* Changes double bindings to seperate ones appended with numbers in SQL string
* example: :term will become :term_1, :term_2, .. when used multiple times.
*
* #param string $pstrSql
* #param array $paBindings
* #return string
*/
private function prepareSqlForMultipleBindings($pstrSql, array $paBindings = array())
{
foreach($paBindings as $lstrBinding => $lmValue)
{
// $lnTermCount= substr_count($pstrSql, ':'.$lstrBinding);
preg_match_all("/:".$lstrBinding."\b/", $pstrSql, $laMatches);
$lnTermCount= (isset($laMatches[0])) ? count($laMatches[0]) : 0;
if($lnTermCount > 1)
{
$lnCount= 0;
$pstrSql= preg_replace_callback('(:'.$lstrBinding.'\b)', function($paMatches) use (&$lnCount) {
$lnCount++;
return sprintf("%s_%d", $paMatches[0], $lnCount);
} , $pstrSql, $lnLimit = -1, $lnCount);
}
}
return $pstrSql;
}
Example of usage:
$lstrSqlQuery= $this->prepareSqlForMultipleBindings($pstrSqlQuery, $paParameters);
$laParameters= $this->prepareParamtersForMultipleBindings($pstrSqlQuery, $paParameters);
$this->prepare($lstrSqlQuery)->execute($laParameters);
Explanation about the variable naming:
p: parameter, l: local in function
str: string, n: numeric, a: array, m: mixed
I don't know if it's changed since the question was posted, but checking the manual now, it says:
You cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.
http://php.net/manual/en/pdo.prepare.php -- (Emphasis mine.)
So, technically, allowing emulated prepares by using $PDO_obj->setAttribute( PDO::ATTR_EMULATE_PREPARES, true ); will work too; though it may not be a good idea (as discussed in this answer, turning off emulated prepared statements is one way to protect from certain injection attacks; though some have written to the contrary that it makes no difference to security whether prepares are emulated or not. (I don't know, but I don't think that the latter had the former-mentioned attack in mind.)
I'm adding this answer for the sake of completeness; as I turned emulate_prepares off on the site I'm working on, and it caused search to break, as it was using a similar query (SELECT ... FROM tbl WHERE (Field1 LIKE :term OR Field2 LIKE :term) ...), and it was working fine, until I explicitly set PDO::ATTR_EMULATE_PREPARES to false, then it started failing.
(PHP 5.4.38, MySQL 5.1.73 FWIW)
This question is what tipped me off that you can't use a named parameter twice in the same query (which seems counterintuitive to me, but oh well). (Somehow I missed that in the manual even though I looked at that page many times.)
It's possible only if you enable prepared statement emulation. You can do it by setting PDO::ATTR_EMULATE_PREPARES to true.
A working solution:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);
$query = "SELECT * FROM table WHERE name LIKE :term OR number LIKE :term";
$term = "hello world";
$stmt = $pdo->prepare($query);
$stmt->execute(array('term' => "%$term%"));
$data = $stmt->fetchAll();
User defined variables its one way to go and use a the same variable multiple times on binding values to the queries and yeah that works well.
//Setting this doesn't work at all, I tested it myself
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);
I didn't wanted to use user defined variables at all like one of the solutions posted here. I didn't wanted also to do param renaming like the other solution posted here. So here it's my solution that works without using user defined variables and without renaming anything in your query with less code and it doesn't care about how many times the param is used in the query. I use this on all my project and it's works well.
//Example values
var $query = "select * from test_table where param_name_1 = :parameter and param_name_2 = :parameter";
var param_name = ":parameter";
var param_value = "value";
//Wrap these lines of codes in a function as needed sending 3 params $query, $param_name and $param_value.
//You can also use an array as I do!
//Lets check if the param is defined in the query
if (strpos($query, $param_name) !== false)
{
//Get the number of times the param appears in the query
$ocurrences = substr_count($query, $param_name);
//Loop the number of times the param is defined and bind the param value as many times needed
for ($i = 0; $i < $ocurrences; $i++)
{
//Let's bind the value to the param
$statement->bindValue($param_name, $param_value);
}
}
And here is a simple working solution!
Hope this helps someone in the near future.
I've been having problems trying to update a value based off a code that is received on the page.
For example:
http://example.com/register.php?code=fa82f82712d1 (not the actual code, it's always a 32-char code actually).
I start a transaction, and do an update in the following way:
$stmt = $stmt->prepare("UPDATE USER SET GOT_CODE = 1 WHERE CODE = :code");
Then do a $stmt->execute(array(':code' => $code)); from the code gotten before.
But it never updates anything, I'm running a rowCount() (gives me '0') and closing the transaction but can't seem to get it updated.
The column type is CHAR(32) which should match with the length of the code received.
Is it possible that it's causing confusions because of the data type?
Maybe bind the parameter before like:
$stmt2 = $stmt->prepare("UPDATE USER SET GOT_CODE = 1 WHERE CODE = :code");
$stmt2->bindParam(":code", $code, PDO::PARAM_STR);
if ($stmt2->execute()){
$stmt->commit();
} else {
$stmt->rollBack();
}
EDIT: after comment of other people. The basic is to not use
$stmt = $stmt->prepare("UPDATE USER SET GOT_CODE = 1 WHERE CODE = :code");
but to give different var name like
$stmt2 = $stmt->prepare("UPDATE USER SET GOT_CODE = 1 WHERE CODE = :code");
because otherwise the system will overwrite $stmt and not work anymore
First - my code works and no problem with that, but it is not completely safe.
I don't know how to bind my query. I know a bout bindParam / bindValue but i don't have any idea how to use those in my case...
My query consists of part and the parts depends of AJAX post:
if(!empty($_POST['manufacturers']))
$manufacturers = $_POST['manufacturers'];
else
$manufacturers = null;
if(!empty($_POST['processors']))
$processors = $_POST['processors'];
else
$processors = null;
if($manufacturers != null)
$manufacturers = ' AND manufacturer.slug IN('.$manufacturers.')';
if($processors != null)
$processors = ' AND processors.slug IN('.$processors.')';
And complete query will be:
$query = "bla bla my query";
$query = $query.$processors.$manufacturers;
Example query is:
SELECT manufacturer.name AS ManufName,
model.model_name AS ModelName,
processors.name ProcName,
laptops.resolution,
inches.name,
graphic_card.name GraphName,
laptops.memory_type,
laptops.memory_size,
laptops.ram,
laptops.price,
laptops.image_path
FROM manufacturer, model, processors, inches, graphic_card, laptops
WHERE manufacturer.id = Laptops.manufacturer_id
AND model.id = Laptops.model_id
AND inches.id = Laptops.inches_id
AND processors.id = Laptops.processor_id
AND graphic_card.id = Laptops.graphic_card_id
AND manufacturer.slug
IN('Dell','Lenovo')
AND processors.slug
IN('Intel_core_i5','Intel_core_i7')
And from post i get in this case: 'Dell','Lenovo' and secondly i get:
'Intel_core_i5','Intel_core_i7'
Query changes by every checkbox change from user interface...
So if user checks only checkbo from manufacturers then the query will not be the same if query checks checkboxes from both - manufacturers and processors...
I need to prevent things like this:
$.post('ajaxCallback.php', {manufacturers: 'sleep(15)'});
How to bind this query or how to make this correctly safe?
I appreciate any help and advice!
Thanks a lot!
I have a PDO/MySQL database connection. My database holds content for various landing pages. To view these landing pages I enter *localhost/landing_page_wireframe.php* and append with ?lps=X (where X represents the Thread_Segment) to display the particular page in the browser. I am now getting to second iterations of these pages and need to add a secondary classifier to follow "Thread_Segment" to distinguish which version I am trying to pull up. Here is a snippet of my current working query.
<?php
$result = "SELECT * FROM landing_page WHERE Thread_Segment = :lps";
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->execute();
$thread = "";
$threadSegment = "";
$version = "";
$categoryAssociation = "";
while($row = $stmt->fetch()) {
$thread = $row["Thread"];
$threadSegment = $row["Thread_Segment"];
$version = $row["Version"];
$categoryAssociation = $row["Category_Association"];
}
?>
So I need to now change this to add in the secondary classifier to distinguish between versions. I would imagine my query would change to something like this:
$result = "SELECT * FROM landing_page WHERE Thread_Segment = :lps AND Version = :vrsn";
if this is correct so far, then where I am beginning to get lost is in the following PHP code.
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->execute();
I imagine I need to include some secondary iteration of this in my php to talk to the secondary classifier, but not totally sure how to go about this, and then I would imagine my url appendage would go from ?lps=X to something like this ?lps=X&vrsn=Y (Y representing the version).
I should state that I am somewhat new to PHP/MySql so the answer here may be simple, or may not even be possible. Perhaps I am not even going about this the correct way. Thought you all might be able to shed some insight, or direction for me to curve my research on the matter to. Thanks and apologies for any improper terminology, as I am definitely new to these technologies.
The URL change is as you describe. Just add another bindParam call to use that parameter:
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->bindParam(':vrsn', $_GET['vrsn']);
$stmt->execute();
Adding another bindParam() should work here.
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->bindParam(':vrsn', $_GET['vrsn']);
$stmt->execute();
You can access it via ?lps=X&vrsn=Y but just as a warning, the query will fail if those $_GET params are not requested. I recommend defaulting it to something prior to sending it through the query:
$stmt = $connection->prepare($result);
$lps = isset($_GET['lps']) ? $_GET['lps'] : 'default lps value';
$vrsn = isset($_GET['vrsn ']) ? $_GET['vrsn '] : 'default vrsn value';
$stmt->bindParam(':lps', $lps);
$stmt->bindParam(':vrsn', $vrsn);
$stmt->execute();