Drop down with MySQL and PHP sample - php

I have tried out this example but not sure where I have gone wrong - I've created the database and relative fields. When I select UK it gives me a blank result. Here is my script
main.php
<?php
$connect=mysql_connect("localhost","root","") or die("Cannot connect");
$dbselect=mysql_select_db("test");
$sql_country = "SELECT * FROM COUNTRY";
$result_country = mysql_query($sql_country) or die("Query problem");
echo "<form method='POST'>";
echo "<select name='country' onChange='get_cities(this.value)'>"; //get_cities is defined below
echo "<option value=''></option>";
while($row_country = mysql_fetch_array($result_country))
{
echo "<option value='".$row_country['id']."'>".$row_country['country']."</option>";
}
echo "</select>";
echo "<select name='city' id='city'></select>"; //We have given id to this dropdown
echo "</form>";
?>
<script type="text/javascript">
function get_cities(country_id)
{
$.ajax({
type: "POST",
url: "cities.php", /* The country id will be sent to this file */
beforeSend: function () {
$("#city").html("<option>Loading ...</option>");
},
data: "country_id="+country_id,
success: function(msg){
$("#city").html(msg);
}
});
}
</script>
cities.php
<?php
// Code for cities.php
$connect=mysql_connect("localhost","root","") or die("Cannot connect");
$dbselect=mysql_select_db("test");
$country_id = $_REQUEST['country_id'];
$sql_city = "SELECT * FROM CITY WHERE country_id = '".$country_id."'";
$result_city = mysql_query($sql_city);
echo "<select name='city'>";
while($row_city = mysql_fetch_array($result_city))
{
echo "<option value='".$row_city['id']."'>".$row_city['city']."</option>";
}
echo "</select>";
?>
Sample code: http://www.x-developer.com/php-scripts/loading-drop-downs-with-ajax-php-and-fetching-values-from-database-without-refreshing-the-page

There doesn't seem to be any error checking in your example, and you should be aware that with databases, plenty of things can go wrong!
Try making these amendments. Change this:
$connect=mysql_connect("localhost","root","");
to:
$connect=mysql_connect("localhost","root","") or die("Cannot connect");
And this:
$result_country = mysql_query($sql_country);
to:
$result_country = mysql_query($sql_country) or die("Query problem");
This will highlight two common problems - connecting or not finding the specified table.
Also, cities.php doesn't appear to connect to the database at all. Add in the mysql_connect and the mysql_select_db from the first file into the second, and that should connect it correctly.
Lastly, there is a serious security vulnerability with this tutorial, which would permit internet users to run arbitrary SQL on your database server. Change this:
$country_id = $_REQUEST['country_id'];
to this:
$country_id = (int) $_REQUEST['country_id'];
That will force the country ID to be an integer, rather than just accepting it uncritically as a string.

In your cities.php there is no database connection. Write the DB connection there also after that it will give you drop down.

You have not any databse connection in cities.php, so SELECT statement does not work.

If you are open to use jquery, which is a great help when it comes to ajax driven web apps,
Try this for your jquery code
//ensure the select name 'country' has the id 'country'
$("#country").change(function(){
//get country id of the selected country option
var countryid = $("#country option:selected").val();
//here we post the id of the country to the php page. note that within the curly braces, the first parameter is what corresponds to the variable in php e.g $countryid=$_POST[country_id]. The second parameter is the javascript variable
$.post("cities.php",{country_id:countryid},function(data){
//check that the json object returned is not empty
if(!$.isEmptyObject(data))
{
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
var cityid = [data[i].id];
var cityname = [data[i].city];
html += '<option value = '+cityid+'>'+city+'</option>';
}
//append the results of the query. The prepend part is to make a blank option first and make it selected so as to force a user to actually select a city.
$("#city").html(html).prepend("<option value='' selected='selected'></option>").show();
}
else{
alert('No cities found for this country');
}
},'json')
})
Your php page for cities remains as it is but make the following adjustments
<?php
// Code for cities.php
$connect=mysql_connect("localhost","root","") or die("Cannot connect");
$dbselect=mysql_select_db("test");
//change it from request to post.
$country_id = $_POST['country_id'];
//the below code is not safe!!! You are open to sql injection. To make it worse you are connected as root. A malicious user can drop your database.
$sql_city = "SELECT * FROM CITY WHERE country_id = '".$country_id."'";
$result_city = mysql_query($sql_city);
while($row_city = mysql_fetch_array($result_city))
{
$data[] = $row_city;
}
//return the json onject to the client.
echo json_encode($data);
?>
The above code might help you should you choose the jquery way of writing javascript. You will need to download jquery first.

