How do I search a table for multiple rows? - mysql

So this is my first question on stackoverflow and I've searched for day's but can't find the results I am looking for. I'm not looking for someone to write the code for me as I prefer to figure it out on my own, but I am looking for some assistance on finding how to do it.
My problem is I don't know how to word my search for what I'm looking for and this is what I want to do. I want to be able to search a MySQL database by using keywords such as "U10 Mustangs" where U10 would be data in a row called 'divisions' and Mustangs would be data in a row called 'club', I know I can use the OR statement like this
(`division` LIKE '%".$query."%') OR (`club` LIKE '%".$query."%')
but that only allows me to search by division or club not both. So basically I'm looking for a tutorial to show me how I can search by more than one keyword. I'm sure I'm wording this wrong and that's why I'm unable to find what I want.
I'm new to MySQL and PHP so please be understanding if this makes no sense!
*UPDATE*
here is my search code:
<body>
<?php include 'menu.php';?>
<br/><br/><br/>
<div id="searchcontainer" style="width: 55%; height: 132px;">
<fieldset style="width: 330px"><legend>Search Criteria</legend>
<form action="search.php" method="POST">
<td>Enter Search</td><td> <input type="text" name="query"/></td><td> <input type="submit" name="submit" id="table_button" value="Search" action="search.php"/></td>
<br />
</form>
</fieldset><br/>
<fieldset><legend>Search Results</legend>
<?php
include 'connect/local_connect.php';
$query = $_POST['query'];
// gets value sent over search form
// $min_length = 3;
// you can set minimum length of the query if you want
// if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM players
WHERE (`team_name` LIKE '%".$query."%' AND `division` LIKE '%".$query."%') OR (`last_name` LIKE '%".$query."%') OR (`division` LIKE '%".$query."%') ORDER by id ASC") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `first_name`, `any`
// players is the name of our table
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
}
else{ // if there is no matching rows do following
echo "<font color=red>No Results!</font>";
?><br/><br/>
<?php
}
// else{ // if query length is less than minimum
// echo "Minimum length is ".$min_length;
// }
// Define $color=1
$color="1";
echo '<table width="100%" border="1" align="center" cellpadding="0" cellspacing="0">';
echo '<th>ID</th><th>Club</th><th>Last Name</th><th>First Name</th><th>Division</th>';
while($rows = mysql_fetch_array($raw_results)){
echo "<tr bgcolor='#fff000'>
<td><center>".$rows['id']."</td></center><td><center>".$rows['club']."</center></td><td><center>".$rows['last_name']."</td></center><td><center>".$rows['first_name']."</center></td></td><td><center>".$rows['division']."</center></td></td></tr>";
}
echo '</table>';
mysql_close();
?>
</fieldset>
</div>
</body>

Are yu looking for concat
where CONCAT(`division`,' ',`club`) like '%".$query."%'

I will suggest to create a full text index on division and club like this FULLTEXT (club,division)
and search using query like this
SELECT * FROM db
WHERE MATCH (club,division)
AGAINST ('search');

'...but that only allows me to search by division or club not both...'
You can split your search string in words and then use a condition like this
SELECT *
FROM table1
WHERE (division LIKE '%U10%' AND club LIKE '%Mustang%')
OR (division LIKE '%Mustang%' AND club LIKE '%U10%')
Here is SQLFiddle demo

Related

HTML Form data from checkboxes within while loop

I have a really basic Date system on a site which displays the dates from the Database using a While loop, next to each date that is listed is a check box.
I would like the user to be able to select as many dates as they would like and click submit to remove these dates or edit these dates.
I am having trouble figuring out how I would get the data from multiple check-boxes using only one within the while loop which could be used multiple times?
Here is my current code:
<form action="" method="post">
<b>Current Dates:</b> <button type="submit" id="remove_dates" name="remove_dates" class="btn btn-danger btn-sm">Remove Selected</button>
<hr>
<div style="overflow-y: scroll;height:100px">
<?
$sqldate = "SELECT * FROM `foiu51r_calendar` ORDER BY date DESC";
$resultdate = $conn->query($sqldate);
if ($resultdate->num_rows > 0) {
// output data of each row
while($rowdate = $resultdate->fetch_assoc()) {
$date_id = $rowdate['date_id'];
$dates = $rowdate['date'];
?>
<input type="checkbox" id="date_id" name="date_id" value="<? echo $date_id; ?>"> <b><? echo date("d/m/Y", strtotime($dates)); ?></b><br>
<?
}
}
?>
</div>
</form>
if(isset($_POST['remove_dates'])){
$date_id = $_POST['date_id'];
}
I believe if you add this: [], to the name attribute, like this: <input type="checkbox" id="date_id" name="date_id[]" value="<? echo $date_id; ?>">. Then it will be handled as an array, which you can loop through with a foreach loop. and insert it into a database (or whatever you like).
Declare the name as an array, like as follows:
<input type="checkbox" id="date_id" name="date_id[]" value="<? echo $date_id; ?>">.
On submitting it will be handled as an array,
Then, you can loop the values of an array and for each element of an array use the id to remove the dates.

