how do I loop inside a loop with PHP in MySQL? - php

table persons
name | details
------------------
mathew| tax,home,car,insurance
john | job,tax,employ
neil | tax,home,car,job
yancy | consultant,rent,family
lucy | home,car,insurance
I want loop through this table and search with details then saved result to another table called persons1
name | names
------------------
mathew| neil,lucy,john
neil | mathew,lucy,john
john | mathew,lucy,neil
so far I coded something like below but not working
mysql_connect("localhost", "root", "pass");
mysql_select_db("database");
$query = "SELECT * FROM persons";
$result = mysql_query($query);
while($r = mysql_fetch_array($result))
{
$exp = explode(",",$r["details"]);
$sql = mysql_query('SELECT * FROM persons WHERE MATCH (tags) AGAINST ("+$exp[0]" "+$exp[1]" "+$exp[2]" IN BOOLEAN MODE)');
$result = array();
while($row = mysql_fetch_assoc($sql))
{
array_push($result,$row['name']);
$name = implode(",",$result);
mysql_query("INSERT INTO person_new (name,names) VALUES (\"".$r["name"]."\", \"".$name."\")");
}
}
IT is very sad that nobody can give an answer to my question about my code. instead of looking into my design I request you to look into my code and tell me where I made a mistake..i am doing something different than what it sees and this is why I request you to check my code...

Your problem would be better solved via database normalization.
Storing data like tax,home,car,insurance in a single column, then parsing it to search is a Very Bad Idea.

First of all, it'd be nice if you'd tell us what doesn't work.
Having said that, I suspect (at least one of) your error(s) is here:
'SELECT * FROM persons WHERE MATCH (tags) AGAINST ("+$exp[0]" "+$exp[1]" "+$exp[2]" IN BOOLEAN MODE)'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This will literally give you the query AGAINST ("+$exp[0]" "+$exp[1]" "+$exp[2]" IN BOOLEAN MODE), which is likely not what you want. You need to concatenate the string, or use a double quoted string:
'SELECT ... AGAINST ("+' . $exp[0] . '" "+' . $exp[1] . '" "+' . $exp[2] . '" IN BOOLEAN MODE)'
or
"SELECT ... AGAINST (\"+$exp[0]\" \"+$exp[1]\" \"+$exp[2]\" IN BOOLEAN MODE)"
I'm with #Dolph though, this is not a good database structure, and if you're going to redesign it later anyway (careful with saying "later", that usually never happens), you should just do it now.

Related

Failing to search for full names while querying mysql with php

First time asking on SO. I currently am trying to search a database where the first and last names are seperate. Example:
player_id | first_name | last_name
191 John Smith
192 Larry Citizen
193 Benjamin Example
I am trying to allow users to search this list using a full name only. I currently have the following code once the user hits submit, it calls usersearch.php.
session_start();
include '../con.php';
$player = $_POST['name'];
$sql = "SELECT * FROM characters WHERE (concat(first_name,' ',last_name)) = ($player)";
$result = mysqli_query($conn, $sql);
if (!$row = mysqli_fetch_assoc($result)) {
echo "Found no-one with the name $player. <a href='../search.php'>Try Again?</a>";
} else {
$_SESSION['selplate'] = $row['plate'];
$_SESSION['selname'] = $row['first_name, last_name'];
header("Location: ../profile.php?player=$player");
}
No matter the query it will not find users and always returns "Found no-one with the name $player. Try again?"
This was supposed to be the easy part of this project and I am pulling my hair out.
I have spent over an hour searching SO and Google to no avail so it must be my code? afaik it should work.
you need qoutes ' ' around player because its a text and also concatinated.
if you search Johnsmith it will return nothing
if you search John Smith it will give you result, because in your concat you are adding a space between words
"SELECT * FROM characters WHERE concat(first_name,' ',last_name) =('".$player."')"
I would change it to a fulltext index on both first and last name, change the word min on full text indexes. then I would search using ( some guy as the name )
MATCH( first, last )AGAINST('+"some" +"guy"' IN BOOLEAN MODE )
delete the white-space from concat function in query and other thing is use $player = str_replace(' ','',trim($_POST['name'])) instead of $player = $_POST['name'].
$SQL = "SELECT * FROM TABLE_NAME WHERE concat(first_name,last_name) = '".$player."'"
i suggest PDO with prepared statements...
assume you are searching 'benjamin example' and query will check for 'benjamin example' so str_replace will output as benjaminexample.and the concated first_name and last_name will match it.
hope it help.
ignore if it sound silly.

Matching variable to two columns joined (PHP)

A previous variable from a query gave me a value $name. I need to find the user id associated with that name, however in my users table I have two fields, firstName and lastName.
I cannot explode $name as I have both cases of double names (e.g. John Eric Smith) and last names (e.g. Jan van der Worde), so my attempt was to find a way to match firstName + lastName with $name.
My attempt was this:
$drid = "SELECT id FROM users WHERE CONCAT(firstName,' ',lastName)='$name'";
$rest = mysql_query($drid);
while ($row = mysql_fetch_row($rest)) {
$driver_id = $row[0];
}
Unfortunately, nothing comes out as a result for $driver_id (whereas $name returns a result).
Thank you for your help!
Are you looking for something like this:
<?php
$drid = "SELECT id FROM users WHERE CONCAT(firstName, ' ', lastName) LIKE '%".$name."%'";
$rest = mysql_query($drid);
while ($row = mysql_fetch_row($rest)) {
$driver_id = $row[0];
}
?>
I would suggest adding a new fullname field or using a temp table rather than using the concat, for performance reasons.
https://stackoverflow.com/a/29285246/3923450 should work though if you are looking for a temp solution

How to retrieve data from a single field in mysql?