The response from the server contains a dropdown menu, but the current code appends the HTML result not into a div or span, but into into another dropdown menu, thus:
<select name='city' id='city'><select name='city'>....</select> </select>
This is incorrect. To avoid this, change:
echo "<select name='city' id='city'></select>";
to
echo "<div id='city'> </div>";
Or, removeecho "<select>" line from cities.php
<?php
// DB CONNECTION
$country_id = $_REQUEST['country_id'];
$sql_city = "SELECT * FROM CITY WHERE country_id = '".$country_id."'";
$result_city = mysql_query($sql_city);
while($row_city = mysql_fetch_array($result_city))
{
echo "<option value='".$row_city['id']."'>".$row_city['city']."</option>";
}
?>

Related

How to get in a variable the value of the selection of a Select/Drop Down Menu PHP or HTML

I'm trying to connect 2 drop-downs so in the first I show a list of countries and based on the selection of the country I show a list of the cities for the country selected.
I have my index.php file which load all the countries correctly as seen in this image:
Code to load my countries
<select name="country" id="country">
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$query = "SELECT country FROM countries";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value=Select>Select a Country</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[country]>$myrow[country]</option>");
}
?>
</select>
Now I'm trying to do the same based on the selection from the previous "Select" but it is not working. The issue I'm having is getting the value selected in the country select because if I hard-type a value of a country like: $query = "SELECT city FROM cities where country = Albania"; then it works. Also I tried to print the value of the country selected: (echo $selectedCountry;) and it not printing anything so I'm guessing neither $selectedCountry = $_GET['country']; or $selectedCountry = $_POST['country']; are getting the value of the country selected.
<select name="city" id="city">
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$selectedCountry = $_GET['country'];
$selectedCountry = $_POST['country'];
echo $selectedCountry;
$query = "SELECT city FROM cities where country = ' $selectedCountry '";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value=Select>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[city]>$myrow[city]</option>");
}
?>
</select>
Thank you very much in advance
UPDATE
This is what I see in the first Load. Where the country Select is loaded with all the values as per the image above and the city Select is empty (Only the "Select a city" value) waiting to be loaded with the values depending on the country selection.
LAST UPDATE - From Borna Suggestion
Borna,
I've tried your suggestion, below the exact code that I'm using. Using two countries as example. However, the cities are empty the first load and when I select a country nothing loads in the city Select and I get the following screen. It seams that it is actually not calling/running the getCities.php:
Index.html
<!DOCTYPE html>
<html>
<head>
<script>
function populateCities(citiesSelectBoxOptions){
document.getElementById("city").innerHTML = citiesSelectBoxOptions;
}
function httpGetAsync(theUrl, callback)
{
alert(theUrl);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
</script>
</head>
<body>
<select name="country" id="country" onchange="httpGetAsync('http://localhost/FillCity/getCities?country=' + this.value, populateCities)">
<option value="Angola">Angola</option>
<option value="Spain">Spain</option>
</select>
<select name="city" id="city">
</select>
</body>
</html>
getCities.php
<?php
include("config.php");
$db = pg_connect("$db_host $db_name $db_username $db_password");
$selectedCountry = $_GET['country'];
echo "country: " .$country;
$query = "SELECT city FROM cities where country = ' $selectedCountry '";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value='Select'>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value='$myrow[city]'>$myrow[city]</option>");
}
?>
UPDATE
If I run http://localhost/FillCity/getCities?country=Spain this is what I get
If I run just http://localhost/FillCity/getCities.php I get: (I'm getting the word country because I place and echo $country in the code to see the country selected)
This is my FillCity folder under my localhost (var/www/html)
And here is what I see when running the Index.html for the first time with Angola as default country.
If I select any country, Spain, as example this is what I get
LAST UPDATE
When I open the .html file and I select a country this is what I get (Still printing out that message on the screen):
Once I click Ok then it works and I can see all the cities for the country (But of course I would like not to have that message popping up)
Thanks again
Well, what you really need is AJAX call which allows you to communicate with server without reloading a page. All you have to do is basically send a new HTTP request with a country parameter to get the list of cities in it. The correct way would be to send (HTTP response) only the data(cities) in JSON or similar format, and not its presentation also (html), but for simplicity, you can continue to work like you started (return data with html).
Start by separating the code that generates HTML selectBoxOptions of cities in another script.
You will use that script to get the list of cities in particular country by using AJAX (XMLHttpRequest library).
Have a look at this, it's a working solution of your problem. HTTP request is sent whenever user changes the countrySelectBox option, that way your cities select box gets updated every time it needs.
All you have to do is change the url in the onchange attribute that points to your script (I previously said that you should move 2nd block of code into separate script).
<!DOCTYPE html>
<html>
<head>
<script>
function populateCities(citiesSelectBoxOptions){
document.getElementById("city").innerHTML = citiesSelectBoxOptions;
}
function httpGetAsync(theUrl, callback)
{
alert(theUrl);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
</script>
</head>
<body>
<select name="country" id="country" onchange="httpGetAsync('www.yourdomain.com/getCities.php?country=' + this.options[this.selectedIndex].value, populateCities)">
<option value="Country1">Country 1</option>
<option value="Country2">Country 2</option>
</select>
<select name="city" id="city">
</select>
</body>
</html>
getCities.php
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$selectedCountry = $_GET['country'];
$query = "SELECT city FROM cities where country = ' $selectedCountry '";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value='Select'>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value='$myrow[city]'>$myrow[city]</option>");
}
?>
EDIT:
httpGetAsync is native (only pure/vanilla javascript is used. No other libraries are used) javascript function that enables you to send HTTP request without reloading a page. I see you are using jQuery, which hides this function's complexity, same as form->submit, but I recommend you to learn how httpGetAsync works, because using a jQuery for such a simple task is overkill.
You don't need this javascript function
function getCity(countryId)
Instead, you should put your code that communicates with database in a .php file, not in javascript (remember, javascript is a client side, it executes on client machine, e.g. browser, while php executes on server). Your SQL should never be written in javascript. Client side code cannot communicate with a database directly, only through server side coding. To accomplish that, you must return a value of PHP script getCities.php back to the client(javascript) as a HTTP response.
When you send a HTTP request to some .php file, that scripts executes on a server, and everything that you said "echo" or "print", on the end of script, is automaticaly sent as HTTP response. You don't actualy have to write any code to send a HTTP response. Its done automaticaly. You just have to echo/print whatever you need on the client side. In your case, you need to print options for particular country.
How the script knows for which country it needs to select cities from database?
Well, you send HTTP request with a parameter "country". That is what you Form is doing automaticaly when you submit it. All HTML tags that are inside Form, and have a name attribute set, are gonna be send in HTTP request as parameters. But, since you cannot use submit, you must do this manualy.
To send a parameter inside HTTP GET request is very simple.
Have a look at the following url:
localhost/getCities?country=countryX&someOtherParam=something&myThirdParam=something3
On server side, the following variables are gonna be populated:
$_GET["country"] // value is 'countryX'
$_GET["someOtherParam"] // value is 'something'
$_GET["myThirdParam"] // value is 'something3'
To learn more about how GET and POST works, and what is the difference, check this
Get started by creating a getCities.php file, and copy paste the code that communicates with database and generates city options. It's basically what you already did, you just have to put that code in separate .php file. So, when a client (browser) asks for a list of cities in particular country, you are going to send a HTTP request (using httpGetAsync() function) to get that list from the server.
In your index.php copy paste this script
<script>
function populateCities(citiesSelectBoxOptions){
document.getElementById("city").innerHTML = citiesSelectBoxOptions;
}
function httpGetAsync(theUrl, callback)
{
alert(theUrl);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
</script>
Next, put onchange attribute on select box, remember, its all lower case, not onChange.
<select name="country" id="country" onchange="httpGetAsync('localhost/getCities?country=' + this.value, populateCities)">
For any question just ask... :)
Well, I suppose one way to do it would be with jQuery.
There's probably a few different ways to do this, but what you could do, is load all the cities into the city drop-down, regardless of country, but change the printf for the city options like this.
$query = "SELECT city, country FROM cities";
....
while($myrow = pg_fetch_assoc($result)) {
printf ("<option class="$myrow[country] city_select" value=$myrow[city]>$myrow[city]</option>");
}
And then in the javascript for the page, have something like
$('#country').bind('change', function(){
var country = $(this).val();
$('#city option.city_select').hide();
$('#city option.'+country+'').show();
});
It's not necessarily the most elegant solution, though.
You are missing the quotes inside your option, it should be something like
<option value=$myrow['city']>$myrow['city']</option>
try that

