way to check for if sql row exists? - php

my problem is this
i am fetching a mysql row via this
$sql_istorrenthere = $this->query_silent("SELECT media_type
FROM " . DB_PREFIX . "auction_media WHERE
auction_id='" . $item_details['auction_id'] . "'");
$row = mysql_fetch_array($sql_istorrenthere);
and then calling it with this
if ($row['media_type'] == 4)
{
$display_output = GMSG_TORRENT;}
else
{
$display_output = GMSG_NOTORRENT;
}
}
however, media_type has multiple values, (1,2,3,4)
how to write it so that it checks if 4 exists? because now i believe it is checking if media_type equals 4 and that is false, which is giving me the wrong display_output

You can use mysql_num_rows to determine if any rows were returned, and this works by adding a search condition in your query adding " AND media_type = 4" to the end
if(mysql_num_rows($sql_istorrenthere)) {
} else {
}
// You can loop through records by doing the following, this prints out every media type :)
while ($row = mysql_fetch_array($sql_istorrenthere)) {
echo $row['media_type'] . '<br />';
}

You can just add on "AND media_type = '4'" to your query. But you really should use paramaterized queries.
Once your query has "AND media_type = '4'" you can check RowCount.

There are probably better ways, but here's one idea.
$media_type_ids = explode(',', $row['media_type']);
if (array_search(4, $media_type_ids) !== FALSE) {
// found
}
It could be possible to even do this in-situ in the database query ... potentially.

// Comment the next line after you get what it is
#print ("Value of media type is: >>>".$row['media_type']."<<<"); // Line to be commented
if (isset($row['media_type']) && $row['media_type'] == 4) {
$display_output = GMSG_TORRENT;
}
else {
$display_output = GMSG_NOTORRENT;
}
To fetch all media types:
<?php
$sql_istorrenthere = $this->query_silent("SELECT media_type FROM " . DB_PREFIX . "auction_media");
while ($row = mysql_fetch_array($sql_istorrenthere)) {
// Comment the next line after you get what it is
#print ("Value of media type is: >>>".$row['media_type']."<<<"); // Line to be commented
if (isset($row['media_type']) && $row['media_type'] == 4) {
$display_output = GMSG_TORRENT;
}
else {
$display_output = GMSG_NOTORRENT;
}
}

Related

PHP/PDO Dynamically binding values (invalid param count error)