I'm trying to retrieve an email address from a table in MySql using $keyword (keyword can be anything in the question field) to identify the row. I am successful in finding the row I need with the query below but it returns the entire row, how does one pull just the email out of the row and store it as $email?
Query:
$result = mysql_query("SELECT * FROM ask WHERE date = '$keyword' order by ask_id")
or die(mysql_error());
Table:
| ask_id | store | fname | lname | email | phone | city| state | zip_code |question | sku | date |
Just select only the column you need email instead of them all *
$result = mysql_query("SELECT email FROM ask WHERE date = '$keyword' order by ask_id")
Note that mysql_* function are deprecated, better to switch to either mysqli or PDO. So you will be able to use prepared statements and you will avoid any risk of mysql injection, learn more here How can I prevent SQL injection in PHP?
SELECT `email` FROM ask WHERE date = '$keyword' order by ask_id
Use code above instead. SELECT * FROM... in your mysql statement means select everything.
$result = mysql_query("SELECT columnName AS email FROM ask WHERE date = '" . $keyword . "' ORDER BY ask_id");
while($row = mysql_fetch_assoc($result)){
$row['email']; // Here Do Anything With Email...
}
First off, the obligatory mysql_* commands are deprecated, don't use them, kittens will die and your dog will get shot etc. For more on that, please see this question.
If you only want to retrieve one column from your MySQL database you can do so by specifying the column after your SELECT, instead of an asterisk. So you would have a query as follows:
SELECT email FROM ask WHERE date = '$keyword' order by ask_id
You can use this as follows in PHP code:
$result = mysql_query("SELECT email FROM ask WHERE date = '$keyword' order by ask_id")
or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
var_dump($row);
}
To reiterate, you should not be using the mysql_* functions. There are superior replacements available, as detailed in the question referenced above.

SELECT MAX(... not returning anything in PHP/MYSQL

This is the table structure-
Table: test
+------+---------+
| PAGE | CONTENT |
+------+---------+
| 1 | ABC |
+------+---------+
| 2 | DEF |
+------+---------+
| 3 | GHI |
+------+---------+
PAGE is a Primary with datatype INT(11). It does not auto-increment. CONTENT is of the datatype TEXT.
In PHP I do-
$result = mysql_query(SELECT MAX(PAGE) FROM test);
$row = mysql_fetch_array($result);
echo $row["PAGE"];
No output. At all. If I do something like echo "Value : ".$row["PAGE"]; all I see is Value :
The query SELECT * FROM test works just fine though. Am I wrong somewhere using the MAX() syntax?
I want it to return the maximum value of PAGE as of yet.
This should be the code.
$result = mysql_query("SELECT MAX(PAGE) AS max_page FROM test");
$row = mysql_fetch_array($result);
echo $row["max_page"];
Shouldn't you have quotes around that query in mysql_query? I have no idea what PHP will do with such a syntactically inadequate statement, I would have thought it would have given you an error.
In any case, an aggregate function may have a different column name than the column used for it (from memory, DB2 gives it a similar name to the function, like max_page_ or something). You may want to ensure it has the correct column name by forcing the name with something like:
$result = mysql_query("SELECT MAX(PAGE) AS MAXPAGE FROM TEST");
$row = mysql_fetch_array($result);
echo $row["MAXPAGE"];
Try below code
$result = mysqli_query($con,"SELECT max(page2_content_id) AS max_page from page2_content_data");
$row = mysqli_fetch_array($result);
echo $row["max_page"];
Where $con=new mysqli($server,$user,$password,$db_name); and page2_content_data is my table,and page2_content_id is the column name
$connect = mysqli_connect("localhost", "root", "", "carBid") or die("not connected");
//connection to database
$sql2 = "SELECT max(mybid) FROM `bid`";
//simle select statement with max function
$result_set2 = mysqli_query($connect,$sql2);
//query a result fetch
if ($result_set2) {
$rowB = mysqli_fetch_array($result_set2);
//feching a result in array format
echo $rowB['max(mybid)'];
//accessing array by name of column with max() function of mysql
} else {
echo 'No Current Bid';
}
mysqli_close($connect);
I used something like this in my code;
$maxscore_query = mysql_query("SELECT MAX(`score`) FROM `allscores` WHERE`level`='$levelcode'");
echo mysql_result($maxscore_query, 0);
The difference here is the use of WHERE for selecting a group.
And mysql_result($maxscore_query, 0); is easier to manage for me.

Select row from DB based on 3 different values

Currently my DB looks similar too...
ID Username Interest
04 Tommy Soccer
04 Tommy Internet
32 Jack Soccer
32 Jack Swimming
32 Jack Boxing
I have a page on my website where the user can specify his/her interests and depending on what they enter, those with the same interests will be displayed.
So If Tommy was to visit my page and add "Boxing" as an Interest Jack would show up as he has "Boxing" listed within the table.
I need to write a query to do this but i'm unsure of the best way to do it as i'm still very new to PHP, would something along the lines of...
mysql_query(SELECT * FROM interests_table WHERE Interest = $interest1 || $interest2 || Interest3);
mysql_query("SELECT * FROM interests_table WHERE (Interest = $interest1 OR Interest = $interest2 OR Interest = $Interest3)");
Even shorter:
mysql_query("SELECT * FROM interests_table WHERE Interest IN ($interest1, $interest2, $interest3)");
Of course you will need to add necessary parameters escaping for more secure code.
If you have all possible values you want to search for in array, the code may look like this:
$interests = array('boxing', 'swimming', 'speedway');
// ... query preparation
$result = mysql_query("SELECT * FROM interests_table WHERE Interest IN (" . implode('", "', mysql_real_escape_string($interests)) . ")");
// rest of the code ...
But this code is only effective for small sets of data (few to hundreds). If you'd have more interests on list, you should find more effective way.

Categories