I have created a form which queries a MySQL database and displays results. Now I want to be able to filter my results. I have:
<input type="checkbox" name="multi_cif[]" value="<?php echo $g1 ?>"><font size="1" face="Arial, Helvetica, sans-serif">
In the output which is displaying all results via foreach and the variable $g1 is a MySQL query value (address). I want to be able to click these check boxes next to the results so when the user clicks the button labeled "Filter" only the results checked are displayed.
So far my code is as follows:
<?PHP
if (isset($_POST['Submit2']))
{
$stmt = $dbh->prepare('SELECT * FROM CIF WHERE address LIKE ?');
$stmt->execute(array("%$_POST[multi_cif]%"));
//$stmt->execute(array(":term" => "%" . $_POST["multi_cif"] . "%"));
//$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
/*while ($results = $stmt->fetch()) //WILL UNCOMENT AND ADD OR LIKE AFTER SINGLE QUERY WORKING
{
echo $results['address'];
echo $results['alternativeid'];
}*/
print_r($_POST);
$results = $stmt->fetch();
echo $results['address'];
echo $results['alternativeid'];
}
?>
The commented out stuff is other things I have tried. I am very close to my results. The results of the following code ends in:
[multi_cif] => Array ( [0] => test.13ann.com [1] => testfortestltd444557.com.tw ) ) coralarray.ruhttp://mirror3.malwaredomains.com/files/domains.txt
So clearly "Array" is being passed as a value instead of the desired address assigned to multi[]. Could someone please explain why this is and help me fix it? I am new to PDO as of yesterday but have chosen to use it and re-work my other statements to implement prepared statements instead of dynamically building them. Thanks in advance!
Edited: I took some of Brad's advice but kept the statement without the additional "OR address LIKE ?" as right now I am only clicking one checkbox but still getting "Array" instead of "test.13.ann.com" Once I figure out why "Array" vs. value I will add the additional OR --thanks Brad for pointing out!
Try accessing the first array value, rather than the outer array -
$stmt->execute(array("%{$_POST['multi_cif'][0]}%"));
to do it dynamically you could try
// create n number of placeholders based off number of $_POST['multi_cif']
$place_holders = implode(' OR', array_fill(0, count($_POST['multi_cif']), ' address LIKE ?'));
// create n number of values based off number of $_POST['multi_cif']
$values = '"%'. implode('%","%', $_POST['multi_cif']).'%"';
// explode the values into an array
$values = explode(',',$values);
$stmt = $dbh->prepare("SELECT * FROM CIF WHERE $place_holders");
$stmt->execute(array($values));
You were nearly there. You didn't concatenate your parameter correctly.
Try
<?php
if (isset($_POST['Submit2']))
{
$term = "%" . $_POST["multi_cif"] . "%";
$stmt = $dbh->prepare('SELECT * FROM CIF WHERE address LIKE ?');
$stmt->execute(array($term));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
while ($rows = $stmt->fetch())
{
echo $results['address'];
echo $results['alternativeid'];
}
}
?>
Related
This is my Entire Code:
<?php
$query = "SELECT category FROM html where id = '1' ";
$result = mysql_query($query);
//while loop to display mysql table field values in html text boxes
$i = 0;
while ($row = mysql_fetch_row($result)) {
$count = count($row);
$y = 0;
while ($y < $count) {
$c_row = current($row);
next($row);
$y = $y + 1;
}
$i = $i + 1;
$category = $c_row;
}
echo $category;
?>
I am showing the value of $categories variable using this code given below:
Categories ( '. $categories; .' )
Actaully, the above code including to is not directly written in php
web page. The code "Categories ( '. $categories; .' ) " is containing in the data base. Therefore $categories; cannot be parsed.
What I need is to show the Value:
Eg, if $categories = Books and Shelf;
I need, Categories ( '. $categories; .' ) :- Categories (Books and Shelf)
The $categories; value is already obtained in the php page before selecting from Mysql Table.
How can I parse php variable inserted in Mysql Row?
Categories ( '. $categories; .' ) :- The complete html tag is putted in the data base. The complete html code in the Mysql DB.
I'd like to know why you are storing variable references like that in your db but to solve it you could simply do something like this:
/*
assuming $string contains EXACTLY this
<h4>Categories ( '. $categories; .' ) </h4>
*/
echo str_replace('\'. $categories; .\'',$categories, $string);
If you commonly need to do word replacement on strings stored in a database I would recommend one of the following instead:
1) Use sprintf() and store your string like this:
$string = '<h4>Categories ( %s ) </h4>';
echo sprintf($string, $categories);
2) Use str_replace() and format string with braces around replacements:
$string = '<h4>Categories ( {categories} ) </h4>';
echo str_replace('{categories}', $categories, $string);
The benefit of that last one is you could store all kinds of variable references and replace them accordingly without having to know if they exist in the string:
$string = 'Hello, my name is {firstname} and I live in {city}, {state}';
$replace = ['{firstname}','{lastname}','{address}','{city}','{state}'];
$info = [
'firstname' => 'john',
'lastname' => 'doe',
'address' => '123 main st',
'city' => 'somewhere',
'state' => 'IL'
];
echo str_replace($replace, $info, $string);
OUTPUT: Hello, my name is john and I live in somewhere, IL
A rewrite of your code:
1) Stop using MySQL_ fuctions, they are deprecated, insecure and should not be used. There are two alternatives; mysqli_ functions (Object orientated or Procedural) or PDO functionality (object orientated only)
2) Your question appears uclear, is your <h4> tag within <?php tags or is it just HTML? To output PHP you need to wrap the print/echo article in <?php tags to tell the server how to process this section of the code.
Likewise, you need to be sure the page is pocessed as a PHP page rather than just as an HTML page. So does the page name end with .php (such as page.php)?
3) For clarity: while ($row = mysql_fetch_row($result)) will only ever output one row at a time, each MySQL row with hold numerous columns.
4) It's very useful for you to indent your brackets correctly, typing four spaces (not tab) for each bracket contents, as exampled a litte bit below.
5) Your While loops are confused; you have too any brackets. Your value $c_row will only ever be the final value found in the row, but the row will only ever have one unqiue value in it -- that of the category column, because that's what's specified in the SQL query.
Rewrite:
/***
* Fill with your own values, Address is usually 'Localhost'
***/
// connction details:
$conn = mysqli_connect(Address, User, Password, Database);
// A numeric column (id) does not need values to be quoted.
$query = "SELECT category FROM html where id = 1 ";
// note the mysqli_ and use of new $conn variable setout above
$result = mysqli_query($conn, $query);
/***
* Typical output from the above for returning two rows from
* the DB would be:
* $result[0]['category'] = "whatever_value"
* $result[0][0] = "whatever_value"
* $result[1]['category'] = "whatever_value_row2"
* $result[1][0] = "whatever_value_row2"
***/
// This will fetch all the rows, one row at a time,
// with array keys being the SQL column names
// (ignores numeric array keys).
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
// use definite named array key selectors to not need counters.
$category = $row['category'];
echo $category;
}
That would give you an output:
whatever_value
whatever_value_row2
To make your <h4> work as expected you can try replacing your echo with:
print "<h4>Categories ( ". $category; ." ) </h4>";
I have actors field in my movie database which is having many actors in one field separated by comma and fetching them using below code. My requirement is to link all fetched actors. on click on each actor will take to the list of their movie.
Since i am having all actors in one field and separated by commas, struggling to link each of them with separate url
<?php
require('connect');
$filmActor=$_GET['filmActor'];
$sql ="SELECT * FROM films WHERE filmActor LIKE '%$filmActor%' LIMIT 0 , 5;";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result))
{
$filmActor=$row['filmActor'];
$filmName=$row['filmName'];
$url=$row['url'];
echo "
<a href='$url.html'>$filmName</a>: $filmActor<br>
";
}
mysqli_free_result($result);
mysqli_close($conn);
?>
Output i am getting like:
Expected:
Want to pass this parameter:
/actor.php?filmActor=Tom_Hanks, /actor.php?filmActor=Emma_Thompson etc will displace each actors film they have worked on.
This script should work. It takes the $row['filmActor'] and split all the actors into an array by ',', and then we print them out one after one.
Just keep in mind that this can be done a better way, but this should work.
Also, I've added a "mysqli_real_escape_string" to the GET input "$_GET['filmActor']" to prevent SQL injections.
<?php
require('connect');
// Escape the input from the user, preventing SQL injections
$filmActor = mysqli_real_escape_string($conn,$_GET['filmActor']);
$sql ="SELECT * FROM films WHERE filmActor LIKE '%$filmActor%' LIMIT 0 , 5;";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result))
{
$filmActor=$row['filmActor'];
$filmName=$row['filmName'];
$url=$row['url'];
echo "<a href='$url.html'>$filmName</a>:";
// Make an array of the actors by splitting them by ','
$actorsArray = explode(',',$filmActor);
// Loop the array
foreach ($actorsArray as $key => $actor)
{
// Just trim the space in front of name in case there is any
$actor = trim($actor);
// Check if the current key is == to the last key in the array
// so it wont make an ',' in the end of the actors.
if ($key == (count($actorsArray)-1))
echo "<a href='/actor.php?filmActor=$actor'>$actor</a>";
else
echo "<a href='/actor.php?filmActor=$actor'>$actor</a>, ";
}
}
mysqli_free_result($result);
mysqli_close($conn);
Let me know how it works out.
And as tadman said in the comments above "NEVER put $_POST or $_GET data directly into a query, it can be very harmful if someone seeks to exploit your mistake."
Hope it helps!
I have to following situation: I'm making a search page. The search page is populated with MySQL select query selectboxes. Therefor the name of the checkboxes are like name="name[]".
To show you what I'm doing, I'll include a picture:
So if I were to check 1 Availability - like Week - the query will work perfectly. But if I choose 2 Availabilities, only the models with BOTH availabilites show instead of every model that has one of both availabilities.
Here is my code:
HTML:
$return2 = $tafel->query("SELECT DISTINCT whenpossible FROM models where arttype LIKE 'Model%'");
while($row1 = $return2->fetch(PDO::FETCH_ASSOC)){
$whenp = $row1['whenpossible'];
<input type="checkbox" name="when[]" value="<?= $whenp ?>"><span class="box2"><?= $whenp ?></span>
PHP:
if (!empty($_POST['gender'])) {
$genders = $_POST['gender'];
$gender = implode(",",$genders);
} else {
$gender = "%";
}
$select = $tafel->prepare("SELECT * FROM models
WHERE whenpossible LIKE :when");
$select->bindParam(':when', $when, PDO::PARAM_STR);
$select->execute();
Does anyone have an idea how to fix this so that I can choose either 1 or multiple options?
Thank you all very much!
In code you build incorrect SQL command.
For your example SQL is
SELECT * FROM table WHERE field LIKE '%value1,%value2'
This is wrong code. Correct code can be
SELECT * FROM table WHERE field LIKE '%value1' OR field LIKE '%value2'
You should rewrite your code for build correct SQL
For those who are interested or facing the same problem, here is the answer:
In case IN or FIND_IN_SET aren't working for you, you can try this.
Implode your value like so:
if (!empty($_POST['VALUE'])) {
$value = $_POST['VALUE'];
$valueimplode = implode('|', $value)
} else {
$value = 'somethingelse'
}
| is very important for the SQL function. It acts like OR.
SQL as followed:
$query = $db->prepare("SELECT * FROM table WHERE column REGEXP(:valueimplode)");
$query->bindParam(':value', $valueimplode, PDO::PARAM_STR);
$query->execute();
You will find all the results that you need.
If you have an empty value, you can do this:
if (!empty($_POST['VALUE'])) {
$value = $_POST['VALUE'];
$valueimplode = implode('|', $value)
} else {
$value = '%' <-- Wildcard, means EVERYTHING!!!
}
Then the SQL like this:
$query = $db->prepare("SELECT * FROM table WHERE (column REGEXP(:valueimplode) OR column LIKE :value)");
$query->bindParam(':value', $valueimplode, PDO::PARAM_STR);
$query->execute();
% doesn't work with REGEXP so it will go to LIKE, which will then select everything in that column. Meaning, it will result everything.
I hope someone has good use for this!
Alright,
I've got a multiple select dropdown on a page called week-select, its selections get passed via ajax to my php page.
I can get the data just fine, but when the query runs it doesn't complete appropriately.
I've got this:
//Deal with Week Array
$weekFilter = $_GET['week']; /*This is fine, if it's 1 week the query works great (weeks are numbered 12-15), but if it is 2 weeks the result is formatted like this 12-13 or 13-14-15 or whichever weeks are selected*/
$weekFilter = str_replace("-",",",$weekFilter); /*This works to make it a comma separated list*/
.../*I deal with other variables here, they work fine*/
if ($weekFilter) {
$sql[] = " WK IN ( ? ) ";
$sqlarr[] = $weekFilter;
}
$query = "SELECT * FROM $tableName";
if (!empty($sql)) {
$query .= ' WHERE ' . implode(' AND ', $sql);
}
$stmt = $DBH->prepare($query);
$stmt->execute($sqlarr);
$finalarray = array();
$count = $stmt->rowCount();
$finalarray['count'] = $count;
if ($count > 0) { //Check to make sure there are results
while ($result = $stmt->fetchAll()) { //If there are results - go through each one and add it to the json
$finalarray['rowdata'] = $result;
} //end While
}else if ($count == 0) { //if there are no results - set the json object to null
$emptyResult = array();
$emptyResult = "null";
$finalarray['rowdata'] = $emptyResult;
} //end if no results
If I just select one week it works great and displays the appropriate data.
If I select multiple options (say weeks 12, 14 and 15) it runs the query but only displays week 12.
When I manually input the query in SQL, how I imagine this query is getting entered - it runs and displays the appropriate data. So if I put SELECT * FROM mytablename WHERE WK IN ( 12, 14, 15 ) it gets exactly what I want.
I can't figure out why my query isn't executing properly here.
Any ideas?
**EDIT: I make the array from the multiple selections a string using javascript on the front end before it is passed to the backend.
Your resulting query with values probably looks like this with a single value in IN:
… WK IN ("12,14,15") …
Either use one placeholder for each atomic value:
if ($weekFilter) {
$values = explode(",", $weekFilter);
$sql[] = " WK IN ( " . implode(",", array_fill(0, count($values), "?")) . " ) ";
$sqlarr = array_merge($sqlarr, $values);
}
Or use FIND_IN_SET instead of IN:
$sql[] = " FIND_IN_SET(WK, ?) ";
I don't think you can bind an array to a singular ? placeholder. Usually you have to put in as many ? values as there are elements in your array.
If your HTML is correct and your week select has name="week[]", then you will get an array back with $_GET['week'];, otherwise without the [] it will only give you 1 value. Then, you're doing a string replace, but it's not a string. Instead, try this:
$weekFilter = implode(',', $_GET['week']);
I'm trying to code an array that displays a certain set of products depending on the gender of the logged in user. The arrays not really the problem but the parts where I'm going to have to check the database then create the conditional statement from the results is the main problem i think.
Here is my code:
<?php
include"config.php" or die "cannot connect to server";
$gender=$_POST['gender'];
$qry ="SELECT * FROM server WHERE gender ='$gender'";
$result = mysql_query($qry);
$productdetails;
$productdetails1["Product1"] = "£8";
$productdetails1["Product2"] = "£6";
$productdetails1["Product3"] = "£5";
$productdetails1["Product4"] = "£6";
$productdetails1["Product5"] = "£4";
$productdetails2["Product6"] = "£8";
$productdetails2["Product7"] = "£6";
$productdetails2["Product8"] = "£5";
$productdetails2["Product9"] = "£6";
$productdetails2["Product10"] = "£4";
if (mysql_num_rows($result) = 1) {
foreach( $productdetails1 as $key => $value){
echo "Product: $key, Price: $value <br />";
}
}
else {
foreach( $productdetails2 as $key => $value) {
echo "Product: $key, Price: $value <br />";
}
}
?>
You if statement is wrong. = is an assignment operator, you should use a comparison operator like == or ===
What happens with the current code?
Some tips:
First try echoing $gender, to make sure it is getting through. It is submitted through post, what happens if nothing is being posted? Where is this coming from? You should try to use get instead. This seems like something you'd give someone a link to therefore post doesn't make sense here. You could always have both, and just get post if it exists otherwise use get otherwise default to 'male' or 'female' depending on your audience.
Next, what is your query outputting? It might be empty at this point if gender is not giving anything back. It seems like you are querying for all rows where gender = whatever was passed, but then your if statement is asking was there anything returned? Then all you are doing is going to the arrays, but you shouldn't be doing that you should be outputting what you got from the DB. Assuming you do actually have products in the table called server you should do something like this:
$products = mysql_query("SELECT * FROM server WHERE gender ='$gender");
while($product = mysql_fetch_array($products)){
echo $product['name'] . " " . $product['price']. " " . $product['gender'];
echo "<br />";
}
On that note. You should really call your table something else, like product not just "server" unless by server you mean a table filled with instances of waiters or computer hardware.