Accessing data from Wikidata JSON file

I'm trying to access the following properties from the Wikidata API: id, url, aliases, description and label but so far have been unsuccessful. I'm sure I'm making basic mistakes and so far only have the following code. Any suggestions as to the best way to access this data is much appreciated.
<html>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$errors = libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php?
action=wbsearchentities&search=Google&format=json&language=en");
libxml_clear_errors();
libxml_use_internal_errors($errors);
}
?>
</body>
</html>
Edit - I have managed to get a string ($jsonArr) containing particular data that I would like. However I would like to get the first instance of the particular elements from the string specifically id, url, alias, description and label i.e. specifically: variable1 - Q95, variable2 - //www.wikidata.org/wiki/Q95, variable3 - Google.Inc, varialbe4 - American multinational Internet and technology corporation, variable5 - Google/ Please see code below:
<HTML>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$errors = libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php?
action=wbsearchentities&search=$search&format=json&language=en");
libxml_clear_errors();
libxml_use_internal_errors($errors);
var_dump($doc);
echo "<p>";
$jsonArr = $doc->documentElement->nodeValue;
$jsonArr = (string)$jsonArr;
echo $jsonArr;
}
?>
</body>
</HTML>
You need to show the JSON you want to parse...
Basicly you can get values out of JSON in PHP like this...
If $doc is the JSON you want to parse
$jsonArr = json_decode($doc, true);
$myValue = $jsonArr["keyYouWant"];
Edit after understanding what you are doing there :-)
Hi, Im sorry I was completely confused of what you were doing there... So I have testet your code on my server and just get what you want...
Following the code you wanted... I took clear var names, so they are a little bit longer, but easier to understand...
$searchString = urlencode($_POST['q']); //Encode your Searchstring for url
$resultJSONString = file_get_contents("https://www.wikidata.org/w/api.php?action=wbsearchentities&search=".$searchString."&format=json&language=en"); //Get your Data from wiki
$resultArrayWithHeader = json_decode($resultJSONString, true); //Make an associative Array from respondet JSON
$resultArrayClean = $resultArrayWithHeader["search"]; //Get the search Array and ignore the header part
for ($i = 0; $i < count($resultArrayClean); $i++) { //Loop through the search results
echo("<b>Entry: ".$i."</b>");
echo("<br>");
echo($resultArrayClean[$i]["id"]); //Search results value of key 'id' at position n
echo("<br>");
echo($resultArrayClean[$i]["url"]); //Search results value of key 'url' at position n
echo("<br>");
echo($resultArrayClean[$i]["aliases"]); //Search results value of key 'aliases' at position n
echo("<br>");
echo("<br>");
echo("<br>");
}

saving answers in an online test and sending them to database