I was tasked (stuck) with trying to update an old mysql_query code to be PDO compliant.
This was (is) a messy search form, that was dynamically creating the query string based on field values if (or not) there were any key words submitted along with the form. (ie: any key word is parsed by spaces, and used for BOTH column searches)
So if a search term of 'dog' was entered.. it would search name & title for the key word of 'dog'..
I think I made my way through it.. keeping the main 'function' in-tact for the most part.. and updating when I needed to.
My approach was to take the function that is dynamically adding more criteria to the query string.... and also add this value field name & value to an array, so I can loop through it later on and dynamically bindValues with it..
I am now stick with the ever so popular Invalid Parameters error!!
However its not saying the counts dont match.. its saying it was defined at all.
I'm not clear where my error is stemming from.. (or how to easily see the computed/parsed query string.. or the actual bound parameters) I can just output the sql statement (before it parses any data).. or echo out my values in the array I loop through to (potentially) bind the data to the PDO call..
WHen I echo out the query (string).. and even the values I am attempting to dynamically bind... they all look legit to me:
Query Check: SELECT * FROM pid_information WHERE 1=1 AND (((title LIKE :title0) OR (name LIKE :name0)) AND ((title LIKE :title1) OR (name LIKE :name1))) ORDER BY title, name, link
PARAM CHECK: ':title0' -> %cat%
PARAM CHECK: ':name0' -> %cat%
PARAM CHECK: ':title1' -> %dog%
PARAM CHECK: ':name1' -> %dog%
To re-cap:
addCriteria() function is used to dynamically (concat) add to the query 'string'
I also populate an array to be used later to loop through and bindValues with.
Yes I know it is long.. yes I know ugly.. (please, just bear with me!) LOL
//dynamically add criteria to query
$boundSearchValues = array();
function addCriteria($targetFields, $criteriaString, $targetOperator='LIKE'){
global $boundSearchValues;
$fieldCount = 0;
$tempString = "";
if($criteriaString != ""){
$criteriaArray = explode(" ", $criteriaString);
$tempString .= " AND (";
foreach($criteriaArray as $criteriaIndex => $criteriaValue){
//is array of fields
if(is_array($targetFields)){
$tempString .= "(";
foreach ($targetFields as $targetField => $fieldName){
if($targetOperator != 'LIKE') {
$tempString .= "($fieldName ".$targetOperator." :". $fieldName.$fieldCount .")";
$boundSearchValues[] = [$fieldName.$fieldCount, $criteriaValue];
}else{
$tempString .= "($fieldName LIKE :". $fieldName.$fieldCount .")";
$boundSearchValues[] = [$fieldName.$fieldCount, '%'.$criteriaValue.'%'];
}
if($targetField+1 < count($targetFields)){
$tempString .= " OR ";
}
}
$tempString .= ")";
if($criteriaIndex+1 < count($criteriaArray)){
$tempString .= " AND ";
}
//not an array of fields
}else{
if($targetOperator != 'LIKE') {
$tempString .= "(".$targetFields . $targetOperator . " :" . $fieldName.$fieldCount . ")";
$boundSearchValues[] = [$fieldName.$fieldCount, $criteriaValue];
} else {
$tempString .= "(". $targetFields . " LIKE " . $fieldName . $fieldCount . ")";
$boundSearchValues[] = [$fieldName.$fieldCount, '%'.$criteriaValue.'%'];
}
}
$fieldCount++; //increment counter
}
$tempString .= ")";
}
return $tempString;
}
//start serach query
$searchDetails_sql = "SELECT * FROM $tablename ";
//dynamically update query string
if($clean_keywords != "") {
$whereClause = addCriteria(array('title', 'name'), $clean_keywords);
}else{
if($title != "" && $title != "all"){
$whereClause .= " AND title = :" . $title;
}
if($name != "" && $name != "all"){
$whereClause .= " AND name = :" . $name;
}
if($link != "" && $link != "all"){
$whereClause .= " AND link = :" . $link ;
}
}
$searchDetails_sql .= "WHERE 1=1 ". $whereClause;
$searchDetails_sql .= " ORDER BY title, name, link";
$searchDetails_stmt = $conn->prepare($searchDetails_sql);
//dynamically bind values
for($i=0; $i<count($boundSearchValues); $i++){
$searchDetails_stmt->bindValue("':".$boundSearchValues[$i][0] ."'", $boundSearchValues[$i][1]);
//$searchDetails_stmt->bindParam("':".$boundSearchValues[$i][0] ."'", $boundSearchValues[$i][1]);
echo '<br>PARAM CHECK: ' . $boundSearchValues[$i][0] . " / " . $boundSearchValues[$i][1];
}
$searchDetails_stmt->execute();
$searchDetails_stmt->setFetchMode(PDO::FETCH_ASSOC);
$searchDetails = $searchDetails_stmt->fetchAll(); //returns multi-dimensional array (and correct count)
I think you just messed up the string concatenation in this line
$searchDetails_stmt
->bindValue("':".$boundSearchValues[$i][0] ."'", $boundSearchValues[$i][1]);
You dont actually need the : so you could do this
$searchDetails_stmt
->bindValue($boundSearchValues[$i][0], $boundSearchValues[$i][1]);
Or fix the concatenation and keep the :
$searchDetails_stmt
->bindValue(":".$boundSearchValues[$i][0], $boundSearchValues[$i][1]);

get a value from key value pair list in php

