How to write a dynamic SQL query in PHP? - php

Hello fellow StackOverflowers,
As modifications on my website were needed in result of massive growth and suggestions from the public, I needed to modify my database, which I have already done to adjust it to the visitor suggestions. Right, very confusing so I'll just get to the point:
Current query:
$arow=mysql_fetch_assoc(mysql_query("SELECT * FROM animelist WHERE id = '".$_REQUEST['id']."'"));
$placeholders = array(' ', ',', ':');
$replacements = array('-', '', '');
$title=str_replace($placeholders, $replacements,$arow['name']);
$title=preg_replace("/[^a-zA-Z0-9\s-]/", "", $title);
$link=$title."-".$arow['id'];
$link="Stream-".$title."-Episode-".$row1['episodes_id']."-".$row1['language']."-".$row1['id'];
Initially the part -Episode- was only needed to be named/written as '-Episode-', however to user suggestions and I completely agree, it needs to be dynamic aswell. Lets say (using the terms for reference only) at first the website only had Episodes and not Movies, but now also has Movies. So we want this part to be dynamic aswell. For this we use database information, I have made a column 'type' INT(1) in the table 'items' I suggest 0 to be -Episode- and if value under type is 1 then I suggest it to be -Movie-.
Now the question is how do I correctly implement it in the query? I understand more queries need to be made similar to the one from $title or $row1. this is what I have so far, but it is not complete yet, because I don't know how to:
$link="Stream-".$title."-.$type.-".$row1['episodes_id']."-".$row1['language']."-".$row1['id'];
$type=$arow['type']
Now there should be a code, which I am not sure of how to write correctly, which makes the condition that if type = 0 then echo Episode, elseif type = 1 then echo Movie.
I greatly appreciate the time you took to read this through and hope you can help me out.
Edit:
Assume $row1, is fetched from table named 'videos' and not from 'animelist', however the table 'videos' each video has an 'id' but also has an column named 'anime_id', this anime_id is equal to the 'id' in 'animelist', in short videos id is the post, and anime_id is the category.
More queries need to be written now to balance the game, please help me out, I am stuck.
Thanks in advance,
Inder

$type = ($arow['type']==0) ? "Episode" : "Movie";
or
$type = $arow['type'] ? "Episode" : "Movie";

Related

Laravel 5 eloquent whereIn

Hope anybody can help me, I need to search for items that have category id = x in the database
Example table items
id,cats,name etc...
cats = '1,19' or maybe just '19' or maybe '1,9'
So for this example I need a to search for items that have cats with 9
I tried this but when I search for 9 it also shows 19
$items = Items::where(function($query)use($cat) {
$query->where('cats', 'like', '%,'.$cat->id.'%');
$query->orWhere('cats', 'like', '%'.$cat->id.',%');
$query->orWhere('cats', 'like', '%'.$cat->id.'%');
})->orderBy('updated_at', 'DSC')->get();
I also tried something
$items = Items::whereIn(explode(',', 'cats'), $cat->id)->get();
but it doesn't work
Appreciate any help to find the easiest and shorts way of doing this, regards
It's quite hard to understand what you want to achieve but I'll try. First of all as #particus mentioned the best way is to create pivot table when you don't need to worry about such things.
But the solution if you have list of ids in a columns separated by coma is not storing values like
1,2,3
but always adding , at the beginning and at the end, so it should be in this case:
,1,2,3,
This way, if you have in your table ,19,2,3, and you want to search for value 9, you should use look for ,9, string, for example:
$id = 9;
$items = Items::where('column', LIKE '%,'.$id.',%')->get();
Now for above string no record will be found, but if you have ,9,2,3, or just ,9, the desired record will be found.
Assuming you're using MySQL, you can use the FIND_IN_SET function.
$items = Items::whereRaw("FIND_IN_SET(".$cat->id.", cats)")->orderBy('updated_at', 'DESC')->get();
Please note, this will not use any indexes defined on the cats column. Storing array like data in a field is usually a big red flag. You would benefit by normalizing this out now, rather than trying to work around the current design.

How can i UPDATE a sql field with a variable instead of a field name?