Get value from dropdown list to use in MySQL query

So I'm having this issue with geting a value from a dropdown list in HTML into a variable so that I can do the mysql query. This will be a little tricky to explain but I will do my best. (Do not be shy in correcting my english or my expressions so that the question becomes more concrete and easy to understand).
So I have this dropdown list that gets his values from a mysql query.
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
This "connects" with this query:
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'");
$result4 = mysql_query($sql4, $link);
This query will populate the dropdown list with values. What I'm seeking to do is to populate another dropdown list. For examples I select a list of countrys, and when I select on country it should appear all it's citys in the other dropdown list.
I have been searching guys. Belive me I have.
P.s: Please do not get mad if I change the question a couple of times when I see that you guys show me a way to explain it better. Sorry if my english isn't perfect. Thank you guys for the help.
You can do it with ajax and jquery. I try to write little example
<!-- index.php -->
<select name="desig_act" id="desig_act">
<?php while ($row2 = mysql_fetch_assoc($result4)): ?>
<option value="<?=$row2['new_name_freg']?>">
<?=$row2["new_name_freg"]?>
</option>
<?php endwhile; ?>
</select>
<!-- select tag for countries -->
<select name="country" id="country"></select>
write a little script to return countries as json
<?php //ajax-countries.php
$link = mysql_connect(); // connect as usual
$query = ("SELECT * FROM countries");
$result = mysql_query($query, $link);
$json = array();
while ($row = mysql_fetch_assoc($result)) $json[] = $row;
echo json_encode($json);
?>
Then you can have some sort of script like:
// script.js
$("#desig_act").change(function(){
$.getJSON( "ajax-countries.php", function( data ) {
$.each( data, function(key, val) {
$("#desig_act").append("<option val='" + key + "'>" + val + "</option>");
});
});
I hope it can be useful
1: Create a PHP script to return the data
Essentially just generate the value based off the $_GET input.
2: Create a json request in jquery
Calls the PHP file which will return the data and you will use that data to add more values to the select.
<?php
//Step 1 - The posted ajax data that will return our json request.
if(isset($_GET['fetchrow'])) //Is our ajax request called on page load? If yes, go to this code block
{
//Other stuff like DB connection
$pesq = mysql_escape_string($_GET['fetchrow']); //Put our variable as the variable sent through ajax
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'"); //Run our query
$result4 = mysql_query($sql4, $link); //Please change from mysql_* to mysqli
$data = array(); //The array in which the data is in
while($row = mysql_fetch_assoc($result4)) //Look through all rows
{
array_push($data, $row); //Put the data into the array
}
echo json_encode($data); //Send all the data to our ajax request in json format.
die; //Don't show any more of the page if ajax request.
}
?>
<html>
<head>
<script type='application/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js'></script> <!--Include jquery -->
<script>
//Step #2:
//The jquery script calls ajax request on change of the first select
$( "#desig_act" ).change(function() {
$.getJSON('thisfilename.php', {fetchrow:$("#desig_act").val()}, function(data){ //Get the json data from the script above
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) { //Loop through all results
html += '<option value="' + data[i].new_name_freg + '">' + data[i].new_name_freg + '</option>'; // Add data to string for each row
}
$('#otherselect').html(html); //Add data to the select.
});
});
</script>
</head>
<body>
<!-- Your html code -->
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
</td>
<!-- The new select -->
<select name='otherselect' id='otherselect'>
</select>
<!-- Rest of html code -->
</body>
</html>

I'm not able to change the page contents when i select combo-box options in php

<?php
// select box open tag
$selectBoxOpen = "<select name='store_name' >";
// select box close tag
$selectBoxClose = "</select>";
// select box option tag
$selectBoxOption = '';
// connect mysql server
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
// select database
mysql_select_db("store", $con);
// fire mysql query
$result = mysql_query("SELECT store_name FROM store_input");
// play with return result array
while($row = mysql_fetch_array($result)){
$selectBoxOption .="<option value = '".$row['store_name']."'>".$row['store_name'] . "</option>";
}
// create select box tag with mysql result
$selectBox = $selectBoxOpen.$selectBoxOption.
$selectBoxClose;
echo $selectBox;
?>
this is my sample code, I have created combobox in php with option values from database values
but i'm not able to change the page contents when i select options.
any answers
Your code is lacking Javascript, which would be required for the outcome you are expecting. Seeing as you haven't really defined the complete outcome you expect, I will just show you what you need to update the url with the currently selected store:
$selectBoxOpen = "<select name='store_name' onchange=\"location.href=location.href+'?store='+this.value\" >";
I've added an onchange event (read more about DOM events here) so that when you select a different value you are changing the location.
Now when you change the value of the select, your url should change to scriptname.php?store=SomeStoreName

How can I solve this mysql search query

I'm working on a chained select drop down that pulls data from the database to populate the category combobox while the subcategory combo box populates when an option from the category combobox is selected. The category dropdown box pulls data from database without any issue but I am having problems with getting the subcategorycombo box select data from database based on the 'id' of the option selected in the category combo box.Any help pls?below is my php code and the jquery code that display the data
<?php
include ('../storescripts/connection.php');
function ShowCategory(){
$sql = "SELECT * FROM category";
$res = mysql_query($sql) or die(mysql_error());
$category = '<option value="0">Choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value = "'.$row['category_id'].'"> '.$row['category_name']. ' </option>';
}
return $category;
}
function ShowSubCategory(){
if (!isset($_POST['id']))
{
//If not isset -> set with dumy value
$_POST['id'] = "";
}
$sql1 = "SELECT * FROM subcategory WHERE category_id = '$_POST[id]'";
$res1 = mysql_query($sql1) or die(mysql_error());
$subcategory = '<option value="0"> Choose...</option>';
while($row = mysql_fetch_array($res1)){
$subcategory .= '<option value="'.$row['subcategory_id'].'"> '.$row['subcategory_name'].' </option>';
}
return $subcategory;
}
?>
//jquery code
<script type="text/javascript">
$(document).ready(function() {
$("select#category").change(function(){
var id = $("select#category option:selected").attr('value');
$.post("select_subcat.php", {id:id}, function(data){
$("select#subcategory").html(data);
});
});
});
</script>
Try to narrow down what could be the problem. Have PHP print out the SQL statements to the page when you make a selection.
Then you can feed that exact statement into MySQL (through command line or via phpmyadmin) and see if you get the results you want. If you do, then the problem is later down the line. What do you see?
I will agree with earlier poster - if the $_POST id is not set, you fill it with ""? That probably won't get any results.
One last note: at very least use mysql_real_escape_string() before you ever touch any $_POST or $_GET variables. You are opening your site up to a number of SQL injection attacks otherwise.

