PHP: strval in WHERE clause - php

Currently I have a piece of code that functions fine as it is. But what I really want to do is take the <?php if strval ..?> part and place it into the "SELECT * FROM projects" part as a WHERE clause. I am not sure whether this is possible or how to go about it. Any thoughts would be really valued. Hope this makes sense.
<?php
// ** User ID
$userid = $row_listelements ['id'];
// ** Projects
mysql_select_db($database_db, $db);
$query_activeusers = "SELECT * FROM projects ";
$activeusers = mysql_query($query_activeusers, $db) or die(mysql_error());
$row_activeusers = mysql_fetch_assoc($activeusers);
$totalRows_activeusers = mysql_num_rows($activeusers);
?>
<? do {?>
<?php if (!(strpos($row_activeusers['assignedto'], strval(",".$userid.",")) === false)) { ?>
<div><?=$row_activeusers['jobnumberdisplay'];?></div>
<?php } ?>
<? } while ($row_activeusers = mysql_fetch_assoc($activeusers)); ?>
<strong><?php echo $totalRows_activeusers; ?></strong>

In case your userid is a unique number, and I understand your question correctly, you could reach this by:
using IN - can handle strings and numbers (they have to be unique to make this work):
$query_activeusers = "SELECT * FROM projects WHERE ".$userid." IN (assignedto)";
or using FIND_IN_SET - can handle Strings and numbers is case sensitive:
$query_activeusers = "SELECT * FROM projects WHERE FIND_IN_SET('".$userid."', assignedto)"
But I think you should look at your database design. The trouble with including Foreign Keys in a delimited list like this is that whole point of a foreign key is to enable you to locate the information in the other table quickly, using Indexes. By implementing a database as it sounds you have, you have all sorts of issues to resolve.

i m not sure but maybe this will help you.
if(strval ...)
{
$where = "where field = $value";
}
Now you can use this $where variable in your select query. it will execute only if your if condition is satisfy.

If I understand your code correctly, you should use SQL LIKE, i.e. something like:
$query_activeusers = "SELECT * FROM projects WHERE assignedto LIKE '%," .
((int) $userid) . ",%'";
The cast to (int) here is done to ensure you have no special SQL characters in $userid - kind of cheap SQL quoting for values that are integers. You do not really need to use strval as concatenation into the string will convert that number into a string.

Related

Joining 2 statements to pull data from different tables

I have this code:
<?php
$data = mysql_query("SELECT * FROM repin WHERE new_pin_id LIKE ".$pinDetails->id) or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "".$info['from_pin_id'].",".$info['new_pin_id']."";
}
?>
Obtained thanks to this article: Check field for identical number
I'm trying to use the detail I pulled: ".$info['from_pin_id']." to get data from another table. I'm looking for the best way to do this.
I thought about making it a variable and then running a second statement within the same <?php?> which would look something like this:
Print "".$info['from_pin_id'].",".$info['new_pin_id']."";
}
$newdata = "".$info['from_pin_id']."";
// new statement here.
?>
But 1. it won't work and 2. it looks messy.
What is the best way to achieve it?
FYI, what I need to do is use ".$info['from_pin_id']." to match a field in another table where the data is the same ID, then pull more info based on the match.
Use the following query:
"SELECT *
FROM repin r
LEFT JOIN otherTable o
ON o.someColumn = r.from_pin_id
WHERE r.new_pin_id LIKE '".$pinDetails->id."'"
Also, the argument to LIKE must be a string; you need to put quotes around it.

Possible to use php tag inside query string?