I want to display a specific value from key value list..
here is my code:
if (isset($_POST) && count($_POST)>0 )
{
foreach($_POST as $paramName => $paramValue) {
echo "<br/>" . $paramName . " = " . $paramValue;
}
}
ouput
ORDERID = ORDS3700373
TXNAMOUNT = 200.00
CURRENCY = INR
TXNID = 32221284
BANKTXNID = 475815
STATUS = TXN_SUCCESS
RESPCODE = 01
RESPMSG = Txn Successful.
TXNDATE = 2017-01-10 18:13:25.0
GATEWAYNAME = WALLET
BANKNAME =
PAYMENTMODE = PPI
CHECKSUMHASH =
here I want to display only ORDERID and TXNID.. How do I get that value?
You can easily access post values by it's field name instead of looping through all post elements. Simply access that elements directly as below:
if(isset($_POST['ORDERID'])) {
echo 'ORDERID = '.$_POST['ORDERID'];
}
if(isset($_POST['TXNID'])) {
echo 'TXNID= '.$_POST['TXNID'];
}
Moving comments to an answer.
You do not need to loop post it is just a global array. You can access the values at any of the keys like any associative array because that is what it is. Likewise these value can be used like any other
if(isset($_POST['ORDERID'])){
$orderid = $_POST['ORDERID'];
}
if(isset($_POST['TXNID'])){
$txnid = $_POST['TXNID'];
}
// Should use htmlspecialchars() or htmlentities() here
// but didn't want to confuse OP. It is for security.
echo "ORDERID is: " . $orderid . " and TXNID is: " . $txnid;
A note for security never trust user input and sanitize all $_POST variables before echoing or persisting. There are far better article out on the internet than I can summarize here.
You can use if condition in the loop like this
if (isset($_POST) && count($_POST)>0 )
{
foreach($_POST as $paramName => $paramValue) {
if($paramName == 'ORDERID' || $paramName == 'TXNID')
echo "<br/>" . $paramName . " = " . $paramValue;
}
}
add an if like
if($paramName == "ORDERID" || $paramName == "TXNID") {
after foreach, remeber to close it after echo statement line
Don't overcomplicate a trivial task with a loop.
Just drop the loop and echo the two values directly:
// Assuming the two values are expected to come in pair:
if(isset($_POST['ORDERID']) && isset($_POST['TXNID'])) {
echo "<br/>ORDERID = " . $_POST['ORDERID'];
echo "<br/>TXNID = " . $_POST['TXNID'];
}
If you insist on having a loop, then you can go through the property names which you need
foreach(array('ORDERID', 'TXNID') as $paramName) {
if(isset($_POST[$paramName])) {
echo "<br/>" . $paramName . " = " . $_POST[$paramName];
}
}

php mysql search options combination

i have got 4 checkboxes for filterung mysql result. Checkboxes can be activated all or single, too. I don't know how to make sql statement. DO i really have to use all combined possibilities manually or is there a simplier solution? Perhaps with "switch"?
No as first statement i have:
if ($vart1 == "1" AND !isset($vart2) AND !isset($vart2) AND !isset($vart2) AND !isset($vart4)) {
$tname_sql .= " a.tdesc = 'option1' AND";
};
How many variations are there?
Thank you for help.
Regards,
Olaf.
You can make a simple PHP function which returns WHERE or AND depending how many times has been called:
$wa = 0;
function whereAnd() {
global $wa;
if ($wa == 0) {
$wa = 1;
return ' WHERE ';
} else {
return ' AND ';
}
}
$query = "SELECT * FROM table1 t ";
if (isset($var1)) {
$query .= whereAnd() . "t.field1 = " . $var1;
}
if (isset($var2)) {
$query .= whereAnd() . "t.field2 = " . $var2;
}
if (isset($var3)) {
$query .= whereAnd() . "t.field3 = " . $var3;
}
if (isset($var4)) {
$query .= whereAnd() . "t.field4 = " . $var4;
}
First call will returns WHERE, all other calls will return AND no matter what kind of combinations you may have. You don't need to care about how many checkboxes are passed.

I need a character or string which will match ANY value in my table field

I have a form that requires the user to only fill out at least 1 (out of four) fields. They can then submit and get a search result based off of their input.
The problem is, I can't get a character to set my variables to that will match any database value. Here is my code for some context;
if (isset($_POST['buildname']) ||
isset($_POST['weapon']) ||
isset($_POST['category']) ||
isset($_POST['id']))
{
if ($_POST['buildname'] == "")
{
$buildname = ".*";
}
if ($_POST['weapon'] == "")
{
$weapon = ".*";
}
if ($_POST['category'] == "")
{
$category = ".*";
}
if ($_POST['id'] == "")
{
$id = ".*";
}
$buildname = sanitizeString($_POST['buildname']);
$weapon = ($_POST['weapon']);
$category = ($_POST['category']);
$id = ($_POST['id']);
$searchstring = "SELECT buildname,weapon,category,id,author FROM weapons " .
"WHERE buildname='$buildname' AND weapon='$weapon' AND category='$category' AND id='$id'";
As you can see, the code looks at if one of the variables is set, then submits a form. If a variable isn't set, it assigns a character of ".*" (which I thought would match anything). It then queries the database to match any rows. I get no results unless I enter EVERY field with a correct entry.
Any ideas?
Thanks!
I would not use %, instead do something like this
if (isset($_POST['buildname']) || isset($_POST['weapon']) || isset($_POST['category']) || isset($_POST['id'])){
$sqlArray = array();
if(isset($_POST['buildname'])){
$sqlArray[] = "buildname='" . mysqli_real_escape_string($connection,$_POST['buildname']) . "'";
}
if(isset($_POST['weapon'])){
$sqlArray[] = "weapon='" . mysqli_real_escape_string($connection,$_POST['weapon']) . "'";
}
if(isset($_POST['category'])){
$sqlArray[] = "category='" . mysqli_real_escape_string($connection,$_POST['category']) . "'";
}
if(isset($_POST['id'])){
$sqlArray[] = "id='" . mysqli_real_escape_string($connection,$_POST['id']) . "'";
}
$searchstring = "SELECT buildname,weapon,category,id,author FROM weapons " .
"WHERE " . implode(' AND ', $sqlArray);
}
The wildcard character for MySQL is: %
The query you are executing, you "thought would match anything" wont. The statement uses no regular expressions.
WHERE buildname='$buildname' AND weapon='$weapon'
Which is essentially saying you need to have the following fields equal their string value of:
WHERE buildname='.*' AND weapon='.*'
I doubt you have any building with a name of .*.
It would be better to not filter on that field. basically remove the WHERE cause criteria if the variable is not defined.
You can do this dynamically, buliding the SQL statement only when you need to filter by that field.
if (isset($_POST['somevalue']) && ! empty($_POST['somevalue'])) {
$where .= 'column_name = ?';
$values[] = sanitizeString($_POST['somevalue]);
}
I've also used positional parameters which assumes you will be using the PDO or MySQLi libraries for querying.
No, you are using = operator, that only compares 2 values. In your case it will search for '.*' - and fail. If you want to ignore the fields, that were not filled, just don't put them into the query: no need for regexps. So, if the weapon and category are missing, your query should be like this
$searchstring = 'SELECT buildname,weapon,category,id,author FROM weapons WHERE ';
$fields = array('buildname', 'weapon', 'category', 'id');
$data = array();
foreach($fields as $value)
{
if (isset($_POST[$value]) && ($_POST[$value] != "") )
{
$data[] = sanitizeString($_POST[$value]);
}
}
$n = count($data);
if($n > 0)
{
$searchstring .= implode(' AND ', $data);
//do MySQL request and output result
}
Don't overcomplicate simple things. Also your code is vulnerable to SQL injection as some fields are not escaped.
You can do it like this:
$fields = array('buildname', 'weapon', 'category', 'id');
$sql = 'SELECT buildname, weapon, category, id, author FROM weapons';
$prefix = ' WHERE ';
foreach ($fields as $field) {
if (isset($_POST[$field]) && strlen($_POST[$field])>1) {
$sql .= $prefix . $field . '=\''
. sanitizeString($_POST[$field]) . '\'';
$prefix = ' AND ';
}
}
if ($prefix == ' AND ') {
// send the query
}
Notice: if you want to perform search with incomplete values, you could use LIKE instead of =, example:
$sql .= $prefix . $field . ' LIKE \'%' . sanitizeString($_POST[$field]) . '%\'';
But keep in mind that LIKE is slower than =

Can anyone explain the following PHP Code?

Can anyone explain what the following PHP Code does
function query($query_string)
{
if ($query_string == "") {
return 0;
}
if (!$this->connect()) {
return 0;
};
if ($this->QueryID) {
$this->free_result();
}
if ($this->RecordsPerPage && $this->PageNumber) {
$query_string .= " LIMIT " . (($this->PageNumber - 1) * $this->RecordsPerPage) . ", " . $this->RecordsPerPage;
$this->RecordsPerPage = 0;
$this->PageNumber = 0;
} else if ($this->RecordsPerPage) {
$query_string .= " LIMIT " . $this->Offset . ", " . $this->RecordsPerPage;
$this->Offset = 0;
$this->RecordsPerPage = 0;
}
$this->QueryID = #mysql_query($query_string, $this->LinkID);
$this->Row = 0;
$this->Errno = mysql_errno();
$this->Error = mysql_error();
if (!$this->QueryID) {
$this->halt("Invalid SQL: " . $query_string);
}
return $this->QueryID;
}
function next_record()
{
if (!$this->QueryID) {
$this->halt("next_record called with no query pending.");
return 0;
}
$this->Record = #mysql_fetch_array($this->QueryID);
$this->Row += 1;
$this->Errno = mysql_errno();
$this->Error = mysql_error();
$stat = is_array($this->Record);
if (!$stat && $this->AutoFree) {
$this->free_result();
}
return $stat;
}
Can the above be done in a simpler way , would it be wise to use an ORM ?
The first class method looks like it performs a MySQL query and adds a LIMIT clause for pagination. The second moves the current query onto the next record, while incrementing the pagination counters.
In more detail, here's the first sample:
Exit the method if the query is empty or the database connection doesn't exist.
Free any existing query.
If the number of records per page and page number are set:
Add them to the LIMIT clause of the query.
And reset them to 0.
Otherwise if records per page is set:
Add it to the LIMIT clause of the query.
And reset them to 0.
Run the query.
Set the current row to 0.
Collect errors.
If the query failed halt with the error.
Return the query.
And the second:
If the query is not set halt with an error.
Fetch row information as an array for the current row.
Increment the row number.
Catch any errors.
If the result isn't an array free/close the query.
Otherwise return the result set.
Yes you are right Ross it something like pagination function in a class which calls the records one by one.

Categories