how Start PHP Session when click with jquery

i have problim in jquery
i working in interactive map, in click form href for city i wnat insert the city name or number in sql query .
this link
link citys :
<a href='#' class='city_pr' id=aden> </a>
mysql query:
$sql="select * from project where city='$_SESSION[CITY]' AND active =1 ";
How to make a change when the session to mysql query on click the link below Download Page Navigation with jquery
It is not possible to use PHP session directly with jQuery, you need to do an ajax call.
Try this.
Explanation:
This will capture the value inside the link, do a post to a PHP file and print the data in "result" div without refreshing the page.
(Don't forget to read my observation at the end of the post)
HTML:
<a href='#' id='country'>USA</a>
<br/>
<div id="result"></div>
JS:
​$('#country').click(function(){
// get the value inside the <a> tag
var country = $(this).html();
$.post('process.php', { country:country }, function(data){
// Everything is Ok, so data won't be 0
if(data != 0){
// Print country information
$('#result').html(data);
}
});
});
process.php
<?php
if($_POST() && isset($_POST['country'])){
/* Connect to DB */
$link = mysql_connect('server', 'user', 'pwd');
if (!$link) {
// No connection
print(0);
exit();
}
$db = mysql_select_db('db', $link);
if (!$db) {
// DB selection error
print(0);
exit();
}
/* sanitize the value */
$country = mysql_real_escape_string($_POST['country']);
/* do your query */
$sql = "SELECT * FROM country WHERE country_name = '$country'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
// At this point I am supposing that you stored in your table
// latitudes and longitudes of countries.
echo "Latitude is: ".$row['latitude']." Longitude is: ".$row['longitude'];
}
} else {
// No results found
print(0);
}
}
?>​
Observation:
Try using other way to send the country value to the server.
For example:
if I have:
<a href='#' id='country'>United States of America</a>
In SQL query I will have:
SELECT * FROM country WHERE country_name = 'United States of America';
A better way could be:
<a href='#' id='us'>United States of America</a>
So in my JS I will have to replace var country = $(this).html(); for this:
//outputs 'us'
var country = $(this).attr('id');
Then in your SQL query you will get this:
SELECT * FROM country WHERE country_name = 'us';
It is more reasonable to use codes and no names (names are just to show the user, for better understanding because then you will have more problems to sanitize the value for using it with your query and also use functions like trim(); to remove spaces and others). If you do that you will have to change your query to find the country by code:
SELECT * FROM country WHERE country_code = 'us';
Hope this helps :-)

Categories