I have multiple values passed through a POST form (from multiple check boxes of previous page) and I stored them into an array $vals. Now I want to write a query string (in a while loop) that generates a slightly different query depending on how far in the loop it has been.
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>
But it doesn't seem to work this way? I thought that by having double quotes for query, the
echo $vals[$i]
would generate the actual value of the current index in $vals[$i] and not the literal string? Is this what's happening? Can I not have php inside a query string that the mysql servers would accept?
lets just say i have a fooID in my server table that is '12345'. Even if I set $vals='12345' and write:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
it still doesn't work. I guess my general question would be: is it possible to write/get values of variables in a query string, and if not, is there another way around my situation? Any help is appreciated. Thanks!
You should not be placing the un-sanitized $_POSTed values into a SQL query. Look into using paramaterized arguments and mysqli.
You can output variables using the syntax:
$myVar = 'toast';
$combined = "I like $myVar";
However, this will not work as you would like for an array.
For an array, you'll want to look into using something like php's implode() to convert your array into a string first.
first of all never do queries in loop.
Second of all never use straight $_POST or $_GET or whatever client is passing in queries because you can be harmed by sql injections.wiki and also clearing data for mysql in php
ok so how it should be done (i am saying only about first one. second one i dont know how to make it without oop ).
<?php
$vals=($_POST['selectedIDs']);
$vals = implode(',',$vals);
$query = "SELECT * FROM List foo WHERE foo.fooID IN ($vals)";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
echo "YES IT WORKS!";
var_dump($row); //you will see all the data in one row
}
}?>
You have an extra echo in your SQL string:
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
It should be:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals[$i]";
Generally, it's a BAD idea to construct SQL strings from user input. Use prepared statements instead. Check here for more info on prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php
Thanks you guys for the advice but it turned out, my code didn't execute correctly because of a syntax error (and the extra echo statement). my original code was missing quotation marks around $vals[$i]. This is a mysql syntax mistake because it didn't accept foo.fooID=12345 but did for foo.fooID='12345'. Here is the final code that solved it
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = '$vals[$i]'";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>

Building interactive WHERE clause for Postgresql queries from PHP