I'm asked to write an online test. I have 2 tables, one includes questions (2 fields, one for id and one for question text). And another table for saving answers (with 3 fields, one for id, one for question id and one for the answer).
Here's how I've written it so far:
<form name="test" method="post" action="index.html">
<div class="slideshowContainer">
$question_query=dbquery("SELECT * FROM questions");
while($question_array=dbarray($question_query)){
echo'
<div class="question">
'.$question_array['question_text'].'
<br />
<textarea name="'.$question_array['id'].'"></textarea>
</div>
';
}
echo'
<input id="finish" type="submit" name="finish_test" value="send" />
</div>
</form>';
I'm also using cycle plugin so users can see the questions as slides and write the answers in each textarea provided for each specific question.
What I can't do is the way I should write the if(isset($_POST['finish_test'])) part. Because as I know in this way, the received data is in the form of an array. So I thought I might need another for or while element when I'm gonna save the answers and send them to my database.
What can you suggest?
Sure you are gonna need to loop through the results of the $_POST but its nice to make different id for each of the text areas in your code. That way you can identify which are which answers. So to do that I would do something like this.
while($question_array=dbarray($question_query)){
i = 0;
echo'
<div class="question".i>
'.$question_array['question_text'].'
<br />
<input id='question' type='hidden' value="'.$question_array['id'].'"/>
<textarea name="answer".i></textarea>
</div>';
i++;
}
Now since I know that i starts with 0 and ends when the questions end I can loop through that and access $_POST['answer'.i] and make the insertion.
while ($_POST['answer'.$i]) {
$i = 0;
//insert query after establishing connection, which i believe you got figured out
$sql = 'INSERT INTO ANSWERS VALUES ($_POST['answer'.$i], $_POST['question'.$i])';//Note you must have the question id in some hidden input field
$result = mysql_query( $sql, $conn );//where $conn is your connection object
//after this you might want to do something with the $result,
$i++;
}

multiple values in a single submit

I've been searching google to find the code, but I can't find it. What I want to do is pretty simple, but I'm not php expert.
I want to insert multiple cities' name in a single press of submit button (if that is possible)
I have created a database with 2 tables: 'cities' and 'states'
and I have populated the states table
so I need two fields or boxes, one is for states, which is drop down 'select' box which already filled with states name, pulled from the database,
the other one is a cities field which a text type field (type="text").
I want to be able to type in multiple cities name, probably separated with ',' a comma,
and with a single press of submit button, all the value will be inserted into mysql cities table and go on to the next state.
I know I need to create some sort of loop, but I have no idea how to do it.
*index.php (html):
<html>
<body>
<form action="save.php" method="POST">
<input type="text" name ="cities" value="">
<input type="text" name ="state" value="">
<input type="submit">
</form>
</body>
*save.php:
<?php
/* -------include you db connection here ----*/
if(isset($_POST['çities']) && $_POST['çities'] !='' && isset($_POST['state']) && $_POST['state'] !=''){
$cities = explode (',', $_POST['çities']);
$n = count($cities);
for($i=0;$i<$n;$i++){
//Insert data
mysql_query("insert into `cities` (city,state) values ('".$cities[$i]."','".$_POST['state']."') or die(mysql_error());
}
}
?>
First you create the input in the form like this:
<input type="text" name="cities"/>
And you then type: New York, New Jersey, San Francisco, Denver, etc.
Then on the .php file that receives the data (i'd guess it's a $_POST variable), so $_POST['cities'] then, you split it and loop:
// split the values by comma
$_POST['cities'] = explode(',',$_POST['cities']);
// loop the values
foreach($_POST['cities'] as $city) {
// trim (delete white space at the end and start for safety)
$city = trim($city);
mysql_query("insert into `cities` ('city','state') values ('".$city.','".$_POST['state']."');
}
And done.

fill a select html with mysql table rows

I'm writting a web app, I'm doing a html form with javascript to validate the data, I'm using a servlet to insert the data in a DB, but I need, when the form load, fill a select in the html form with the rows of a table in a MySql DB, I think I have to make a query in a ResultSet and then fill the select in the html form with this info, and then use the HttpServletResponse, but I have no idea how to make this
Use PHP to access the database and then put it into the form. Something like this:
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM table_name WHERE id='$id'");
$info = mysql_fetch_array($result))
$name = $info['name'];
$email = $info['email'];
$anotherField = $info['another_field'];
In this, the info array has all of the database data in it of the id. But of course you would change the values and stuff. Change table_name to the table name, and if you are going to do something in the URL like ?id=373384 or something, then this will work. (I would assume you are doing it this way.) But, if it isn't 'id', just change WHERE id='$id' to what is in the database to identify a line.
$info['name']; would be the "name" column in your table. But, you can change 'name' and stuff to what you have in your database.
Here is the form code to pre-fill it with data:
<form>
<input type="text" name="name" value="<?php echo $name ?>" />
<input type="text" name="name" value="<?php echo $email ?>" />
<!--etc...-->
<input type="submit" value="Submit" />
</form>
You would need to change a lot of this, but I'm sure you get the point of it. :)
Note: This is not a simple copy+paste script. You will have to do a lot of charing because I don't know what your table values are and stuff.
If you have any questions, please do ask.