I've created some if / else statements to get name from url like http://website.com/page.php?name=Love It seems to look good and trows no errors, but for some reason I am not getting data from the database. Basically it gets 'name' from url and checks of it is one of allowed categories, if yes it selects article from database that has st_category = to what user selected.
But than again for some reason it doesn't work.
Here is a snippet of code that I think causes the problem.
<?php
$category = preg_replace('#[^a-z]#i', '', $_GET["name"]);
if ($category = "Love") {
$st_category = "Love";
}
else if ($category = "Work") {
$st_category = "Work";
}
else if ($category = "Money") {
$st_category = "Money";
}
else if ($category = "Kids") {
$st_category = "Kids";
}
else if ($category = "Health") {
$st_category = "Health";
}
else if ($category = "Friends") {
$st_category = "Friends";
}
else if ($category = "Education") {
$st_category = "Education";
}
else if ($category = "Other") {
$st_category = "Other";
}
else {
header("Location: http://www.inelmo.com/");
exit;
}
$sql = mysql_query("SELECT * FROM stories WHERE showing = 1 AND st_category = '$st_category' ORDER BY st_date DESC LIMIT 10") or die (mysql_error("There was an error in connection"));
//And another stuff here to display article
?>
= is not the same as ==. In your if statements you are doing assignments not comparison.
if ($category = "Love") should be changed to if ($category == "Love") (or to if ($category === "Love") and so on...
That could be tidied up to much less code, much more maintainable, using in_array().
$categories = array(
'Love',
'Work',
'Money',
'Kids',
'Health',
'Friends',
'Education',
'Other'
);
$category = preg_replace('#[^a-z]#i', '', $_GET["name"]);
if (!in_array($category, $categories)) {
header("Location: http://www.inelmo.com/");
exit;
}
$sql = mysql_query("SELECT * FROM stories WHERE showing = 1 AND st_category = '$category' ORDER BY st_date DESC LIMIT 10") or die (mysql_error("There was an error in connection"));
And this also fixes the problem that #matino rightly pointed out, which is that you were assigning and not comparing.
You have used a single "=" in every if.
The correct syntax is with "==" or "===", like:
<?php
$category = preg_replace('#[^a-z]#i', '', $_GET["name"]);
if ($category == "Love") {
$st_category = "Love";
}
else if ($category == "Work") {
$st_category = "Work";
}
...
?>
Please use double equal sign like
if($foo=="foo1")
In your if-statements you used the = while you had to used the == sign. With the = you assign a value to a variable on the left, like $sum = 1 + 2; you wanted is $sum==3.
Related
I have a problem code beneath this line does not work! How can I let this work? where ... orWhere orWhere does filter but cumulates the queries. where ... where does not provide any result. Can someone help me?
$artworks = Artwork::where('category_id', $category)
->where('style_id', $style)
->where('technic_id', $technic)
->where('orientation', $orientation)
->get();
Here is the full code:
if (request()->category_id) {
$category = request()->category_id;
} else {
$category = 0;
}
if (request()->style_id) {
$style = request()->style_id;
} else {
$style = 0;
}
if (request()->technic_id) {
$technic = request()->technic_id;
} else {
$technic = 0;
}
if (request()->orientation_id == 'vertical') {
$orientation = 'vertical';
} else if (request()->orientation_id == 'horizontal') {
$orientation = 'horizontal';
} else {
$orientation = 0;
}
$artists = Artist::get();
$artworks = Artwork::where('category_id', $category)
->where('style_id', $style)
->where('technic_id', $technic)
->where('orientation', $orientation)
->get();
return view('frontend.index', compact('artworks', 'artists'));
I think you want to use OR Condition and you are mistaking it with double where. Please look below to understand properly
If you want AND condition in your query then the double where are used but if you want OR condition then you have to use orWhere
Examples:
AND condition
Query::where(condition)->where(condition)->get();
OR Conditon
Query::where(condition)->orWhere(condition)->get();
If you expect all of your variables to be set
Your query variables category_id, style_id, orientation_id & technic_id are being defaulted to 0 if they are not true.
Your query is fine, but you may not have the data you think you do.
Run the following at the top of this function:
print_r($request->all());
exit;
If all of your variables are optional
very procedural, basic way to achieve this:
$artists = Artist::get();
$artworks = Artwork::where('id', '>', 0);
$category_id = request()->input('category_id');
if ($category_id != '') {
$artworks->where('category_id', request()->category_id);
}
$style_id = request()->input('style_id');
if ($style_id != '') {
$artworks->where('style_id', request()->style_id);
}
$technic_id = request()->input('technic_id');
if ($technic_id != '') {
$artworks->where('technic_id', request()->technic_id);
}
$orientation_id = request()->input('orientation_id');
if ($orientation_id != '') {
$artworks->where('orientation_id', request()->orientation_id);
}
$artworks->get();
return view('frontend.index', compact('artworks', 'artists'));
PHP
I have having problem with my case, statements. I am trying to search books between 2 years but i am having trouble i can search one year using this code perfectly but trying for two is not working. I do understand i am more than likely going about this the wrong way to get desired result but any help would be greatly appreciated.
Also i am getting ERROR Notice: Undefined variable: Year1 for the else part of the last case. Thanks.
If Year and Year1 have a value it should look bettwen the two years if Year just has a value just find books in that year.
<?php
include 'header.php';
include 'searchscript.php';
$sql = "SELECT DISTINCT bk.title AS Title, bk.bookid AS BookID, bk.year AS Year, bk.publisher AS Publisher, aut.authorname AS Author
FROM book bk
JOIN book_category bk_cat
ON bk_cat.book_id = bk.bookid
JOIN categories cat
ON cat.id = bk_cat.category_id
JOIN books_authors bk_aut
ON bk_aut.book_id = bk.bookid
JOIN authors aut
ON aut.id = bk_aut.author_id";
if(isset($_GET['searchInput'])){
$input = $_GET['searchInput'];
$input = preg_replace('/[^A-Za-z0-9]/', '', $input);
}
if (isset($input)){
$getters = array();
$queries = array();
foreach ($_GET as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (!empty($temp)){
if (!in_array($key, $getters)){
$getters[$key] = $value;
}
}
}
if (!empty($getters)) {
foreach($getters as $key => $value){
${$key} = $value;
switch ($key) {
case 'searchInput':
array_push($queries,"(bk.title LIKE '%$searchInput%'
|| bk.description LIKE '%$searchInput%' || bk.isbn LIKE '%$searchInput%'
|| bk.keywords LIKE '%$searchInput%' || aut.authorname LIKE '%$searchInput%')");
break;
case 'srch_publisher':
array_push($queries, "(bk.publisher = '$srch_publisher')");
break;
case 'srch_author':
array_push($queries, "(bk_aut.author_id = '$srch_author')");
break;
case 'srch_category':
array_push($queries, "(bk_cat.category_id = '$srch_category')");
break;
**case 'Year' && 'Year1':
if("$Year1" ==""){
array_push($queries, "(bk.year = '$Year')");
} else {
array_push($queries, "(bk.year BETWEEN '$Year' AND '$Year1')");
}
break;**
}
}
}
if(!empty($queries)){
$sql .= " WHERE ";
$i = 1;
foreach ($queries as $query) {
if($i < count($queries)){
$sql .= $query." AND ";
} else {
$sql .= $query;
}
$i++;
}
}
$sql .= " GROUP BY bk.title ORDER BY bk.title ASC";
}else{
$sql .= " GROUP BY bk.title ORDER BY bk.title ASC";
}
$rs = mysql_query($sql) or die(mysql_error());
$rows = mysql_fetch_assoc($rs);
$tot_rows = mysql_num_rows($rs);
?>
Your code:
foreach($getters as $key => $value)
switch ($key) {
case 'Year' && 'Year1':
if("$Year1" ==""){
array_push($queries, "(bk.year = '$Year')");
} else {
array_push($queries, "(bk.year BETWEEN '$Year' AND '$Year1')");
}
break;
}
}
shows two issues:
case statements don't work this way. You can't use boolean operators the same way here like when using an if() statement. (see manual)
You cannot expect the iterator variable $key in foreach($getters as $key=>$value) hold both values at the same time, which you imply by saying 'Year' && 'Year1'!
To solve those issues, you could do something like:
foreach($getters as $key => $value)
switch ($key) {
case 'Year':
if($getters["Year1"] ==""){
array_push($queries, "(bk.year = '{$value}')");
} else {
array_push($queries, "(bk.year BETWEEN '{$value}' AND '{$getters['Year1']}')");
}
break;
}
}
In this case the block is executed when the foreach($getters) hits the key 'Year'. The if statement now handles 'Year1' correctly by accessing the value in the array directly instead of looking at the iterator variables.
Adding as a seperate answer
Your code shows severe security flaws which should be fixed!
Excerpt:
// 1. happily copies all GET variables into an array
foreach ($_GET as $key => $value) {
$getters[$key] = $value;
}
if (!empty($getters)) {
foreach($getters as $key => $value) {
// 2. happily assings any PHP variable in the current scope to almost
// unfiltered input from a malicious user
${$key} = $value;
}
}
// any variable read after this point can not be trusted because
// the value might be manipulated by a malicious user!
Also, SQL injection all over the place! i won't repeat that SQL injection story again. See related questions!
I have a setup where it favourites and retweets a specific tweet. For some reason, the code works for the favourites however retweets do not. Can anyone see the issue?
$method = 'statuses/retweet/'.$url[3];
$amt = "26";
$sub = rand(1,3);
$amt1 = $amt-$sub;
if($_POST['favorite'] == "true" || $_POST['favorite'] == "1"){
for ($x1=1; $x1<=$amt1; $x1++)
{
$content = $connection[$x1]->post('favorites/create', array('id' => $url[3]));
}
}
if($_POST['retweet'] == "true" || $_POST['retweet'] == "1"){
for ($x2=1; $x2<=$amt; $x2++)
{
$content = twitteroauth_row('statuses/retweet/'.$url[3], $connection[$x2]->post($method), $connection[$x2]->http_code);
}
}
have you tried declaring
$amt = 26
instead of
$amt="26"
EDIT:
for ($x2=1; $x2<=amt; $x2++)
{
$content = twitteroauth_row('statuses/retweet/'.$url[3], $connection[$x2]->post($method), $connection[$x2]->http_code);
}
you have used amt instead of $amt in the loop condition
So I have a query that I am returning all of the items into a mysql_fetch_array. Now, I know I could write another query and just select the items I need into a seperate query but, is there a way to just filter from the larger query what I want dependent on $_GET?
So, in english the user comes from a hyperlink that has ?id=1 and I peform a while that gets the all the values but, only display the $_GET['id'] items in a list
<?php //give ma all values but only echo out list of the $_GET['id'] in the url
while ($row = mysql_fetch_array($result) {
$id = $rowvideo["id"];
$title = $rowvideo["title"];
$length = $rowvideo["length"];
}
echo("<li><a href='#'>". $title." " .$length. "</a></li>");
?>
Hope this makes sense. Thank you all.
If you do not want a second query to get just what you need, a simple-if-statement in your loop should work:
<?php
$getId = isset($_GET['id']) ? $_GET['id'] : false;
//give ma all values but only echo out list of the $_GET['id'] in the url
while ($row = mysql_fetch_array($result)) {
$id = $row["id"];
$title = $row["title"];
$length = $row["length"];
if ($id == $getId) {
echo("<li><a href='#'>". $title." " .$length. "</a></li>");
}
}
?>
Note that I declared $getId outside of the loop to prevent having to use isset() during every iteration. If you don't verify if it's set and attempt to use it it will throw an undefined index warning - assuming you have error_reporting turned on (with that level enabled).
Alternatively, you could use PHP's array_filter() on the data after you've parsed it all:
$results = array();
while ($row = mysql_fetch_array($result)) $results[] = $row;
if (isset($_GET['id'])) {
$filtered = array_filter($results, function($element) use ($_GET['id']) { return ($element['id'] == $_GET['id']); });
$results = $filtered;
}
foreach ($results as $result) {
echo("<li><a href='#'>". $result['title']." " .$result['length']. "</a></li>");
}
My personal opinion would be to be more efficient and write the second query though, assuming of course you don't actually need all of the results when an id is specified. It would be as simple as:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$query = 'SELECT id, title, length FROM table WHERE id=' . (int)$_GET['id'];
} else {
$query = 'SELECT id, title, length FROM table';
}
// your existing code as-is
A little more clarity here:
This will allow the filter by id in the url by specifying id=xxx, IF xxx is an integer that is positive. So id of 'bob' or -1 will not filter the results still giving all results
$filter=false;
if(isset($_GET['id']))
{
$filter_id=intval($_GET['id']);
if($id>0) $filter=true;
}
while($row = mysql_fetch_array($result))
{
if( (!$filter) || ( ($filter) && ($filter_id==$row['id']) ) )
{
$id = $row["id"];
$title = $row["title"];
$length = $row["length"];
// do other stuff here
}
}
I also changed $rowvideo to $row as this is the array you used to fetch the results.
<?php //give ma all values but only echo out list of the $_GET['id'] in the url
while ($row = mysql_fetch_array($result)) {
$id = $rowvideo["id"];
$title = $rowvideo["title"];
$length = $rowvideo["length"];
if ($id == $_GET['id']) { // or even ===
echo("<li><a href='#'>". $title." " .$length. "</a></li>");
}
}
?>
Good day guys,
I've made a sweet favorites function with php mysql and ajax, and its working great. Now I want to show 'favorite' when favorite = 0 and show 'unfavorite' when favorite = 1
if ($favorites == 0) {
$favorite = 'Favorite';
}
if ($favorites == 1) {
$unfavorite = 'unFavorite';
}
and echo it in the row as :
<div id="favorites">' .($favorite). ' ' .($unfavorite). '</div>
The problem is: when favorite = 0, both $favorite and $unfavorite are being shown. When favorite = 1 only $unfavorite is being shown correctly. Of course it should be $favorite OR $unfavorite. I assume the problem is clear and simple to you, please assist :)
Thanks in advance
It's easier to use just one variable:
$text = ''
if ($favorites == 0) {
$text = 'Favorite';
} else {
$text = 'unFavorite';
}
...
echo $text;
If you want to check $favorite, you are using the wrong variable in your control statement. Also, it is better coding practice to use elseif rather than if for that second if. One more thing: it's easier to manage one resulting variable.
$output = "";
if ($favorite == 0) {
$output = 'Favorite';
}
elseif ($favorite == 1) {
$output = 'unFavorite';
}
...
echo $output; // Or whatever you want to do with your output
Is $favorites an integer?
Anyway try using three equal signs (===) or else instead of the second if:
if ( $favorites === 0 )
{
// ...
}
else // or if ($favorites === 1)
{
// ...
}
You're making a toggle, so you only need one variable:
if(empty($favourites)){
$fav_toggle = 'Favorite';
} else {
$fav_toggle = 'unFavorite';
}
echo $fav_toggle;
Same code is working on me if I assigned $favorites = 0; or $favorites = 1;
You can also use if else
$favorites = 1;
if ($favorites == 0) {
$favorite = 'Favorite';
}
else if ($favorites == 1) {
$unfavorite = 'unFavorite';
}