I'm using Postgresql 9.2 and PHP 5.5 on Linux. I have a database with "patient" records in it, and I'm displaying the records on a web page. That works fine, but now I need to add interactive filters so it will display only certain types of records depending on what filters the user engages, something like having 10 checkboxes from which I build an ad-hoc WHERE clause based off of that information and then rerun the query in realtime. I'm a bit unclear how to do that.
How would one approach this using PHP?
All you need to do is recieve all the data of your user's selected filters with $_POST or $_GET and then make a small function with a loop to concatenate everything the way your query needs it.
Something like this... IN THE CASE you have only ONE field in your DB to match with. It's a simple scenario and with more fields you'll need to make it so that you add the field you really need in each case, nothing too complex.
<?php
//recieve all the filters and save them in array
$keys[] = isset($_POST['filter1'])?'$_POST['filter1']':''; //this sends empty if the filter is not set.
$keys[] = isset($_POST['filter2'])?'$_POST['filter2']':'';
$keys[] = isset($_POST['filter3'])?'$_POST['filter3']':'';
//Go through the array and concatenate the string you need. Of course, you might need AND instead of OR, depending on what your needs are.
foreach ($keys as $id => $value) {
if($id > 0){
$filters.=" OR ";
}
$filters.=" your_field = '".$value."' ";
}
//at this point $filters has a string with all your
//Then make the connection and send the query. Notice how the select concatenates the $filters variable
$host = "localhost";
$user = "user";
$pass = "pass";
$db = "database";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "SELECT * FROM table WHERE ".$filters;
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");
while ($row = pg_fetch_row($rs)) {
echo "$row[0] $row[1] $row[2]\n";
//or whatever way you want to print it...
}
pg_close($con);
?>
The above code will get variables from a form that sent 3 variables (assuming all of them correspond to the SAME field in your DB, and makes a string to use as your WHERE clause.
If you have more than one field of your db to filter through, all you need to do is be careful on how you match the user input with your fields.
NOTE: I did not add it here for practical reasons... but please, please sanitize user input.. ALWAYS sanitize user input before using user controlled data in your queries.
Good luck.
Don't do string concatenation. Once you have the values just pass them to the constant query string:
$query = "
select a, b
from patient
where
($x is not null and x = $x)
or
('$y' != '' and y = '$y')
";
If the value was not informed by the user pass it as null or empty. In the above query the x = $x condition will be ignored if $x is null and the y = '$y' condition will be ignored if $y is empty.
With that said, a check box will always be either true or false. What is the exact problem you are facing?
Always sanitize the user input or use a driver to do it for you!
I have created a Where clause builder exactly for that purpose. It comes with the Pomm project but you can use it stand alone.
<?php
$where = Pomm\Query\Where::create("birthdate > ?", array($date->format('Y-m-d')))
->andWhere('gender = ?', array('M'));
$where2 = Pomm\Query\Where::createWhereIn('something_id', array(1, 15, 43, 104))
->orWhere($where);
$sql = sprintf("SELECT * FROM my_table WHERE %s", $where2);
$statement = $pdo->prepare($sql);
$statement->bind($where2->getValues());
$results = $statement->execute();
This way, your values are escaped and you can build dynamically your where clause. You will find more information in Pomm's documentation.

Query for select multiple values from 2 tables

Table names:
tbla_can_types
Fields are fac_id,type_id,type_name,status
tbla_canteen_rates (there is no data in this table)
Fields are `fac_id,cat_id,type_id,from time,to_time,rate,off_rate,status,effective_date.,can_id(sequence number)
<?php
include('adodb/adodb.inc.php');
$conn=&ADONewconnection('oci8');
$conn->Pconnect('conn','hostname','username','pwd');
$fac_id=$_GET['fac_id'];
$cat_id=$_GET['cat_id'];
$file=fopen("text.txt","w+");
global $newId;
header("Content-type: text/xml");
echo('<?xml version="1.0" encoding="iso-8859-1"?>');
echo "<data>";
$ids = explode(",",$_POST["ids"]);
$rates="select type_id,from_time,to_time,rate,off_rate,status,to_char(effective_date,'dd-Mon-yyyy') e_date,can_id from tbla_canteen_rates where fac_id=$fac_id and cat_id=$cat_id order by to_number(substr(from_time,0,length(from_time)-3))";
$rs1=$conn->Execute($rates);
if(!$rs1->EOF)
echo $rs1->fields[0].'~'.$rs1->fields[1].'~'.$rs1->fields[2].'~'.$rs1->fields[3].'~'.$rs1->fields[4].'~'.$rs1->fields[5].'~'.$rs1->fields[6].'~'.$rs1->fields[7];
$temp_id=$rs1->fields[0];
echo $temp_id;
$rs1->MoveNext();
for ($i=0; $i < sizeof($ids); $i++)
{
$rowId = $ids[$i]; //id or row which was updated
$newId = $rowId; //will be used for insert operation
$mode = $_POST[$rowId."_!nativeeditor_status"]; //get request mode
switch($mode)
{
case "inserted":
$insert= "insert into tbla_canteen_rates(type_id,from_time,to_time,rate,off_rate,status,effective_date,fac_id,cat_id )values
($temp_id,
'".$_POST[$rowId."_c1"]."',
'".$_POST[$rowId."_c2"]."',
'".$_POST[$rowId."_c3"]."',
'".$_POST[$rowId."_c4"]."',
'".$_POST[$rowId."_c5"]."',to_date('".$_POST[$rowId."_c6"]."','dd-Mon-yyyy'),$fac_id,$cat_id)";
$conn->Execute($insert);
fwrite($file,$insert);
$action='add_row($rowId)';
break;
case "deleted":
$delete = "delete from tbla_canteen_rates where can_id=".$rowId ;
$conn->Execute($delete);
fwrite($file,$delete);
$action ='delete_row($rowId)';
break;
default:
$update ="update tbla_canteen_rates set
type_id=$temp_id,
from_time='".$_POST[$rowId."_c1"]."',
to_time='".$_POST[$rowId."_c2"]."',
rate='".$_POST[$rowId."_c3"]."',
off_rate='".$_POST[$rowId."_c4"]."',
status='".$_POST[$rowId."_c5"]."',
effective_date=to_date('".$_POST[$rowId."_c6"]."','dd-Mon-yyyy'),
fac_id='$fac_id',cat_id='$cat_id'
where can_id=".$rowId;
$conn->Execute($update);
fwrite($file,$update);
$action = 'update_row($rowId)';
break;
}
echo "<action type='".$action."' sid='".$rowId."' tid='".$newId."'/>";
}
echo "</data>";
?>
In the query i need id for type_id in a variable
i have written but every time it is getting id of first element only.
in this i need an id for type_id.
please send me the code 4 that
Regards
Pawan
I've got a sneaking suspicion that you've got several questions in there, but since you asked about the sql query, this should work:
Note: I'm assuming fac_id is the id that binds the two tables together. "var_fac_id" and "var_cat_id" are the values from your comboboxes.
Select t1.type_name, t2.from_time, t2.to_time, t2.rate
FROM tbla_can_types as t1 LEFT JOIN tbla_canteen_rates as t2
ON t1.fac_id = t2.fac_id
WHERE t1.fac_id = var_fac_id AND t2.cat_id = var_cat_id
Further notes: I think this should work despite the "AND t2.cat_id = var_cat_id" (which obviously would find not results in an empty table), since it's a left join. If it returns an empty set, however, see if it works if you remove it.
Update:
your comment above makes me think the tables are bound together by type_id instead. If that's the case, use ON t1.type_id = t2.type_id instead of ON t1.fac_id = t2.fac_id
Update #2 based on poster's comments
I'm not going to do your homework, dude. And homework is the only place where they'd tell you to not do joins. I will send you to some resources that will help you learn this stuff, though. Check out the basic mysql example from php.net: http://www.php.net/manual/en/mysql.examples-basic.php . That sample actually gets you pretty close to what you need. Also their overall mysql documentation, which is good for looking up what specific functions do: http://www.php.net/manual/en/book.mysql.php . Finally, remember that you're learning two languages here -- PHP, along with its functions to access a mysql DB, and -- SQL, which is a query language used within DBs. For SQL, check out http://sqlzoo.net/ , which seems a decent introduction on how to write queries.
Good luck on your assignment.

Search entire table? PHP MySQL

I have made the following search script but can only search one table column when querying the database:
$query = "select * from explore where site_name like '%".$searchterm."%'";
I would like to know how I can search the entire table(explore). Also, I would need to fix this line of code:
echo "$num_found. ".($row['site_name'])." <br />";
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Thanks for any help, here is the entire script if needed:
<?php
// Set variables from form.
$searchterm = $_POST['searchterm'];
trim ($searchterm);
// Check if search term was entered.
if (!$serachterm)
{
echo "Please enter a search term.";
}
// Add slashes to search term.
if (!get_magic_quotes_gpc())
{
$searchterm = addcslashes($searchterm);
}
// Connects to database.
# $dbconn = new mysqli('localhost', 'root', 'root', 'ajax_demo');
if (mysqli_connect_errno())
{
echo "Could not connect to database. Please try again later.";
exit;
}
// Query the database.
$query = "select * from explore where site_name like '%".$searchterm."%'";
$result = $dbconn->query($query);
// Number of rows found.
$num_results = $result->num_rows;
echo "Found: ".$num_results."</p>";
// Loops through results.
for ($i=0; $i <$num_results; $i++)
{
$num_found = $i + 1;
$row = $result->fetch_assoc();
echo "$num_found. ".($row['site_name'])." <br />";
}
// Escape database.
$result->free();
$dbconn->close();
?>
Contrary to other answers, I think you want to use "OR" in your query, not "AND":
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
Replace other_column with the name of a second column. You can keep repeating the part I added for each of your columns.
Note: this is assuming that your variable $searchterm has already been escaped for the database, for example with $mysqli->real_escape_string($searchterm);. Always ensure that is the case, or better yet use parameterised queries.
Similarly when outputting your variables like $row['site_name'] always make sure you escape them for HTML, for example using htmlspecialchars($row['site_name']).
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Make sure that both forms use the same method (post in your example). The <form> tag should have the attribute method="post".
Also, what is wrong with the line of code you mentioned? Is there an error? It should work as far as I can tell.
A UNION query will provide results in a more optimized fashion than simply using OR. Please note that utilizing LIKE in such a manner will not allow you to utilize any indexes you may have on your table. You can use the following to provide a more optimized query at the expense of losing a few possible results:
$query = "SELECT * FROM explore WHERE site_name LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE other_field LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE third_field LIKE '".$searchterm."%'";
This query is probably as fast as you're going to get without using FULLTEXT searching. The downside, however, is that you can only match strings beginning with the searchterm.
To search other columns of table you need to add conditions to your sql
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
But if you don't know that I would strongly advise going through some sql tutorial...
Also I didn't see anything wrong with this line
echo "$num_found. ".($row['site_name'])." <br />";
What error message are you getting?
Just add 'AND column = "condition"' to the WHERE clause of your query.
Be careful with adding lots of LIKE % conditions as these can be very slow especially if using a front wild card. This causes the RDBMS to search every row. You can optimize if you use an index on the column and only a trailing wildcard.
You are searching the whole table, just limiting the results to those where the site_name like '%".$searchterm."%'. If you want to search everything from that table, you need to remove the WHERE clause
Here's the corrected line. You had a few too many quotes in it.
echo $num_found.".".($row['site_name'])." <br />";
Regarding displaying the message, you have a typo in your code:
// Check if search term was entered.
if (!$serachterm)
should be:
// Check if search term was entered.
if (!$searchterm)
In the code you have written, !$serachterm always evaluates to true because you never declared a variable $seracherm (note the typo).
your code is very bugy for sql injection first do
do this
$searchterm = htmlspecialchars($searchterm);
trim($searchterm);
next
$query = mysql_real_escape_string($query);
finaly your search looks like this
$query = "select * from explore where site_name like '%$searchterm%';

Categories