I am using fckeditor class in my php code.
Ok , when I search or enter p in search box it will print all the records included in specific table('p' is the problem of fckeditor).
I have one chapter combo and one text box.before when i search any keyword,it did work but not now. Yesterday I posted this question, I got an answer but problem is what when I search any keyword, it is unable to show record related to that question. it only shows chapter related question after entering that chapter field.
To further explain, if I enter in text field 'p' and 1 in dropdown then it will print all questions in chapter number 1, but when I enter any keyword it did not work.
My code is:
<?php
if (isset($_POST['submit'])) {
if (empty($_POST['fname'])) {
die ("<script type='text/javascript' > alert('PLEASE ENTER KEYWORD...!!!');</script>");
} else {
?>..................................
<?php
include("conn.php");
$name = $_POST['fname'];
$name2 = $_POST['chapter'];
/*This query searches all records with duplicate entry....*/
//$sql="SELECT * FROM $user WHERE question like '%".$name."%' and
//Chapter like'%".$name2."%' ";
/*This query searches all records without duplicate entry....*/
$sql = "SELECT * FROM $user WHERE question like '%" . $name . "%' and
Chapter like '$name2'";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
?>
I have again one problem in it.When i write my 1 st query commented on duplicate entry, if I enter chapter no 1 then it will print 1,11,21 chapters records,it will work for every task.i mean this query is able to search keyword wise record or 'p' for all records but one 1,11,21,12 is a problem.and in my second query ,it will only print chapter-wise record as i said earlier.So please help me for this question.
I'm really struggling to understand your question so I'll start with some general advice that you should have heard here before:
Please try to use mysqli or PDO
Your code is wide open to sql injection attacks. You should use prepared statements or at the very least use mysqli_real_escape_string on all user input.
There is no need to reassign your posted variables to $name or $name2.
don't forget that mysql table names are case sensitive. It may be wise to keep your case usage consistent as it will help future code writing.
Your sql query, translated into English says:
Find all the columns from the table named in the variable $user in which BOTH the column chapter is exactly equal to the variable $name2 and the column question has the text of $name1 as a continuous string, case insenstive, somewhere in its text.
If that is what you want, that is what you will get.
I wonder if your problem is the lack of % either side of your chapter query?
Consider:
$sql="SELECT * FROM $user WHERE question LIKE '%$name%' AND Chapter LIKE '%$name2%'";
or
$sql="SELECT * FROM $user WHERE question LIKE '%$name%' AND Chapter = '$name2'";
If that achieves the desired result then you can move on and remove the sql injection vulnerabilities.
If you provide some sample data, perhaps a fiddle and some examples of desired outputs, I am sure the community here will be happy to help. Those work well in any language.
Related
a quick question :), I wrote this because someone said that my codes are vulnerable to mysql injection and it is a requirement to learn prepared statement in web programming to avoid any user putting malicious data or statement into the database..What I have is a search function that search data from the database, if you type in a string like this "torres" then i search for torres but if you just put "tor" it won't search for datas that contain "tor" in their name..I don't know the correct format while using prepared statement, If you have advice I'm very happy to take it :)
<?php
if (isset($_POST['search'])) {
$box = $_POST['box'];
$box = preg_replace("#[^0-9a-z]#i","",$box);
$grade =$_POST['grade'];
$section = $_POST['section'];
$strand = $_POST['strand'];
$sql = "SELECT * FROM student WHERE fname LIKE ? or lname LIKE ? or mname LIKE ? or grade = ? or track = ? or section = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)){
echo "SQL FAILED";
}
else {
//bind the parameter place holder
mysqli_stmt_bind_param($stmt, "ssssss",$box, $box, $box, $grade, $strand, $section);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['lname']."</td>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$row['mname']."</td>";
echo "<td>".$row['grade']."</td>";
echo "<td>".$row['track']."</td>";
echo "<td>".$row['section']."</td>";
echo "</tr>";
}
}
As requested:
#ArtisticPhoenix I clearly prefer the king's way [compound full text index]. This should be your primary answer showing an example/explaination.
First make a full text index that includes all three fields (this is in PHPmyAdmin, it's a bit easier to explain with an image)
Then do a query like this:
#PDO version SELECT * FROM `temp` WHERE MATCH(fname,mname,lname)AGAINST(:fullname IN BOOLEAN MODE)
#MySqli version SELECT * FROM `temp` WHERE MATCH(fname,mname,lname)AGAINST(? IN BOOLEAN MODE)
SELECT * FROM `temp` WHERE MATCH(fname,mname,lname)AGAINST('edward' IN BOOLEAN MODE)
It seems simple but there are some things with full text to be aware of Min char count which is 3 (I think) anything smaller than that is not searched on. This can be changed but it requires repairing the DB and restarting MySql.
Stop words, these are things like and, the etc. These can also be configured in my.cnf.
Punctuation is ignored. This might not seem a big deal on names but think of hyphenated last names.
Usually I reduce the word min to 2 and point the stopwords to an empty file (disabling them).
The match against syntax is quite different, it's pretty powerful but it's not really used outside of full text. An example is: this is the wild card * and you use '"' double quotes for exact phrase match '"match exactly"', and + is logical AND, such as word+ word+ (default is or), - is do not match this etc... If I remember right, I used it a bunch a few years ago but haven't had to use it recently.
For example doing "begins with" on a partial word
SELECT * FROM `temp` WHERE MATCH(fname,mname,lname)AGAINST('edwar*' IN BOOLEAN MODE)
Same result matches one row. The obvious benefit is searching all 3 fields at the same time, but the full text syntax itself can be quite useful too.
For more information:
https://dev.mysql.com/doc/refman/8.0/en/fulltext-boolean.html
PS. I might add that using OR in a query can really kill performance, I've went as far as to replace simple OR with a UNION because of how bad the performance is on a large table. Logically the DB optimizer has to rescan the entire table for an OR, unlike AND where it can use the result of the previous expression to reduce the next expressions data set (or that is how I understand it). I can say the performance difference is very noticeable using OR vs UNION.
This is true for a compound full text index vs doing OR on each field separately. By default fulltext is faster, but it's even faster this way.
To fix your current query (for the sake of completeness)
You need whats known as an exclusive or, like this:
SELECT * FROM student WHERE ( fname LIKE ? OR lname LIKE ? OR mname LIKE ? ) AND grade = ? AND track = ? AND section = ?
What this does is group the OR's together so that they evalute as one expression to the "next level up" ( outside the parenthesis ). Basically order of operations. In English, you would have to match at least 1 of these columns fname, lname, mname AND you would also have to match all of the rest of the columns as well, to get a result returned for any given row.
If you use all OR (as you are now) and any single field matches, then the query comes back as true with matches. Which is the behaviour you are experiencing now.
If you simply change everything outside of the name fields to AND, Basically remove the parenthesis
Like this:
#this is wrong don't use it.
SELECT * FROM student WHERE fname LIKE ? OR lname LIKE ? OR mname LIKE ? AND grade = ? AND track = ? AND section = ?
Then you have to match this way.
(grade AND track AND section AND mname) OR lname OR fname
So if the last or first name match you get results regardless of any of the other fields. But the mname field you would find has to match with all the rest of the fields to get a result (but you would not likely notice this). Because, it would seem that the query works how you want but only when the mname is a match.
I hope that makes sense. It may be helpful to think of the WHERE clause as an IF condition the same logic rules apply.
Cheers!
This question already has answers here:
fetch single record using PHP PDO and return result
(2 answers)
Closed 6 years ago.
I have not made the change from MySQL_ to PDO until today. Needless to say, the migration is more than a simple headache. So, I need a bit of help. I tried all the search terms I could before registering and asking this question.
My Problem
User types a numeric code into the search box, translates it to
.php?code=term
Script selects all columns from the database where the code is the
code term searched for.
PHP will Echo the results
My Code
if (isset($_GET["code"])) {
//IF USER SEARCHES FOR CODE, RUN THIS. ELSE SKIP.
$crimecode = $_GET["code"];
$crcode = $link->prepare("SELECT * FROM crimecodes WHERE code = :code");
$crcode->bindParam(':code', $crimecode);
$crcode->execute();
$coderesult = $crcode->fetchAll();
echo "<h4>CODE:</h4>";
echo $crimecode;
echo "<br /><h4>DEFINITION:</h4>";
echo $coderesult;
die();
}
Before, it was simple. All I had to do was:
$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);
echo $fcode['definition'];
But, the ever evolving world has decided to fix something that wasn't broken so now the whole prior code is pointless and you gotta learn something new. Any help is appreciated to get this to work.
Right now, the above PDO code returns definition: ARRAY.
Like literally, the $coderesult prints Array.
The fetchAll() option returns an array containing all of the result set rows (http://php.net/manual/pt_BR/pdostatement.fetchall.php).
$coderesult prints Array because it's actually an array. If you do var_dump($coderesult) you'll see it.
I suppose that you are trying to get one row only. If that's the case, add this line after $coderesult = $crcode->fetchAll();:
$coderesult = $coderesult[0];
Then you can
echo $coderesult['definition'];
If you're trying to get more than one row, you need to use foreach to loop through the array.
I suggest you read the php manual for PDO Class or mysqli, wherever you prefer. There's a lot more options than mysql_.
Also, I think it's worth to mention that your previous code
$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);
echo $fcode['definition'];
it's vulnerable to SQL Injection.
been googling for hours and I'm quite new to this.
I have two identical tables in one MySQL database:
One named "users" and one named "keys".
They are identical for testing purposes.
When I query "users" I get a response, when I query "keys" I get nothing.
Querying users I get the expected response:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT name
FROM users
WHERE can_share = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
Querying keys I get nothing:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT name
FROM keys
WHERE can_share = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
I guess there must be some basic understanding of databases that has slipped by me, but still, after hours of searching I can't figure it out. Maybe I'm becoming retarded.
I think that might be due to table name being 'keys'.
Have a look here:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
You have to understand while designing your tables and naming the attributes that some words are reserved by MySQL itself.
So, if you name your table 'WHERE' you will have troubles in usual query. Why?
'SELECT * FROM WHERE'
Such a query obviously doesn't work, as it will ask you to provide table name.
Now, when you change format situation also changes:
'SELECT * FROM `WHERE`'
As you can see I added some backwards commas. In MySQL they are used to denote names of tables or fields. If you use them - the server processes and reads your query correctly.
So, that's why your edited query worked fine in the end.
Thanks to enabeling debugging, I got this message:
mysql_result() expects parameter 1 to be resource, boolean given in
...
And figured out that I had to query "keys" like this:
<?php
require('../db/connect.php');
$query = mysql_query("
SELECT `name`
FROM `keys`
WHERE `can_share` = '".$_POST['URLkey']."'
");
echo mysql_result($query, 0);
?>
Now it works, but I still don't understand why only one of the tables needed that formatting. And I have learned that I should rewrite the whole thing to not be vulnerable to SQL injection attacks. ...
EDIT: It seems like the words "key" and "keys" and some more are reserved by MySQL, so to use them, they have to be formatted like that.
I currently have this table.
Names
Two fields, ID and Names. Example data would be 1 | Harry.
Now what i am planning on doing is that if someone enters in something like Henry in my form, it will search my database for a result that begins with "H" Then if their are multiple results, it will see if there are any results that are "He" if their isn't it will fallback to the previous result from "H".
The only thing i can think of doing is this,
$inputted_name = "Henry";
$query = mysql_query("SELECT `name` FROM `names`");
while($row = mysql_fetch_array($query)){
$stored_name = $row['name'];
if($stored_name[0] == $inputted_name[0]){
if($stored_name[1] == $inputted_name[1]){
$result = $stored_name;
break;
} else {
// continue looking but then return the first result that matched one letter?
}
}
}
Now i am sure this can't be the best way to do it. Would it be possible in a query? I'm just really not sure where to look for a sensible answer for this one.
change
mysql_query("SELECT name FROM names");
to
mysql_query("SELECT name FROM names WHERE NAME='".$inputted_name."'");
and check you have more than one answer.
Note this is a bad way to do it if your name comes from a non controlled source, such as a web page, as it would allow a SQL injection, and then you would need parameters, but for your example it would work.
Edit: Now I read your question again, yes, you would need parameters or escaping such as:
$name = mysql_real_escape_string($inputted_name);
mysql_query("SELECT `name` FROM `names` WHERE NAME='".$=name."'");
Also, don't try and do in code what the database can do easily (like search for characters). Your code is almost always going to be worse than the database for doing a search, leave it to the 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..