I want to get the value from the Epic[2] column.
The mysql table looks like that:
ID | Epic[0] | Epic[1] | Epic[2] | Epic[3]
-----------------------------------------------
440 xy xy xy xy
I have three variables where the informations are stored.
$qualitybudget = "Epic"
$budgetType = "2"
$itemlevel = "440"
I tried the following:
$sql = "SELECT '$qualitybudget'['$budgetType'] FROM `randproppoints` WHERE id = '$itemlevel'";
Output looks like that:
SELECT 'Epic'['2'] FROM `randproppoints` WHERE id = '440'
As you see 'Epic'['2'] has the wrong syntaxing. The output for the working query should be like: Epic[2]
What is the right syntax handling in a mysql query like that?
Use
$sql = "SELECT `${qualitybudget}[$budgetType]` FROM `randproppoints` WHERE id = '$itemlevel'";
instead. This way, the column name is exactly formatted as you wish and encapsulated.
Note that the syntax ${xyz} has to be used to make it clear that only xyz is the name of the variable and that this is all to be printed here. Otherwise, PHP assumes it is an array and evaluates the following squared brackets for the same string insertion. Another example where this syntax has to be used is if for instance you had a variable $a = "thing"; and wanted
$b = "there are three $as";
to get "there are three things". It would not work as PHP would assume you address a variable $as, but the fix would seem like this:
$b = "there are three ${a}s";
Related
I have an array in php containing strings, which I want to use in a query with Red Bean MySQL in the following manner:
$someString = '\'abc\',\'def\',\'ghi\'';
R::getAll("select * from table where name not in (:list)", array(':list'=> $someString));
The problem is that the list is not being evaluated correctly no matter how I set the values in the array string, and the names abc, def, ghi are returned in the result. I've tried the following:
$someString = '\'abc\',\'def\',\'ghi\''
$someString = 'abc\',\'def\',\'ghi'
$someString = 'abc,def,ghi'
running the query in the SQL server manually works and I don't get those values returned, but running it within the php code with redbean is not working, and it seems that the list is not being interpreted correctly syntax-wise.
Can anyone shed some light on the matter?
Thanks to RyanVincent's comment I managed to solve the issue using positional parameters in the query, or more specifically, the R::genSlots function.
replaced the following:
$someString = '\'abc\',\'def\',\'ghi\'';
R::getAll("select * from table where name not in (:list)", array(':list'=> $someString));
with:
$someArray = array('abc', 'def', 'ghi');
R::getAll("select * from table where name not in (". R::genSlots($someArray) .")", $someArray);
This creates a $someArray length positions for parameters in the query, which are then filled with the values in the second parameter passed to the getAll function.
Notice that in this case I used a set content array (3 variables) but it will work dynamically with any length array you will use.
Furthermore, this can also work for multiple positions in the query, for example:
$surnameArray = array('smith');
$arr1 = array('john', 'pete');
$arr2 = array('lucy', 'debra');
$mergedVarsArray = array_merge($surnameArray,$arr1);
$mergedVarsArray = array_merge($mergedVarsArray,$arr2);
R::getAll("select * from table where surname != ? and name in (." R::genSlots($arr1).") and name not in (". R::genSlots($arr2) .")", $mergedVarsArray);
This code will effectively be translated to:
select * from table where surname != 'smith' and name in ('john','pete') and name not in ('lucy', 'debra')
Each '?' placed in the query (or generated dynamically by genSlots() ) will be replaced by the correlating positioned item in the array passed as parameter to the query.
Hope this clarifies the usage to some people as I had no idea how to do this prior to the help I got here.
I have multiple ids separated by + in one field of a row in a table
Like : (123+21654+412+12387)
I need Only EXACT MATCHES, (e.g.: only "123" and not "123 & 12387")
My code is like this:
$var = $value['id'];
$result = mysqli_query($this->dbh, "SELECT id FROM table
WHERE id REGEXP '[[:<:]]$var[[:>:]]' ");
I have a problem with using a variable in REGEXP.
in case of :
$result = mysqli_query($this->dbh, "Select id FROM table
WHERE id REGEXP '^$id|[\+]$id' ");
it works, but it does not return only exact matches
PHP tip: "Interpolation" works these ways:
"...$var[...]..." treats that as an array lookup for $var[...].
Without [, $var is assumed to be a scalar.
"...{$var}[...]..." is what you need
This last example has braces {} to tell PHP to evaluate what is inside without being concerned about what follows. More common usage:
$var = 'abc';
// I want to generate "abc123"
$bad = "$var123"; // looks for variable 'var123'
$good = "{$var}123; // correctly yields "abc123"
Your second attempt can be fixed thus:
REGEXP '(^|\+)$id(\+|$)'
meaning:
At the beginning or after a +,
Find $id (after interpolating),
And stop with a + or the end of the string.
I'll go with :
$sql = "SELECT id FROM table WHERE id='123' OR id LIKE '123+%' OR id LIKE '%+123' OR id LIKE '%+123+%'";
The first condition will apply if you only have the value, the second if the field starts with the value, the third if the field ends with the value and the fourth if the value is in the middle of the field.
So, I will have a page where a user lands with a /?ref=123 type ending on the URL.
Then, what I want to achieve, is to use that ref 123 in a MySQL query, like this:
SELECT foo FROM table WHERE table.ref = 123
The issue I have hit is that if i use $_GET to get the variable, it breaks my SQL query (obviously!)
SELECT foo FROM table WHERE table.ref = $_GET['ref']; falls over because $_GET is not a MySQL function.
Trouble is, I want to dynamically create page content based on the ref value but I can't figure how.
Any help gratefully accepted.
Timezone GMT+13 so replies will potentially be slow :)
**********EDIT**********
As I may not have given enough info in the OP, here's the code I'm struggling with:
<?php
global $wpdb;
header('Content-Type: text/html; charset=utf-8');
include "../../../wp-config.php";
$get_donation_amount = "select SUM(amount) AS total_donations from SaveContactForm7_1 where ref = 123 ";
$get_donation_amount_result = $wpdb->get_results($get_donation_amount);
$total_donation = isset($get_donation_amount_result[0]->total_donations) && $get_donation_amount_result[0]->total_donations !="" ? $get_donation_amount_result[0]->total_donations :"0" ;
?>
What I need to do is add a call to the URL for the value of ref and add it where shown with the SQL querycode. Then a particular donor who knows his 'ref' value will see results relevant to him alone.
Using PHP7 this could look something like this
$ref = $_GET['ref'] ?? null;
$sth = $dbh->prepare('SELECT foo FROM table WHERE table.ref = ?');
$sth->execute([$ref]);
$orders = $sth->fetchAll();
You should probably have some way of handling errors (ref is not set)
Note that the last variable (result of the query) is called orders. I didn't know what the result set you expected would be, but it was just to illustrate that it makes sense to call it something spesific (what it actually represents), instead of "rows", "result" or similar.
Note that PHP 7 introduces the so called null coalescing operator which simplifies isset statements
PHP7
$ref = $_GET['ref'] ?? null;
PHP < 7
$ref = isset($_GET['ref']) ? $_GET['ref']: null;
I want to prepare a statement for use inside a loop. When I try to execute the statement I see an error in the logs saying "Invalid parameter number: no parameters were bound'".
What's wrong with my code?
$itemSelectSql = "SELECT * FROM `tblItems` WHERE `itemID` IN (?)";
$itemSelectStmt = new Zend_Db_Statement_Mysqli($this->db_ro, $itemSelectSql);
while () {
...
$itemIds = array();
// populate $itemIds array
...
$itemSelectStmt->execute(array($itemIds));
}
EDIT:
I think I may have a bug in my set up which explains why whatever I try fails. I'm seeing this:
PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback,
class 'PDOStatement' does not have a method 'bind_param' in
/var/www/lib/Zend/Db/Statement/Mysqli.php on line 204
EDIT:
I was using the wrong adapter. Should have been Zend_Db_Statement_Pdo :-)
Thanks for the replies.
? can't be replaced by an array, it has to be replaced by a scalar (thanks to comment for pointing out that this does not always mean string... brain-fart on my end). Let me know if this works better:
$itemSelectSql = "SELECT * FROM `tblItems` WHERE `itemID` IN ";
while () {
...
$itemIds = array();
// populate $itemIds array
...
// we need to have the same number of "?,"'s as there are items in the array.
// and then remove final comma.
$qs = rtrim(str_repeat("?,", count($itemIds)),',');
// create a statement based on the result
$itemSelectStmt =
new Zend_Db_Statement_Mysqli($this->db_ro, "$itemSelectSql ($qs)");
// bind to each of those commas.
$itemSelectStmt->execute($itemIds);
}
Have you tried doing this:
while () {
...
$itemIds = array();
// populate $itemIds array
$itemIds = implode(',' $itemIds);
$itemSelectStmt->execute(array($itemIds));
}
I'm not an expert of Zend_framework, but when you use statements, to the execute method you must
If you use positional parameters, or
those that are marked with a question
mark symbol ('?'), pass the bind
values in a plain array.
So i think you need to pass an array with one value and that value replace the "?" in the statement. In this case you need a comma separated string (if you ids are int) to replace (?) in the statement.
What you do if you do not implode the values is passing an array containing an array.
You might use FIND_IN_SET(str,strlist) instead of IN ():
mysql> select id, name from customer where find_in_set(id, '10,15,20');
+----+---------+
| id | name |
+----+---------+
| 10 | ten |
| 15 | fifteen |
| 20 | twelve |
+----+---------+
This way, you don't have to bind array with multiple values to IN(), you can pass list of IDs as a single comma-separated string. You can safely use PHP function implode() to generate string from array of IDs.
Though, I'm not sure if it has any impact on performance.
I took a look at output of explain, and it looks like find_in_set() is not able to use indexes, so generating queries with variable number of parameters should perform better.
There's a mysql database that stores ids and names, when users are creating names with a form they can create existent names since unique ids are the ids such as:
d49f2c32f9107c87c7bb7b44f1c8f297 name
2fa9c810fbe082900975f827e8ed9408 name
what i want to do is saving the second "name" -> "name(1)" when inserting into database.
So far what I've got is this as the idea
lets say the name entered is 'name'
$input = 'name';
select the name we want to check from mysql database
mysql_query(SELECT * FROM `table` WHERE `name` = '$input');
if the result exists, then insert as $input.'(1)'
my question is what if name exists, and name(1) also exists, then how can i add the name(2) there...
You could return the number of people with that name in the database, then add 1 to that number.
SELECT COUNT(id) FROM table WHERE name LIKE '$input(%)');
$i = 1;
$sourceName = $name;
while( sql "SELECT COUNT(*) FROM table WHERE name = '$name'" ) {
$name = $sourceName.' ('.$i.')';
$i++;
}
At this point you have the final $name (with $i counting the iteration)
Something like this should do the trick:
SELECT * FROM table WHERE name = '$input' OR name LIKE '$input(%)'
Note that for this to work, you'd need to escape any percent signs in $input in the LIKE clause, otherwise they'll be treated as wildcards.
Use a regex that checks for integers between two parentheses at the end of the string. If there exists an integer, add 1 to it.
You could also attempt to do it the other way around, make name field unique and try to input it in a while loop, if it fails add ($i) and do $i++ every iteration.
//edit:
The problem with using solutions that do a like comparison is that you will get false positives, for instance $hi% will also count hippie. Which gives you unnecessary (1) additions!