I'm new here (and not english guy, obviously), but I have a problem.
I have a SQL request, it's an UPDATE like the following :
$rep = $bdd->exec("UPDATE z_agenda SET AGENDA_1='$code'WHERE AGENDA_NOM='$agent' AND AGENDA_TYPE='code'");
BUT, and now the fun is incoming, I want to change AGENDA_1 to a variable which can contains AGENDA_1, AGENDA_2, etc. until AGENDA_31.
But it seems SQL doesn't like it.
So, anybody has an idea?
I'm completely stuck right now.
If you want more explanations, I'm here.
Sit, wait, and read some help forum
I'm adding some few code :
"
$mois = $_POST['mois']; (integer)
$debut = $_POST['debut']; (integer : 1-31)
$lettre = $_POST['lettre']; (integer)
$couleur = $_POST['couleur']; (integer)
$agent = $_POST['agent']; (string)
$code = $lettre + $couleur;
$rep = $bdd->exec("UPDATE z_agenda
SET AGENDA_1='$code'
WHERE AGENDA_NOM='$agent'
AND AGENDA_TYPE='code'");
"
my database contain few information columns, and 31 columns for each day. One line/month/user
don't know how manage my database with an other solution.
There's actually quite a lot going on here.
you should consider using prepared statements to prevent SQL injection vulnerabilities;
you should read up on database normalization;
you could expand the string and add the columns dynamically using, for example, a for loop but you don't want to do this!
Having numbered columns is usually a Very Bad Idea. Click the database normalization link for detailed information and thorough guidelines on how to proceed. Your application will get unmaintainable with a database structure like this. You'll be writing 'string building loops' for the rest of your life, whereas problems like the one you're having now have been solved a million times before.
The loop is static just for an example but you can set the inner code into your accordingly
for($i=0;$i<=31;$i++)
{
$agenda_coloumn = 'AGENDA_'.$i;
$rep = $bdd->exec("UPDATE z_agenda SET $agenda_coloumn = '$code' WHERE AGENDA_NOM='$agent' AND AGENDA_TYPE='code'");
}

Need help getting the SQL strings/query right

Here is a snippet of code which most likely clears what I want to achieve, but is written badly, especially the final string/query. Basically I make links based on these strings/query.
$theanimeid = $row1['anime_id'];
$theanimetype = SELECT * FROM animelist WHERE id=".$theanimeid.";
$echothetype = if $theanimetype['type']=1 echo Movie else echo Episode;
The link:
$link="Stream-".$title."-".$echothetype."-".$row1['episodes_id']."-".$row1['language']."-".$row1['id'];
Some clearing up: $row1 is getting data from the table 'videos', but the column 'type' is inside 'categories' therefore first we need to match the anime_id, a column with the same value as the column id of categories to locate the correct data (I think).
After that we need to get the value for column 'type' in that same row, which is either 0 or 1.
If you need extra information I will reply on the spot, as I refresh this page every minute to see if someone answered, I really need help and it is appreciated.
Thanks in advance,
Inder
Do You mean something like that:
$thetype = $theanimetype['type'] == 1 ? 'Movie' : 'Episode';
???
Or maybe doing this in the SQL query:
SELECT *,
CASE type
WHEN 1 THEN 'Movie'
WHEN 0 THEN 'Episode'
END AS animeType
FROM myTable

how to implement the an effective search algorithm when using php and a mysql database?

I'm new to web design, especially backend design so I have a few questions about implementing a search function in PHP. I already set up a MySQL connection but I don't know how to access specific rows in the MySQL table. Also is the similar text function implemented correctly considering I want to return results that are nearly the same as the search term? Right now, I can only return results that are the exact same or it gives "no result." For example, if I search "tex" it would return results containing "text"? I realize that there are a lot of mistakes in my coding and logic, so please help if possible. Event is the name of the row I am trying to access.
$input = $_POST["searchevent"];
while ($events = mysql_fetch_row($Event)) {
$eventname = $events[1];
$eventid = $events[0];
$diff = similar_text($input, $event, $hold)
if ($hold == '100') {
echo $eventname;
break;
else
echo "no result";
}
Thank you.
I've noticed some of the comments mentioned more efficient ways of performing the search than with the "similar text" function, if I were to use the LIKE function, how would it be implemented?
A couple of different ways of doing this:
The faster one (performance wise) is:
select * FROM Table where keyword LIKE '%value%'
The trick in this one is the placement of the % which is a wildcard, saying either search everything that ends or begins with this value.
A more flexible but (slightly) slower one could be the REGEXP function:
Select * FROM Table WHERE keyword REGEXP 'value'
This is using the power of regular expressions, so you could get as elaborate as you wanted with it. However, leaving as above gives you a "poor man's Google" of sorts, allowing the search to be bits and pieces of overall fields.
The sticky part comes in if you're trying to search names. For example, either would find the name "smith" if you searched SMI. However, neither would find "Jon Smith" if there was a first and last name field separated. So, you'd have to do some concatenation for the search to find either Jon OR Smith OR Jon Smith OR Smith, Jon. It can really snowball from there.
Of course, if you're doing some sort of advanced search, you'll have to condition your query accordingly. So, for instance, if you wanted to search first, last, address, then your query would have to test for each:
SELECT * FROM table WHERE first LIKE '%value%' OR last LIKE '%value%' OR address LIKE '%value'
Look at below example :
$word2compare = "stupid";
$words = array(
'stupid',
'stu and pid',
'hello',
'foobar',
'stpid',
'upid',
'stuuupid',
'sstuuupiiid',
);
while(list($id, $str) = each($words)){
similar_text($str, $word2compare, $percent);
if($percent > 90) // Change percentage value to 80,70,60 and see changes
print "Comparing '$word2compare' with '$str': ";
}
You can check with $percent parameter for how strong match you want to apply.

how to updated the keywords from database

hi i have stored 1000 keywords in my database . if i search any keyword(with in my database) my site title must come Like a AIRPORT NETWORKS this title i want . this is for search engine box. how can i do with sql queries i used that below query for displayed my site title.
$ConvertedResultArray = explode('<div id="resultsDiv">', $ConvertedResult);
$V1 = $ConvertedResultArray[0];
$V2 = $ConvertedResultArray[1];
$SponsoredContent = '';
if(strtolower($SearchQuery) == 'taxi')
{
$SponsoredContent = '<br />AIRPORTS<br />NETWORKS';
}
$ConvertedResult = "$V1$SponsoredContent$V2";
i have a only one table named keywords
if i entered that key "taxi" in search box That title comes infront of the page AIRPORTNETWORKS as like that if i entered in the whole 1000 words which it is stored in database it must be come .
how can i do that what sql query i have to use.is it possible. please help me if any one have an idea thanks in advance
I realise this not the answer, but here is something to get you started
SELECT *
FROM Keywords
WHERE Name LIKE "%AIRPORT%"
You need to use AJAX for that. I guess you are speaking about auto complete. if is tat you are talking about do the following steps.
1. use the query given by PerformanceDBA
2. update the textbox value with the first row of query result by triggering textbox onkeyup() event.
If this is not what you want please rephrase your question so tat others can understand..

Categories