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.
Related
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.
This might be a simple question, but I can't find a definitive answer I can understand. I use PHP loops alot, I'm fairly new to PHP so they are usually simple like so:
<?php
$result = mssql_query("SELECT Price FROM Window_Extras WHERE ExtraID = '4' ");
while ($row = mssql_fetch_array($result)) {
?>
<a title="<?php echo $row['Colour']; ?>"></a>
<?php }?>
Is a really simple example, that doesn't make much sense, but I hope it shows how I use them. The question I wanted to ask was if $row and $result have to be named that for it to work, could they for example be named $priceresult and $pricerow?
This is because sometimes I would like to use multiple queries for a single loop, for example:
<?php
$result = mssql_query("SELECT Price FROM Extras WHERE ExtraID = '4' ");
$colourresult = mssql_query("SELECT ColourID FROM Colours WHERE Type = '8' ");
while ($row = mssql_fetch_array($result, $colourresult)) {
?>
This however didn't work, when I tried to echo out:
<?php echo $row['ColourID']; ?>
Can anyone tell me how I should be approaching this, and if I am at all on the correct track. Sorry if I havn't explained it very well.
To answer your first question:
Yes, you can use any variable name you like for the result and row variables. PHP doesn't care what you call them, and in fact it's perfectly possible to have several of them in use at any given time, in which case they obviously need to have different names.
You then followed up that question by asking why the following code doesn't work:
$result = mssql_query("SELECT Price FROM Extras WHERE ExtraID = '4' ");
$colourresult = mssql_query("SELECT ColourID FROM Colours WHERE Type = '8' ");
while ($row = mssql_fetch_array($result, $colourresult)) {
....
}
The reason for this is that the _fetch_array() function can only work with one set of results at a time. You would need to fetch a separate row array for each of them.
It's not clear what you're trying to do with these two queries, and why you would want to put them into the same loop together in the way you've shown.
I'm going to assume that the two queries are linked in some way that makes it logical for you to use them together like this? Perhaps the Extra item you're loading has a known Colour; ie you know that the Extra item numbered 4 is coloured with the Colour numbered 8?
Typically a program wouldn't be written with this knowledge; it would be part of the data. So in the Extras table, you would have a ColourID field, which would contain the value 8. The program would load the Extras record, see that the ColourID was set, and then load the matching Colours record according to what it saw.
Thus, your code could look something like this:
$result = mssql_query("SELECT Price FROM Extras WHERE ExtraID = '4' ");
while ($row = mssql_fetch_array($result)) {
$colourresult = mssql_query("SELECT ColourID FROM Colours WHERE Type = '".$row['colourID']."' ");
while ($row2 = mssql_fetch_array($result)) {
....
}
}
Inside the inner while loop, you could then access fields from either query, using $row or $row2 respectively (again, you can name these as you see fit).
However, that's not the end of the story, because SQL actually has the ability to merge these two queries into one without needing all that PHP code, using a thing call a SQL JOIN.
Now we can write a more complex query, but go back to having simpler PHP code:
$result = mssql_query("SELECT Extras.Price, Colours.ColourName FROM Extras WHERE ExtraID = '4' INNER JOIN Colours ON Colours.ColourID = Extras.ColourID");
while ($row = mssql_fetch_array($result)) {
....
}
If you're a beginner in PHP and SQL, these concepts are all probably new to you, so I advise trying them out, experimenting with them, and most importantly, reading a few (good quality) tutorials about them before proceeding much further.
Hope that helps. :)
(PS: as I said above, make sure you're reading good tutorials; beware of bad PHP examples and teaching sites -- there's a lot of them out there, teaching poor code and obsolete techniques; make sure you're reading something worthwhile. A good place to start might be http://phpmaster.com/)
This is because mssql_fetch_array can only take one result set. So removing $result and leaving $colourresult should work for you.
See: http://php.net/manual/en/function.mssql-fetch-array.php
Your variables ($...) can be called whatever you want, it's generally better to name them in a way that you can understand, hence most of the examples in the PHP Manual contain variables like $row, $result, $query, etc.
In terms of your database query, you can only pass one query to the mssql_query method. If you have data from different tables that you need to display, you should try and join the tables if possible using SQL rather than looping through multiple result sets.
Okay so the title may be a bit misleading. What I am trying to do is add a favorite system to my site. I have one column for my favorite things and I set it up so after each item ID there is a :. How can I check the string returned from my database (1345:13456:232:524378:324) if it contains 232? If it does I would echo preRend else I would echo insert and insert that ID followed by a :. This is what I have so far:
<?php
session_start();
require_once(".conf.php");
$logged = $_SESSION['logged'];
$user = $_SESSION['user'];
$fwdfav = $_POST['id'];
$query = mysql_query("SELECT * FROM accountController WHERE user='$user'");
if ($logged == 1)
{
while ($row = mysql_fetch_array($query)) {
if ($row['fav-itms'] //This is where I got stuck. How to check if it contains a value.)
{
mysql_query("INSERT INTO accountController ('fav-itms') VALUES ('$fwdfav')");
echo 'inserted';
}
else
{
echo 'preRend';
}
}
}
else
{
echo 'nlog';
}
?>
Thank you so much! I am sure there are a lot of errors here as I am very tired.
The approach you are taking is extremely inefficient and does not take advantage of the fact that you are using a database.
(Btw... I hope this is just example code; you have a giant SQL injection vulnerability in your INSERT query.)
What I would do instead is create a second table that would look something like:
favorites (
id int(11) NOT NULL auto_increment,
user_id int(11),
fav_id int(11)
)
And have each row represent a user-favorite pair. Then you can let MySQL do the heavy lifting of figuring out whether a user has favorited something, e.g.,
SELECT COUNT(*) FROM favorites WHERE user_id = %d AND fav_id = %d;
// Substitute the actual look-up values in using prepared statements
You could also similarly quickly get the actual favorites for a user, etc.
Remember, a database is designed for the explicit purpose of storing and looking up information quickly. PHP is a general-purpose programming language. Where possible, let MySQL do the walking for you.
(This advice is general for a moderately scaled setup. If you need to handle millions of simultaneous users, far more optimization is obviously required, and conventional relational databases might not even be suitable. But I don't get the impression that's where you're at right now.)
You could explode it in array as check, like:
$yourArr = explode(":", $row['fav-itms']);
$checkFor = 232;
if(in_array($checkFor, $yourArr)) {
//it exists
}
else {
//does not exist
}
Did you mean something like this
I know this was posted a while ago but it came up when I did a search.
I have a database storing information for my portfolio, it holds locations for images.
I am working on a page to display the full view of the project. Within the page I need it to check the columns for the images and if any are empty I need it to not display anything.
This is how I've done it.
// connect, select database, query table relevant to page. I have done a query for a specific row.
if($row[columnName1]){
echo '<div> displaying value </div>';
}
if($row[columnName2]){
echo '<div> displaying value </div>';
}
what is happening, if columnName1 in selected row has a value display the value in div else nothing. then on to column 2.
if it is done like this
if(!$row[columnName1]){
//content displayed
}
and the column does not contain a value then what is in between the {} will be ran.
Works the way I needed it to, maybe this will help someone.
I need to grab data from two tables, but I know theres a better, more tidier way to do this. Is it some kind of JOIN i need?
I'll show you my code and you'll see what I mean:
if ($rs[firearm] != "") {
$sql_result2 = mysql_query("SELECT * FROM db_firearms WHERE name='$rs[firearm]'", $db);
$rs2 = mysql_fetch_array($sql_result2);
$sql_result3 = mysql_query("SELECT * FROM items_firearms WHERE player='$id'", $db);
$rs3 = mysql_fetch_array($sql_result3);
if ($rs3[$rs2[shortname]] < 1) {
mysql_query("UPDATE mobsters SET firearm = '' WHERE id ='$id'");
}
}
This question is clear, but your code example has alot of formatting issues and I cannot give you direct answer, based on your example code.
The reason, why your example is unclear, is because.. with what are you going to join the tables? From one table you are selecting by name='$rs[firearm]' and from another by player='$id'. You have to provide the hidden data, like $rs and also $id.
You should definitely read these about mysql join and mysql left join. But I will try to give you an example based on your code, with fixed syntax. (Keep in mind, that I'm no mysql join expert, I did not test this code and also I do not know the joining conditions.) And also, the system structure is unclear.
As I understood, this what your tables do, correct?
mobsters - Users table
items_firearms - Links from users table to items table
db_firearms - Items table
So basically, my example does this: It will have preloaded $rs value, from the users table. It will check, if there is a entry inside the links table and hook the result with them items table. However, if the links table or even the items table can return multiple entries, then this doesn't work and you need to loop your results in much more smarter way.
// I can only assume, that $id is the ID of the player
$id = 2;
// Since I dont know the $rs value, then Im going to make some up
$rs = array(
'id' => 33,
'firearm' => 'famas'
);
if ($rs['firearm']) {
$result = mysql_fetch_array(mysql_query("SELECT ifa.*, dbfa.* FROM `items_firearms` AS `ifa` LEFT JOIN `db_firearms` AS `dbfa` ON `ifa.shortname` = `dbfa.shortname` WHERE `ifa.player` = '$id'"));
if ($result['id']) {
mysql_query("UPDATE `mobsters` SET `firearm` = '' WHERE `id` = '$id'", $db);
}
}
It is pretty clear, that you are new to PHP and mysql.. So I think you should probably edit your question and talk about your higher goal. Briefly mention, what your application are you building..? What are you trying to do with the mysql queries..? Maybe provide the table structure of your mysql tables..? I'm sure, that you will get your questions votes back to normal and also we can help you much better.
NOTES
You have to quote these types of variables: $rs[firearm] -> $rs['firearm']
If you want to check if your $rs['firearm'] equals something, then there is a better way then $rs[firearm] != "". The most simple is if ($rs['firearm']) {echo 'foo';}, but will produce a notice message, when all errors reporting mode. You can use isset() and empty(), but keep in mind, that isset() checks whether the variable has been set.. Meaning, even if its false, then it has been set. empty() reacts to undefined and empty variable the same, without any messages.
Also, "" means NULL, so if you even need to use "", then use NULL instead...much neater way..
I strongly recommend to use mysql class. You can understand the basics behind that idea from this answer. This is gonna make things much more easier for you. Also, mysql class is a must-have when dealing with dynamic applications.
if ($rs3[$rs2[shortname]] < 1) { .. makes no sense.. Do you want to check if the value is empty? Then (simple): if (!$rs3[$rs2[shortname]]) { .. and a very strict standard: if (empty($rs3[$rs2[shortname]])) { ..
Also you have to quote your sql queries, see my examples above.
Is the last mysql query missing $db?
I am trying to input multiple pieces of data through a form and all the data will be separated by (,). I plan to use this data to find the corresponding id for further processing through an sql query.
Below is the code I use.
$key_code = explode(",", $keyword);
//$key_count = count($key_code);
$list = "'". implode("','", $key_code) ."'";
//$row_count = '';
$sql4= "SELECT key_id FROM keyword WHERE key_code IN (".$list.")";
if(!$result4 = mysql_query($sql4, $connect)) {
mysql_close($connect);
$error = true;
}else{
//$i = 0;
while($row = mysql_fetch_array($result4)) {
$keyword_id[] = $row['key_id'];
//$i++;
}
//return $keyword_id;
}
The problem i see is that keyword_id[0] is the only element that contains any data (the data is accurate). Even if I input multiple values through the aforementioned form.
I thought it might be an error in the sql but I echo'ed it and it looks like:
SELECT key_id FROM keyword WHERE key_code IN ('WED','WATER','WASTE')
The values in the brackets are exactly what I inputted.
I even tried to figure out how many rows are being returned by the query and it shows only 1. I assume something is wrong with my query but I cannot figure where.
Any help will be greatly appreciated.
Edit: Alright Solved the problem. Thanks to suggestions made I copied and pasted the $sql_query I had echo'ed on the website into mysql console; which resulted in only 1 row being retrieved. After taking a closer look I realized that there was a whitespace between ' and the second word. I believe the problem starts when I input the key_code as:
WED, WATER, WASTE
Instead inputting it as
WED,WATER,WASTE
fixes the problem. I think I should make it so that it works both ways though.
Anyway, thank you for the help.
I am pretty sure that the query is ok. How many rows do you get with just
SELECT key_id FROM keyword
I think that there is just one line that matches your WHERE.
Check the query directly in the database(with phpmyadmin, or in the mysql console), however this query seems to be working as you may assumed. If it returns only 1 row when you use it directly in the db, then maybe there is only one row in your table wich matches this query.