I am work on HTML and PHP on my project , but I have a problem :
I have a drop down list with countries and I want a nother drop down list to appear with (cities of this country) when user choose a country
I have the countries data base and cities data base ( sql )
I try to use a java script method to do that but it didnt work
this is my code
First : this is the countries drop down list it is work good :
<select name="SelectCountry" id="SelectCountry" onchange="showCity()" >
<?php
$Con= mysql_connect("localhost","root","");
if(!$Con) { die('Could not connect'.mysql_error());}
if(!mysql_selectdb("MyDB",$Con)){die(mysql_error());}
$sql = "SELECT * FROM countries";
$result = mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo ("<option value=\"".$row['CountryID']."\">".$row['Name']."</option>");
}
mysql_close($Con);
Second , this is the java script function showCity() // didnt work any way !!
<script>
function showCity()
{
alert("in the function !!");
Document.write(" <?php echo "<select 'SelectCity' ,'SelectCity'";
echo "</select>";
$theCountry=$_GET['SelectCountry']; // get the country ID
$Con= mysql_connect("localhost","root","");
if(!$Con) { die('Could not connect'.mysql_error());}
if(!mysql_selectdb("MyDB",$Con)){die(mysql_error());}
$sql = "SELECT * FROM cities WHERE cities.Fips=(SELECT Fips FROM countries WHERE CountryID='$theCountry')"; // retrive the cities for the spicific country (work when I enter the ID manully in the sql query e.g CountryID='43')
$result = mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo ("<option value=\"".$row['Fips']."\">".$row['Fullname']."</option>"); // print all the cities in a menu (work when I enter the ID manully in the sql query e.g CountryID='43')
}
mysql_close($Con);
");"; ?> ");
}
</script>
this method is to create a new dropdown list for the spicific country cities when the user change the country by using Onchange Event
I hope you will help me
if there any Questions or misanderstod I am ready to answer or explain
thaaaanks all :)
For your level of experience it would probably be best if all you do by onchange is to submit the form:
<select name="SelectCountry" id="SelectCountry" onchange="this.form.submit();" >
This is equivalent to pressing the submit button after selecting a country. (You are missing </select> in your excerpt by the way, although I expect you just didn't copy that here.)
Then in PHP have something like... (note this code bit needs to be before the dropdown boxes so that the variable is there when you want to echo it)
if ( isset($_GET['SelectCountry']) )
{
$country = $_GET['SelectCountry'];
$citySelect = "<select name='SelectCity'>";
//query DB for cities of that country
...
//now add the options from the query just like you did for the countries, except now use the cities
...
$citySelect .= "</select>";
}
else
{
$citySelect = ""; //to make sure the variable isn't undefined
}
Now you can just add underneath your CountrySelect:
<? echo $citySelect; ?>
If a country was chosen before, the city menu will show.
Note that this does not include even the lowest level of security, fool proofing and it can be very complicated to get a large form to work like this.
$_GET['SelectCountry'] only works when you have the selects in a form tag and you click the submit button to reload the page (which creates the $_GET variable. A simple way to do this would be to add the country to your address URL and that will give you a $_GET too.
So inside the showCity() function, write this:
var i = document.getElementById("SelectCountry").selectedIndex;
var countryValue = document.getElementById("SelectCountry").options[i].text;
window.location.href = '/?SelectCountry='+countryValue;
This will redirect your web page to mysite.com/?SelectCountry=USA or something like that. Then your code will work. This isn't the best way to do it, but it should give you some results.
This doesn't work because $_GET['SelectCountry'] is always going to be null. You're confused about the difference between client side and server side scripting. Once you load the page for the first time, there is no GET variable yet, and so your Javascript is sitting on the browser with no cities. Changing the country doesn't make the getCity() go back to the server. It just looks at what it has already, which is nothing. You need an AJAX function, which has the job of sending GET requests to the server and bringing back the results. Once it gets the list of cities, its going to want to know what you want it to do with that list. You give it a function that makes a dropdown out of them. This is known as a callback. There are a lot of tutorials out there telling you how to make an AJAX function and where to put the callback.
Related
I have an HTML page with a filter that basically lists car names. When the user selects a value in the filter, I want to show the data associated to that value which comes from my PostgreSQL database. I have attached the code below. At the moment when the user is presented with the page and selects a value from the filter nothing is currently appearing not sure why. Any help welcome thank you
<html>
<select id="filter">
<option>All</option>
<option>BMW</option>
<option>Mercedes</option>
</select>
<?php
$db_connection = pg_connect("host=localhost dbname=postgres user=postgres password=postgres");
$feild_value = $_POST["filter"];
// you can use this $feild_value variable in query;
$result = pg_query($db_connection, "SELECT * from cars where car_name= $feild_value;");
//echo query result here
while($row = pg_fetch_array($result))
echo $result;
die;
?>
<script>
$(document).ready(function()
{
var value = $("#filter").val();
$.ajax({
type:"POST",
data:{"filter":value},
success:function(result){alert(result);}
})
});
</script>
</html>
I'm not sure about your code but your ajax function will not work on the filter change if you didn't call it in on change even, and make sure to put a submit URL to the ajax call and I hope your PHP script is in a separate file if not your script will not run after the die()
$('#filter').on('change',function(e){
//put your ajax submit here
});
There are couples of things with your code that you should be aware of.
Firstly, the die() function will stop the PHP code before the rest of the code is executed and outputted.
Secondly, $result = pg_query($db_connection, "SELECT * from cars where car_name=$feild_value;"); should be
$result = pg_query($db_connection, "SELECT * from cars where car_name='$feild_value;'");
Note the single quote around the $field_value in the SQL statement.
I have a dropdown box, and this is the format for the create.blade.php
<div class="col-sm-6">
<label for="order_mode">Order Mode</label>
<select class="form-control" id="order_mode" name="order_mode">
<option value="fcfs">First Come, First Serve</option>
<option value="pre-selling">Pre-Selling</option>
<option value="purchase-order">Purchase Order</option>
</select>
</div>
I want to use the same format for the edit.blade.php but I want to show what the selected value is as the default, and when I change it and hit update, then the changes will be saved.
the value for the order_mode is denoted by value="{{ $product->order_mode }}"
You can use AJAX to POST your variable to your edit.blade.php file. Personally, I use jQuery AJAX, simply because it's easy to read and understand. I also encapsulated the AJAX function into another function that you can call in your update button via onclick. However, you could also add this functionality directly to the AJAX function via an onclick event, however, note that in that case, you will need to put that into a document.ready function, so I figured encapsulating the function would make for easier understanding.
Note that you will need to include a jQuery library for this example to work. However, it's no different from including any other JS file or similar.
Example:
<script src="/js/jquery.min.js" type="text/javascript"></script>
/js/ being your JavaScript folder in your directory.
function updateSelection()
{
$.ajax({
type : "POST",
url : "/edit.blade.php",
data : {
selection: $("#order_mode")val()
},
success: function (html) {
/* here you can do something on success if you want.
I.e. redirect to another page etc. */
}
})
}
As for updating the value, I assume that you are storing the data into a database? If not, then you have to, or else there is no way of knowing what was selected in the future. So, going by that you are in fact storing the selected data into a database, your edit.blade.php file will need to fetch the parsed value (I named it selection in this case), and store it in the database.
<?php
/* Note that we used a "POST" method, so in order to
retrieve our parsed variable, we'll have to use $_POST. */
$selected=$_POST['selection'];
/* We then need to store it into the database.
Note that I don't know what mysql extension you use (mysql_*, mysqli_* or PDO).
I will use mysqli_* in my example, and $conn is your
database connection variable. */
/* Note that you will also need the user ID in order to know which user
updated their selected value. You will also need to check if the selection
already exists or not, because if it doesn't, you will have to perform an insert,
and if it does, you will have to perform an update in your query statement. */
//check if user selection already exists, or whether it's the users first selection.
$sql = "SELECT COUNT(column_name_for_user_id) FROM your_table_name
WHERE user_id_column='$your_user_id_variable'";
$result_set = mysqli_query($conn, $sql);
$check = mysqli_fetch_array($conn, $result_set )[0];
if($check > 0)
{
$sql = "UPDATE your_table_name SET column_name_for_selection='$selected'
WHERE column_name_for_user_id='$your_user_id_variable'";
}
else
{
$sql = "INSERT INTO your_table_name SET column_name_for_selection='$selected'
AND column_name_for_user_id='$your_user_id_variable'";
}
mysqli_query($conn, $sql);
/* I would recommend that you look into
prepared statements and/or sanitizing inputs */
?>
Important: In terms of the user ID, I do NOT recommend parsing it through AJAX, as it is something that is handled client side, meaning that it is fully editable by the client through the browser's dev tools. Instead, use a session.
Example of session variable:
<?php
session_start(); //starts the session on the page.
$your_user_id_session_variable = $_SESSION['$your_logged_in_users_user_id'];
?>
You will need to set this session upon user login, where you fetch the users data upon login success, and set the session variable.
Now back to your <select>. We will have to check for what is selected. You will have to retrieve the selected value from the database, using your user's user ID to fetch it.
Remember what I mentioned about sessions.
Example:
<?php
//$conn is your connection variable
$sql = "SELECT column_name_for_selection FROM your_table_name
WHERE user_id_column='$your_user_id_sessin_variable'";
$result_set = mysqli_query($conn, $sql);
$selected = mysqli_fetch_array($conn, $result_set )[0];
?>
You can now use your $selected variable to check for what was selected by the user, and it will always have that as its default selection.
<select class="form-control" id="order_mode" name="order_mode">
<option value="fcfs" <?php if($selected == "fcfs"){ echo 'selected="selected"'; } ?> >First Come, First Serve</option>
<option value="pre-selling" <?php if($selected == "pre-selling"){ echo 'selected="selected"'; } ?> >Pre-Selling</option>
<option value="purchase-order" <?php if($selected == "purchase-order"){ echo 'selected="selected"'; } ?> >Purchase Order</option>
</select>
Please note, that you will need to declare:
<?php
session_start();
?>
at the beginning of every file where you wish to use the session(s).
And now for the last bit, your update button.
<button id="updateButton" name="updateButton" onclick="updateSelection();">Update</button>
Long post... but I hope it helped, or at least gave some insight to how it could be done.
I want to use one single page with pre-defined divs, layout etc. as basis so that when a product is clicked on from elsewhere it loads that product info onto the page?
They way im doing it ill be sitting here till about 2020 still typing out product info onto pages.
EDIT*************
function product ()
{
$get = mysql_query ("SELECT id, name, description, price, imgcover FROM products WHERE size ='11'");
if (mysql_num_rows($get) == FALSE)
{
echo " There are no products to be displayed!";
}
else
{
while ($get_row = mysql_fetch_assoc($get))
{
echo "<div id='productbox'><a href=product1.php>".$get_row['name'].'<br />
'.$get_row['price']. '<br />
' .$get_row['description']. '<br />
' .$get_row['imgcover']. "</a></div>" ;
}
}
}
In addition one problem I have with that code is that the <a href> tag only goes to product1.php. Any ideas how I can make that link to blank product layout page that would be filled with the product info that the user has just clicked on, basically linking to itself on a blank layout page.
Thanks any help would be great!
Thanks Maxyy
Since you dont have code this is a general way of doing this. What you want is a template for the product page
Query the database
load the data into a variable
make a script that will print out the data from the variable into a product page
somescript.php
<?php
$productid = $_REQUEST['productid']; //Of course do sanitation
//before using get,post variables
//though you should be using mysqli_* functions as mysql_* are depreciated
$result = mysql_query("select * from sometable where id='{$productid}");
$product = mysql_fetch_object($result);
include("productpage.php");
productpage.php
<div class="Product">
<div class="picture"><img src="<?php echo $product->imghref;?>" /></div>
<div class="price"><?php echo $product->price;?></div>
</div>
so on and so fourth. Included scripts use whatever variables are currently in the scope of the calling function
If you are meaning to load the products into the same page without doing another page load you will need to use ajax. Which is javascript code that use XHR requests to return data from a server. You can either do pure javascript or a library like jQuery to simplify the process of doing a xhr request by using $.ajax calls.
I know this question has been asked over 4 years ago, but since there's been no answer marked as right, I thought I might chip in.
First, let's upgrade from mysql and use mysqli - my personal favorite, you can also use PDO. Have you tried using $_GET to pull the id of whatever product you want to see and then displaying them all together or one at a time?
It could look something like this:
<?php // start by creating $mysqli connection
$host = "localhost";
$user = "username";
$pass = "password";
$db_name = "database";
$mysqli = new mysqli($host, $user, $pass, $db_name);
if($mysqli->connect_error)
{
die("Having some trouble pulling data");
exit();
}
Assuming the connection was made successfully we move on to checking for an ID being set. In this case I check it via an URL param assumed to be id. You can make it more complex, or take a different approach here.
if(isset($_GET['id']))
{
$id = htmlentities($_GET['id']);
$query = "SELECT * FROM table WHERE id = " . $id;
}
else
{
// if no ID is set, just bring all the results down
// then you can modify how, and which table the results
// are being used.
$query = "SELECT * FROM table ORDER BY id"; // the query can be changed to whatever you would be prefer
}
Once we have decided on a query we go on to start querying the database for information. I have three steps:
Check query >
Check table for records >
Loop through roles and create an object for each.
if($result = $mysqli->query($query))
{
if($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
// you can set up your element here
// you can set it up in whatever way you want
// to see your product being displayed, by simply
// using $row->column_name
// each column becomes an object here. So your id
// column would be pulled using $row->id
echo "<h1>" . $row->name . "</h1>";
echo "<p>" . $row->description . "</p>";
echo "<img src=" . $row->image_path . ">";
// etc ...
}
}
else
{
// if no records match the selected ID
echo "Nothing to see here...";
}
}
else
{
// if there's a problem with the query
echo "A slight problem with your query.";
}
$mysqli->close(); // close connection for safety
?>
I hope this answers your question and can help you if you are still stuck on this problem. This is the bare skeleton of what you can do with MySQLi and PHP, you could always use some Ajax to make the page more interactive, and user-friendly.
Adding content to a page on click needs to be done in either Javascript or in JQuery.
You can use ajax call to retrive the needed data from php page, Syntax is here.
Or you can also load a php page to a div content with .load() function in JQuery, Syntax is here.
I am working on something it has 2 pages. One is index.php and another one is admin.php.I am making CMS page where you can edit information on the page yourself. Then it will go to the database, where the information is stored. I also have to have it where the user can update the information on the page. I am getting a little bit confused here.For instance here I am calling the database and I am starting a function called get_content:
<?php
function dbConnect(){
$hostname="localhost";
$database="blank";
$mysql_login="blank";
$mysql_password="blank";
if(!($db=mysql_connect($hostname, $mysql_login, $mysql_password))){
echo"error on connect";
}
else{
if(!(mysql_select_db($database,$db))){
echo mysql_error();
echo "<br />error on database connection. Check your settings.";
}
else{
return $db;
}
}
function get_content(){
$sql = "Select PageID,PageHeading,SubHeading,PageTitle,MetaDescription,MetaKeywords From tblContent ";
$query = mysql_query($sql) or die(mysql_error());
while ($row =mysql_fetch_assoc($query,MYSQL_ASSOC)){
$title =$row['PageID'[;
$PageHeading =$row['PageHeading'];
$SubHeading = $row['SubHeading'];
$PageTitle = $row['PageTitle'];
$MetaDescription =$row['MetaDescription'];
$MetaKeywords = $row['MetaKeywords'];
?>
And then on the index page and I am going to echo it out in the spot that someone can change:
<h2><?php echo mysql_result($row,0,"SubHeading");?>A Valid XHTML and CSS Web Design by WG.</h2>
I do know that the function is not finished I am still working on that part. What I am wondering is am I echoing it out right or I am way off. This is my first time messing with CMS in php and I am still learning it. I am working with navicat and text pad on this, yes I know it is old school but that is what I am being shown with. But my index is a form not a blog. I have seen many of CMS pages for blogs not to many to be used with forms. Any input will be considered thanks for reading my question.
Your question is a bit confusing and your code very incomplete. I'ts hard to say if you do it the right way since I don't see the rest of the script. You need to connect to the database there as well and get your data. The $row variable only exists in the while statement inside you function get_content() though.
You could complete the get_content() and use it in the index.php as well. Remember that the variables you define inside a function only is available there though. If you need the data outside that function you need to return the values you need and save them to some other variable there. Put if you do the same as you've started doing in the get_content() function in index.php, then you just have to echo the variables you define. Like this:
<h2><?php echo $SubHeading; ?></h2>
or you could also do it like this somewhere inside the php tags:
echo '<h2>{$SubHeading}</h2>';
I hope that answers your question.
EDIT:
What you need in the index.php page is exactly what you seem to be doing in the admin file. You need to connect to db using mysql_connect() and select db with mysql_select_db(). You then need to select the data from the db using the appropriate query with $query = mysql_query($sql). If it's more then one row you want to display you need to put it in a while loop otherwise (which seems to be the case here) you just need to do one $row = mysql_fetch_assoc($query). After that you can get the data using $row['column_name']. If you have more than one row you can just use $row['column_name'] in side the while loop to get each consecutive row's data.
Here is an example index.php:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password') or
die('Could not connect: ' . mysql_error());
mysql_select_db('database_name')) or die('Could not select database: ' .
mysql_error());
$sql = "SELECT SubHeading FROM tblContent WHERE PageID='1' LIMIT 1;";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo '<h2>{$row[\'SubHeading\']}</h2>';
mysql_close();
?>
This is just what you need to display the SubHeading from you database. You probably also need to handle your form and save the submitted data to the database in your admin.php file.
Please could someone help im building my first website that pulls info from a MySQL table, so far ive successfully managed to connect to the database and pull the information i need.
my website is set up to display a single record from the table, which it is doing however i need some way of changing the URL for each record, so i can link pages to specific records. i have seen on websites like facebook everyones profile ends with a unique number. e.g. http://www.facebook.com/profile.php?id=793636552
Id like to base my ID on the primary key on my table e.g. location_id
ive included my php code so far,
<?php
require "connect.php";
$query = "select * from location limit 1";
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['image'] ?>
<?php
}
?>
Thanks
Use $_GET to retrieve things from the script's query (aka command line, in a way):
<?php
$id = (intval)$_GET['id']; // force this query parameter to be treated as an integer
$query = "SELECT * FROM location WHERE id={$id};";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo 'nothing found';
} else {
$row = mysql_fetch_assoc($result);
echo $row['image'];
}
There are many things to consider if this is your first foray into MsSQL development.
SQL Injection
Someone might INSERT / DELETE, etc things via using your id from your url (be careful!, clean your input)
Leaking data
Someone might request id = 1234924 and you expected id = 12134 (so some sensitive data could be shown, etc;).
Use a light framework
If you haven't looked before, I would suggest something like a framework (CodeIgniter, or CakePHP), mysql calls, connections, validations are all boilerplate code (always have to do them). Best to save time and get into making your app rather than re-inventing the wheel.
Once you have selected the record from the database, you can redirect the user to a different url using the header() function. Example:
header('Location: http://yoursite.com/page.php?id=123');
You would need to create a link to the same (or a new page) with the URL as you desire, and then logic to check for the parameter to pull a certain image...
if you're listing all of them, you could:
echo "" . $row['name'] . ""
This would make the link.. now when they click it, in samepage.php you would want to look for it:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
//query the db and pull that image..
}
What you are looking for is the query string or get variables. You can access a get variable through php with $_GET['name']. For example:
http://www.facebook.com/profile.php?id=793636552
everything after the ? is the query string. The name of the variable is id, so to access it through your php you would use $_GET['id']. You can build onto these this an & in between the variables. For example:
http://www.facebook.com/profile.php?id=793636552&photo=12345
And here we have $_GET['id'] and $_GET['photo'].
variables can be pulled out of URL's very easily:
www.site.com/index.php?id=12345
we can access the number after id with $_GET['id']
echo $_GET['id'];
outputs:
12345
so if you had a list of records (or images, in your case), you can link to them even easier:
$query = mysql_query(...);
$numrows = mysql_num_rows($query);
for ($num=0;$num<=$numrows;$num++) {
$array = mysql_fetch_array($query);
echo "<a href=\"./index.php?id=". $row['id'] ."\" />Image #". $row['id'] ."</a>";
}
that will display all of your records like so:
Image #1 (links to: http://www.site.com/index.php?id=1)
Image #2 (links to: http://www.site.com/index.php?id=2)
Image #3 (links to: http://www.site.com/index.php?id=3)
...