I have a DB table named 'affiliate_wp_coupons' where has 3 cols and they are;
coupon_id
affiliate_id
coupon_code
I have coupon_code which is coming from a variable, not static.
Now I wanted to query the associated affilaite_id value based on the coupon_code.
I am trying this code:
$results = $wpdb->get_results( "SELECT * FROM affiliate_wp_coupons WHERE `coupon_code`= 'BS0PDDTTGU'");
This code returns an Object with the matched col.
In the above code coupon_code value is static, how can I put a variable here?
$coupon_code = 'BS0PDDTTGU';
$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM affiliate_wp_coupons WHERE `coupon_code`= %s", $coupon_code));
There're multiple ways to concatenate/inserting variable into a string in PHP, ex:
$coupon_code = 'Windy';
$str = "Hello {$coupon_code}!"; // Hello Windy!
$str2 = "Hello $coupon_code!"; // Hello Windy!
$str3 = 'Hello '.$coupon_code.'!'; // Hello Windy!
personally I prefer $str2.
Then in your case you can replace your code something like:
$results = $wpdb->get_results( "SELECT * FROM affiliate_wp_coupons WHERE `coupon_code`= '{$coupon_code}'");
Note: don't forget to define $coupon_code before run query.
PHP reference: https://www.php.net/manual/en/language.operators.string.php
Related discussion: PHP - concatenate or directly insert variables in string
Related
I have a situation where I need to fetch details of an employee from the database using his ID and display them in the browser.
$sql = "SELECT * FROM employeesalarypayment WHERE empid = ".$val['empid'].";";
$query = $this->db->query($sql);
These are the statements that I have written to get the result array. My problem is how do I take a single field/column from this array? Also have I done it correctly?
Thanks in advance.
If your query return single data from database then you need to use
$row = $query->row_array()
Try this
$sql = "SELECT * FROM employeesalarypayment WHERE empid = ".$val['empid'].";";
$result = $this->db->query($sql)->result_array();
echo $result[0]['field_name'];
I get a table check constraint definition this way:
select a.CHECK_CLAUSE
from INFORMATION_SCHEMA.CHECK_CONSTRAINTS a,INFORMATION_SCHEMA.TABLE_CONSTRAINTS b
where b.TABLE_NAME = 'table name'
For my example, suppose running this query returns this:
[([depname]='mathematics' OR [depname]='electronics' OR [depname]='computer science')]
How do I assign the values specified in the check constraint into variables? i.e. computer science, mathematics and electronics?
It looks like you're getting a string returned. What you can do is split the string on instances of OR and store that in an array, and then run through the array and split each element on = to isolate the values. So, if you were to do this in PHP, the code might look something like this:
// For reasons of simplicity we will assume the result is stored in $result,
// and the leading [( and trailing )] have already been removed
$values = array();
$resultsplit = explode(' OR ', $result);
/* $resultsplit is now an array:
* $resultsplit[0] = "[depname]='mathematics'"
* $resultsplit[1] = "[depname]='electronics'"
* $resultsplit[2] = "[depname]='computer science'"
*/
if ($result != '') {
foreach ($resultsplit as $rs) {
$rsparts = explode('=', $rs);
/* $rsparts is now an array. On the first element:
* $rsparts[0] = "[depname]"
* $rsparts[1] = "'mathematics'"
* So all we need to do is stick $rsparts[1] into $values
*/
$values[] = $rsparts[1];
}
}
This will put all of the values into the array $values (including the single-quotes at the beginning and end) for you to do with as you please, regardless of how many there are. If PHP is not the language you have available to you, the same method should still work in your language of choice.
I'm trying to develop a blog using webpy.
def getThread(self,num):
myvar = dict(numero=num)
print myvar
que = self.datab.select('contenidos',vars=myvar,what='contentTitle,content,update',where="category LIKE %%s%" %numero)
return que
I've used some of the tips you answer in this web but I only get a
<type 'exceptions.NameError'> at /
global name 'numero' is not defined
Python C:\xampp\htdocs\webpy\functions.py in getThread, line 42
Web GET http://:8080/
...
I'm trying to make a selection of some categorized posts. There is a table with category name and id. There is a column in the content table which takes a string which will be formatted '1,2,3,5'.
Then the way I think I can select the correct entries with the LIKE statement and some %something% magic. But I have this problem.
I call the code from the .py file which builds the web, the import statement works properly
getThread is defined inside this class:
class categoria(object):
def __init__(self,datab,nombre):
self.nombre = nombre
self.datab = datab
self.n = str(self.getCat()) #making the integer to be a string
self.thread = self.getThread(self.n)
return self.thread
def getCat(self):
'''
returns the id of the categorie (integer)
'''
return self.datab.select('categorias',what='catId', where='catName = %r' %(self.nombre), limit=1)
Please check the correct syntax for db.select (http://webpy.org/cookbook/select), you should not format query with "%" because it makes code vulnerable to sql injections. Instead, put vars in dict and refer to them with $ in your query.
myvars = dict(category=1)
db.select('contenidos', what='contentTitle,content,`update`', where="category LIKE '%'+$category+'%'", vars=myvars)
Will produce this query:
SELECT contentTitle,content,`update` FROM contenidos WHERE category LIKE '%'+1+'%'
Note that I backquoted update because it is reserved word in SQL.
Note: I have corrected the variable differences and it does print the query from the first set but it returns nothing from the second set. If I use the second set only it works.
In the code below, I have some_array which is array of array the array contains text like name. So
#some_array= ([sam, jon, july],[Mike, Han,Tommy],[angie, sita, lanny]);
Now when I querying the list like 'sam jon july' first and 'mike han tommy' . Only the execute return the result from the first list others is undef. I don't know why any help will be appreciated.
my $pointer;
my $db = $db->prepare_cached("
begin
:pointer := myFun(:A1);
end;
") or die "Couldn't prepare stat: " . $db->errstr;
$db->bind_param_inout(":pointer",\$pointer,0,{ ora_type => ORA_RSET });
for (my $i=0; $i < #some_array ; $i++) {
my #firstarray = #{$some_array[$i]};
my $sql = lc(join(" ", #firstarray));
print "<pre>$sql</pre>\n";
$db->bind_param(":A1",$sql);
$db->execute();
print "<pre>".Dumper($db->execute())."</pre>\n";
}
Just like everyone told you on the last question you asked, initialize your array with parentheses, not nested brackets.
#some_array= ([sam, jon, july],[Mike, Han,Tommy],[angie, sita, lanny])
not
#some_array= [[sam, jon, july],[Mike, Han,Tommy],[angie, sita, lanny]]
You would also benefit tremendously from including
use strict;
use warnings;
at the top of all of your programs. That would catch the strange way you are trying to initialize #some_array, and it would catch your inconsistent usage of #sql and #query. update and $sdh and $db and $dbh.
I wanted to use a named parameter placeholder inside the LIKE operator pattern so that the argument string is properly escaped.
Here's my modified code where I am using the at-param placeholder:
var stmt = new air.SQLStatement();
stmt.text = "SELECT * FROM comments WHERE title LIKE '%#search%';";
stmt.parameters["#search"] = "argument string";
stmt.execute();
Doing so yields an SQLError with the following details
message: Error #3315: SQL Error.
details: '#search' parameter name(s) found in parameters property but not in the SQL specified
As suggested by Mike Petty, I tried:
stmt.text = 'SELECT * FROM comments WHERE title LIKE "#%search%";';
Which yields to the same SQL Error details.
Documentation has this:
expr ::= (column-name | expr) LIKE pattern
pattern ::= '[ string | % | _ ]'
My suspicion is that it is skipped due to the qoutes, any ideas on how to make it work?
Found a solution for this, basically instead of doing it like this:
var stmt = new air.SQLStatement();
stmt.text = "SELECT * FROM comments WHERE title LIKE '%#search%';";
stmt.parameters["#search"] = "argument string";
stmt.execute();
You have to put a placeholder for the entire LIKE operator pattern and bind the pattern as a parameter.
var stmt = new air.SQLStatement();
stmt.text = "SELECT * FROM comments WHERE title LIKE #search;";
stmt.parameters["#search"] = "%" + userInput + "%";
stmt.execute();
Remove your :string from your string.
Like works just fine as:
SELECT * FROM comments WHERE comments.title LIKE '%string%';
It's hard to tell from your question, but is your current statement either throwing a SQLError, just doesn't compile, or just doesn't return any results?
If I had to guess I'd say you have a few issues here:
You shouldn't have to qualify the column in the where clause since you only have 1 table to select from
The parameter string is technically a reserved word by AIR / Actionscript (although the case is different) - still a bit confusing.
Even though the documentation and code allow you to use either the colon, or at-symbol, my preference is the # since it's a bit easier to see ;)
Don't forget to add an itemClass definition of the Class you expect for rows - this helps to avoid anonymous objects.
This should be fairly straight forward:
var stmt:SQLStatement = new SQLStatement();
stmt.itemClass = Comment;
stmt.text = 'SELECT * FROM comments WHERE title LIKE "#%search%";';
stmt.parameters['#search'] = userInput.text;
stmt.addEventListener(SQLEvent.RESULT, onResults);
stmt.execute();