jokomamamita commented: Thanks for your tips ~ jokomamamita +0
nonshatter 26 Posting Whiz
Hey,
This kind of works, but $cnt[0] returns the seller id that the buyer has bought from the least amount of times, rather than the most. I've tried changing 'nooftimes' to 'ASC' but it still gives me the lowest seller rather than the highest?
If I have a table sales:
sales {sellerid, buyerid}
I'm trying to determine the buyers favourite seller... So I need to return the most frequent sellerid.
I've used this query to find out the total number of times the buyer has bought something from any seller:
$countseller = mysql_query("SELECT count(sellerid) FROM sales WHERE buyerid = '$buid'");
$cnt = mysql_fetch_array($countseller);
echo "Number of times = '{$cnt[0]}'";
This returns '7' sales. So out of these 7, how can I determine which seller is the favourite?
Hey everyone. I'm having some trouble returning the correct number of matched results after a search query is issued to my site's search bar.
I was using this, but it returns the wrong number of matches (only for certain queries):
$countofrecs = mysql_query("SELECT count(*) from tablename WHERE title OR description LIKE '%".$searchterm."%' OR catid = '$catid'");
$cnt = mysql_fetch_array($countofrecs);
echo "Your search terms returned '$cnt[0]' results";
Thanks
Yea... I'm currently in the process of re-writing my CSS. I am now using <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> Is this the most 'correct' doctype to use? Or does it not really make much difference? At least I won't make the same mistake again!
Okay...I've been trying for hours and do you know what it was? I didn't have:
<!DOCTYPE html>
At the top of my page! [ROOKIE MISTAKE]
However, now my whole page doesn't display properly at all?! I've spent hours on my layout and styles etc. Does this mean I will need to change everything again to display my page correctly? : (
Still nothing. Technically it should work...
<html>
<head>
<script type="text/javascript">
function updateBids() {
var url="getprice.php?auc=<?php echo $id; ?>";
jQuery("#priceElement").load(url);
}
setInterval("updateBids()", 1000);
</script>
</head>
<body>
Here is the price: <div id="priceElement"></div>
</body>
</html>
<?php
include ('db.php');
$id = $_GET['auc'];
$getprice = mysql_query("SELECT b_currentprice FROM bid WHERE auction_id = '$id' ORDER BY b_timestamp DESC");
$resultprice = mysql_fetch_assoc($getprice);
$price = $resultprice['b_currentprice'];
echo $price;
?>
I have tested the getprice.php page on its own (manually giving it an auction id), so there shouldn't be any issues with that... Is there a way I can troubleshoot to see if the URL is actually being sent correctly by the javascript? I'm a bit stumped... Thanks
You could use a header re-direct to reload the logout page? Not sure if this is a fool proof solution though
header ('Location: /logout.php);
Thanks, I didn't have a clue where to start but you've helped me get started on this feature. I think I am nearly there but I still haven't been able to get the current price to display on the client-side. I have set it up as follows:
(getprice.php) - When I pass an auction ID to this page, it returns the current price, so given an id, I know this page is returning the correct values.
<?php
include ('db.php');
$id = $_GET['auc'];
$getprice = mysql_query("SELECT b_currentprice FROM bid WHERE auction_id = '$id' ORDER BY b_timestamp DESC");
$resultprice = mysql_fetch_assoc($getprice);
$price = $resultprice['b_currentprice'];
?>
<html>
<head>
</head>
<body>
<div id="priceElement">
<?php echo $price; ?>
</div>
</body>
</html>
(auction.php?auc=123) - This is the page that displays the auction. The page that I will need to return the current price.
<script type="text/javascript">
function updateBids() {
//I have left out the date/time just to keep it simple for now
var url = "getprice.php?id=<?php echo $id; ?>";
jQuery("#priceElement").load(url);
}
setInterval("updateBids()", 1000);
</script>
Is there something I am missing? E.g. Is there something else I need to include on the client-side to display the updated price?
Thanks again,
Nonshatter
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if (!$username or !$password) {
echo 'make sure you entered the required fields';
exit(0);
}
$query = "SELECT password FROM table WHERE userId = '$username'";
$dbarray = mysql_fetch_array($query);
if ($password == $dbarray['u_passwd']) {
echo 'Password match';
} else {
echo 'Password Fail';
exit(0);
}
?>
You will probably want to increase the security of your login script by using encryption and other validation... But let's do it one step at a time!
Is there a way to GET the ID=1 from the URL
$urlid = $_GET['id'];
$query = mysql_query("UPDATE memberst SET counter='$counter' WHERE id='$urlid'");
Something like this?
Do you have
<?php session_start(); ?>
at the top of your pages?
Hi all,
I have a been developing an Online auction website using PHP and Mysql for the last few weeks. I have implemented everything including the 'bidding', 'buy it now' options of the auction etc.
I don't know much about AJAX to be honest, but I think it is the technology I need for this... My requirement is to devise a way of updating (in real-time) the current price of a particular auction product as more and more users bid on the item. Once a user bids on the item, the bid table of the database is updated with the highest bidders price. So once this value changes in the database, would it be possible to update the price on the webpage? Obviously, it is important for this update to be as accurate as possible to maintain the integrity of the auction.
Does anyone know of a method or technique to achieve a similar functionality? ANY help is much appreciated!
Thanks,
Nonshatter
Beautiful... Consider it solved!
Hey, thanks for the rapid reply. I'm still not getting the correct result though...
It only echoes "Your search terms returned '' results". It doesn't want to print out whatever is in {$cnt[0]} Any thoughts?
Thanks again
Hi all,
I have just made a search bar for a site but I am having trouble trying to return the number of results that are found.
E.g. I want it to print "Your search terms returned 'xx' results" after each search.
This is my code:
<?php
include ('db.php');
if (isset($_POST['search'])) {
$searchterm = $_POST['searchterm'];
$searchcat = $_POST['searchcat'];
$searchterm = trim($searchterm);
if (!$searchterm && !$searchcat) {
echo 'no search terms entered';
exit;
}
$getresults = mysql_query("SELECT * from auctions WHERE a_title LIKE '%".$searchterm."%' OR category_id = '$catid'");
$i=0;
while ($i < 10 and $matches = mysql_fetch_assoc($getresults)) {
//return number of matches &
//display results here...
}
?>
Thanks, Nonshatter
Hey Lloyd. You're on the right track. However, from a quick glance, it looks as though your sql statement is causing you problems. This is how I would do it:
<?php
$id = $_SESSION['id'];
$id = addslashes($id);
$sql=mysql_query("SELECT * FROM memberst WHERE id='$id'");
$result=mysql_fetch_assoc($sql);
$counter = $result['counter'];
if ($counter == 0) {
$counter = 1;
$sql1= mysql_query("UPDATE memberst SET counter='$counter' WHERE id='$id'");
} else {
$addcounter=$counter+1;
$sql1=mysql_query("UPDATE memberst SET counter='$addcounter' WHERE id='$id'");
}
?>
Not sure if this will work exactly as you want it, but give it a go and get back to me. All the best,
Nonshatter
Hi,
I have never used table locking before. Would something like this be sufficient? Basically I want to only allow exclusive write access to the bid table:
<?php
$query = "LOCK TABLES bid WRITE";
$placebid = mysql_query("INSERT INTO bid (auction_id, seller_id, bidder_id, b_timestamp, b_currentprice) VALUES ('$id', '$uid', '$ruid', NOW(), '$bidprice')");
$query = "UNLOCK TABLES";
if (!$placebid) {
die ('Invalid Bid Query' . mysql_error());
}
?>
A) Does this syntax look correct?
B) Would this actually work? e.g. only allow exclusive write access?
C) Is there anything I am missing here?
Note:- I am using the InnoDB storage engine
Thanks,
Nonshatter
Hi all,
I'm need to devise a server-side method of preventing multiple form submissions. The form is submitted to the same page. I have read about generating a unique value in a session and insert a hidden input field to detect multiple submits, but would this work with a same-page form handler? Here is my code:
<?php
if (isset($_POST['flagged'])) {
$getflag = mysql_query("SELECT a_flagged FROM auctions WHERE a_id = '$id'");
if(!$getflag) {
die('Flag Query failed: ' . mysql_error());
}
else {
$resultflag = mysql_fetch_assoc($getflag);
}
$addflag = 1;
$timesflagged = $resultflag['a_flagged'] + $addflag;
}
$updateflag = mysql_query("UPDATE auctions SET a_flagged = '$timesflagged' WHERE a_id = '$id'");
?>
<form name="flag" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<input type="image" name="flagged" value="flagged" src="/ece60363/images/arrow.gif"
height="20px" width="20px" alt="Submit button"> Flag bad auction
Any ideas are welcome.
Thanks,
nonshatter
Is there an alternative way to send the words in the textarea to another page without using a form and submit button?
Yes, you can use a PHP Session:
Grab text from textarea and put it into a session:
<textarea name="text"> </textarea>
<?php
$texttosend = $_POST['text'];
$_SESSION['textareatext'] = $texttosend;
?>
Print it out on the next page:
<?php echo $_SESSION['textareatext'] ?>
Something like this should work... but not sure
Dude,
You cannot post pages of code and expect us to solve it for you. If it's your 'job' to fix websites you should at least know how to troubleshoot a mysql error. I'm no expert, but the mysql error you posted literally tells you where the problem is occuring. Does "near 'Comic Sans MS\"\">Crystal Spring Minerals affiliate" not give you a hint?
Yes, you will need to do the same for all fields that are of FLOAT type. Make sure you compare the field with the data that's being inserted into the table.
From what I can see, all the data being entered into the courier field is of integer type. Whereas the price and total fields are float.
Great! Thanks for your responses. I will have play around with what was suggested and get back to you. Thanks.
What features does PHP/MySQL provide to deal with concurrent systems?
E.g, If I have a table, and I only want to allow one user to update at any one time. I want to put a lock on the database until the update is complete, then once that request is processed, unlock the database and allow another user to update?
`courier` float NOT NULL default '0',
Needs to be:
`courier` float(4,2) NOT NULL default '0',
Or however many digits you want each side of the decimal point. E.g. Float (2,2) is a number like 23.96 or Float(4,7) gives a number like 1234.1234567
Or it could be that you don't need to have a Float data type at all. It depends what data needs to go in that field!
Okay..... I will look into the PHP timer and get back to you. However, how do websites like Ubid manage do it?
Would you care to tell us:
a) Where you got this from
b) Why you want it decoded
Ardav,
Thanks for your reply. To be honest, I am new to JavaScript and have only been learning PHP for the last 2-3 months, so I apologise if I my understanding is not up to scratch. The functionality I am trying to achieve is to have a countdown timer for each record that is retrieved from the database.
The countdown script I am using is publicly available from this site. It was the only script I found whereby I could format and 'plug-in' my own values from a database.
If I was to place the Javascript in the head section, is there a way I could 'call' the countdown clock within the while loop to dynamically display the countdown for each record retrieved??
Your advice is much appreciated.
Regards,
Nonshatter
Hey guys,
Sorry if I am cross-posting, but I can't seem to find a solution to this problem. I have a PHP while loop that retrieves records from my database. Inside the loop, I also have a Javascript counter that I need to generate for each record I retrieve (for each iteration). However, the counter only works for one record (i think it's the last iteration of the while loop). I'm guessing it's to do with a clash between the client-side javascript and the server-side php.
Can anyone confirm this or tell me if there is a work around? Many thanks.
<?php
$request = mysql_query("SELECT * FROM auctions WHERE category_id BETWEEN '12' AND '84' ORDER BY a_timestamp DESC");
$i = 0;
while ($i <= 6 and $result = mysql_fetch_assoc($request)) {
$time = $result['a_timestamp'];
$length = $result['a_length'];
$expires = strtotime($time. '+' .$length. 'days');
$expires = date('m/d/Y g:i A',$expires);
?>
<table border="0" cellpadding="5px">
<tr class="shade1">
<td rowspan="3" height="50px" width="50px">
<?php echo "<img src=https://students.ee.port.ac.uk/ece60363/".$result['a_image'] ." height=70px width=70px>"; ?>
</td>
<td class="error">Buy it Now price: £<?php echo $result['a_buyitnow']; ?></td>
<td class="error">Current Price: £</td>
<td class="error">
Time Remaining:
<!--------THIS ONLY WORKS ONCE, RATHER THAN EACH ITERATION---------->
<script language="JavaScript">
TargetDate = "<?php echo $expires; ?>";
BackColor = "";
ForeColor = "";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days %%H%% Hrs %%M%% Mins %%S%% Secs";
FinishMessage = "Auction Ended!";
</script>
<script language="JavaScript" src="/ece60363/count.js"></script>
</td>
</tr>
<tr class="shade2">
<td colspan="2"><a href="/ece60363/auction.php?auc=<?php echo $result['a_id']; ?>">
<?php echo $result['a_title'];?></a> …
Okay, my apologies for my dull moment! I think this is to do with the fact that PHP is sending the request (server-side), and the Javascript (client-side) is only taking the value last generated from the while loop.
Can anyone confirm this? Does anyone know a work around?
Many thanks
Hi all,
Is it possible to use the same javascript code in a while loop? The first record that is pulled from the database displays the javascript counter. Yet on the second iteration of the while loop (a new record pulled from the database), the javascript just seems to get ignored by php. Here is the section of code:
<?php
$request = mysql_query("SELECT * FROM auctions WHERE category_id BETWEEN '12' AND '84' ORDER BY a_timestamp DESC");
echo '<h1>'.$_GET['ctg'].' auctions</h1>';
$i = 0;
while ($i <= 6 and $result = mysql_fetch_assoc($request)) {
$time = $result['a_timestamp'];
$length = $result['a_length'];
$expires = strtotime($time. '+' .$length. 'days');
$expires = date('m/d/Y g:i A',$expires);
?>
<table border="0" cellpadding="5px">
<tr class="shade1">
<td rowspan="3" height="50px" width="50px">
<?php echo "<img src=https://students.ee.port.ac.uk/ece60363/".$result['a_image'] ." height=70px width=70px>"; ?>
</td>
<td class="error">Buy it Now price: £<?php echo $result['a_buyitnow']; ?></td>
<td class="error">Current Price: £</td>
<td class="error">
Time Remaining:
<script language="JavaScript">
TargetDate = "<?php echo $expires; ?>";
BackColor = "";
ForeColor = "";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days %%H%% Hrs %%M%% Mins %%S%% Secs";
FinishMessage = "Auction Ended!";
</script>
<script language="JavaScript" src="/ece60363/count.js"></script>
</td>
</tr>
<tr class="shade2">
<td colspan="2"><a href="/ece60363/auction.php?auc=<?php echo $result['a_id']; ?>">
<?php echo $result['a_title'];?></a>
</td>
<td>Quantity Remaining: <?php echo $result['a_quantity']; ?></td>
</tr>
<tr class="shade1">
<td colspan="6" rowspan="2"><?php echo $result['a_description'];?></td>
</tr>
<tr>
</tr>
</table>
<hr>
<?php
$i++;
}
?>
Any thoughts???
Hey,
You can make a database request based on what the user enters in your login form. For example, if the user enters their username to login, you could say something like:
// Get Username from login form. This could be an email address or
// another type of login information...
$loginname = $_POST['NameofLoginField'];
$query = "SELECT * FROM users WHERE username = '$loginname'";
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
//use result
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
Hope that helps
So presumably you want PHP of:
$expires = date('m/d/Y g:i A',$expires);
You're dead right! I realised I was using the wrong format after I posted, I was then trying to use 24 hour format which wasn't being interpreted properly:
$expires = date('m/d/Y G:i A',$expires);
However, the 12 hour format you suggested works great.
Another question... What is the PHP function used to get the server time?
Thanks for your help. :icon_cheesygrin:
Hey,
I have been trying to devise a way to insert a formatted PHP date() variable ($expires) into a publicly available javascript countdown clock. Obviously, this is made difficult because PHP is server-side and Javascript is client-side. This first piece of code is me adding a number of days to a timestamp to find out the expiry/target date for the counter. The second piece is the javascript counter.
<?php
include ('db.php');
$query = mysql_query("SELECT * FROM test WHERE id = '1'");
$result = mysql_fetch_assoc($query);
$time = $result['timestamp'];
$length = $result['length'];
echo $time; //PRINTS 2010-04-30 22:10:42
$expires = strtotime($time. '+' .$length. 'days');
$expires = date('Y-m-d H:i:s',$expires);
echo $expires; //PRINTS 2010-05-05 22:10:42
?>
/*
Author: Robert Hashemian
http://www.hashemian.com/
You can use this code in any manner so long as the author's
name, Web address and this disclaimer is kept intact.
********************************************************
Usage Sample:
<script language="JavaScript">
TargetDate = "12/31/2020 5:00 AM"; //<---------$EXPIRES NEEDS TO GO HERE
BackColor = "palegreen";
ForeColor = "navy";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
FinishMessage = "It is finally here!";
</script>
<script language="JavaScript" src="http://scripts.hashemian.com/js/countdown.js"></script>
*/
function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "<b>" + s + "</b>";
}
function CountBack(secs) {
if (secs < 0) {
document.getElementById("cntdwn").innerHTML = FinishMessage;
return;
}
DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000));
DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));
DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));
DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));
document.getElementById("cntdwn").innerHTML …
Thanks for your response fxm.
Have you used this script before? I have never used JQuery - How exactly does this all work? I'm a little bit confused... If I have my html page with the <div> sections, along with the jQuery script, how could I 'plug-in' the 'time remaining' values from my database and let the user synchronise with my server time? Also, what is JSON data? Are you able to elaborate a little more on this?
Thanks
<html>
<head>
</head>
<body>
<div id="imclock"></div>
<div id="time_href" style="display:none">http://url.to.time.inJSON</div>
</body>
</html>
<script type="text/javascript">
$(function(){
$('#imclock').imclock();
});
(function($) {
$.fn.imclock = function(options) {
var settings = jQuery.extend({
name: "defaultName",
size: 5
}, options);
var version = '1.4.0';
return $.fn.imclock.start($(this), null);
};
// TODO 2: sepparate time setting interval and clock starting
$.fn.imclock.start = function(element, time) {
if (time == null)
{
var time = $.fn.imclock.getServerTime(element);
}
else
{
time.setSeconds(time.getSeconds() + 1);
}
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
if (minutes<10) {
minutes = '0' + minutes;
}
if (seconds<10) {
seconds = '0' + seconds;
}
element.html(hours+ ":" + minutes + ":" + seconds);
element.timerID = setTimeout(function(){$.fn.imclock.start(element, time);},1000);
};
// This is the function that gets the actual time from the server
// time is expected to be returned as JSON data in field named "time"
// For example the request could look like this:
// {
// some_data: "lorem",
// time : 2010-12-12T12:23
// }
$.fn.imclock.getServerTime = function(element) { …
Thanks,
I know there are an abundance of javascript countdown clocks available on the web. I think I'm able to devise one, but my problem is that all my users must be syncronised to the same server (mysql server if possible?). Would this be achievable using PHP Javascript?
Thanks
Just to complicate things slightly more, my database structure is as follows:
c_id c_category c_parentid
1 Components NULL
2 Storage NULL
3 Monitors NULL
12 Processors 1
13 Motherboards 1
14 Memory 1
26 Internal Hard Drives 2
31 < 18" 3
32 19" > 20" 3
So, when i populate the first select box, I retrieve all the categories with c_parentid set as null. Then, depending on which category is selected I need to retrieve all the subcategories.
E.g:
If (Components is selected) {
SELECT c_id, c_category FROM category WHERE c_parentid = '1';
elseif (Storage is selected) {
SELECT c_id, c_category FROM category WHERE c_parentid = '2';
} elseif (etc..............)
I just need a way of determining what value has been selected by the user. Can someone please shed some light on this for me? Your advice is much appreciated!
nonshatter
x
Sorry, I've just managed to solve it, even though i'm not sure what the problem actually was! Typical.
I re-made the Sell table. I also changed the ID data types to int(11) and removed the 'unsigned' attribute from both. I then followed this tutorial:
http://www.learnphp.org/tutorials/Setting-Up-Foreign-Keys-Using-PhpMyAdmin-63466.html
I hope that helps if anyone else has a similar problem.
Hey,
I am having a really annoying problem when trying to set up a foreign key in my database... I have two tables - Sell and Category
I want the 'c_id' from the Category table to be the foreign key for 'p_id' in the Sell table. Both tables are InnoDB and both fields are the same datatype. Here is the query and the error:
ALTER TABLE `sell` ADD FOREIGN KEY ( `p_id` ) REFERENCES `ece60363`.`category` (
`c_id`
);
MySQL said: Documentation
#1452 - Cannot add or update a child row: a foreign key constraint fails (`ece60363/#sql-1f3b_937c`, CONSTRAINT `#sql-1f3b_937c_ibfk_1` FOREIGN KEY (`p_id`) REFERENCES `category` (`c_id`))
Category table:
c_id smallint(5) unsigned NO PRI NULL auto_increment
c_category varchar(50) YES NULL
c_parentid smallint(5) unsigned YES NULL
Sell table:
p_id smallint(5) UNSIGNED No auto_increment
//other fields
Hey guys,
I have this code which grabs categories from my category table of the database and populates the category drop-down box. I was hoping someone could tell me how I could populate the second drop-down box depending on what was selected in the first box.
E.g. If "Networking" is selected in the first box, then the second drop-down displays the subcategories of networking such as "wireless", "bluetooth" etc. Is it possible to do this in PHP alone? Or would I need to use javascript? How can I achieve this functionality?
Thanks
<?php
require ('db.php');
$query = "SELECT c_id, c_category FROM category WHERE c_id BETWEEN '1' AND '11'";
$result = mysql_query($query);
$options= "";
while ($row=mysql_fetch_array($result)) {
$ctgid = $row["c_id"];
$category = $row["c_category"];
$options.="<option value = \"$ctgid\">".$category."</option>";
}
?>
<html>
<head>
</head>
<body>
<select name="category" size="10px">
<option value="">--Select a Category--
<?= $options ?>
</select>
<select name="subcategory" size="10px">
<option value="">--Select a Subcategory--
<?= $options ?>
</select>
</body>
</html>
Hey guys,
I am in need of a live real-time clock to count down to zero depending on the length of days specified in a database (Like an auction count-down timer).
For example, I can retrieve the length of time specified in the database, somehow put that value into the clock and then let the timer count down to zero. Is there a particular scripting language I should be using for this E.g. Javascript/AJAX etc? Does anyone know the best way to achieve this sort of functionality?
Your advice is much appreciated. Many thanks,
nonshatter
Perfect. Thanks for your help!
:icon_cool:
Hey guys,
I am really close with this but can't quite get it right... All I am trying to do is retrieve the users details based on their 'u_id' and display them.
<?php
require ('dbconnect.php');
$user = $_SESSION['username']; //Get the users username
$requestuid = mysql_query("SELECT u_id FROM user_usr WHERE u_username = '$user'"); //Get the users u_id based on their username
$resultuid = mysql_fetch_assoc($requestuid);
echo $resultuid['u_id']; //THIS PRINTS THE USERS ID NO
?>
<table>
<tr>
<td>Gender:</td>
<td>
<?php
$request = mysql_query("SELECT u_gender FROM users WHERE u_id = '$resultuid'");
$result = mysql_fetch_assoc($request);
echo $result['u_gender']; //THIS DOESN'T PRINT THE USERS GENDER
?>
</td>
</tr>
</table>
In my head this should work, but I can't quite get it. Can anyone see where I'm going wrong?
Many Thanks,
Nonshatter
Why do you want the user to enter the user id? Shouldn't this be handled by an auto increment field in your database?
This is roughly how I would validate it...
<?php
function VerifyForm(&$values, &wrong) {
if (strlen($values['userid']) == 0) {
$wrong['userid'] = 'Enter your user id';
}
return (count($wrong) == 0);
}
?>
<html>
<head></head>
<body>
<?php
if (count($wrong) > 0) {
echo "There were some errors in your form...";
}
?>
<form action="#" method="post">
<table><tr>
<td>User id:</td>
<td><input type="text" name="userid" <?php echo htmlentities($values['userid']) ?>></td>
<td class="wrong"><?php echo $wrong['userid'] ?></td>
</tr></table>
</form>
</body>
</html>
What if the data is hardcoded? Basically the user specifies their product details, then clicks submit, the form data is then posted back to itself on the same page to be validated (server-side). If errors are detected, then I want the fields to be re-populated with the users session data... Simples?
My attempt:
<td>Condition:</td>
<td><select name="condition" <?php echo htmlentities($values['condition']) ?>>
<option value="">--Condition--</option>
<option value="new">New</option>
<option value="used">Used</option>
<option value=""><?php echo $_SESSION['sellform']['condition']?></option>
</td>
I've got it working for all input fields except for drop-down boxes.
Thanks in advance
Hey,
I have a combo box and want to populate it with the selected value upon page reload. For a normal text field I would usually do something like this:
<input type="text" name="title" value="<?php echo $_SESSION['sellform']['title']; ?>">
How could I do the same for a drop-down box? E.g:
<select name="condition">
<option value="">--Condition--</option>
<option value="new">New</option>
<option value="used">Used</option>
</select>
I have found the problem...
It was with with this validation regular expression for telephone number:
if (!filter_var($values['telephone'], FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => "/^0[1-9][0-9]{8,9}$/")))) {
$error['telephone'] = 'Invalid number';
}
Thanks anyway
nonshatter
Hey guys,
I have reached my wits end with this..! This code works on two of the servers that I have tested, but doesn't want to work on the third server that I need it on! It displays fine, but when the form data is posted back itself to be validated, I get a blank page - No error messages or clues as to what may be causing the problem.
<?php //session_start();
//THIS FUNCTION VALIDATES ALL USER INPUT
function VerifyForm(&$values, &$error) {
if (strlen($values['title']) == 0) {
$error['title'] = 'Please specify your title';
}
if (strlen($values['firstname']) == 0) {
$error['firstname'] = 'Please Enter a name';
}
if (strlen($values['surname']) == 0) {
$error['surname'] = 'Plese Enter a surname';
}
if (strlen($values['address1']) == 0) {
$error['address1'] = 'Please enter the first line of your address';
}
if (strlen($values['address2']) == 0) {
$error['address2'] = 'Please enter you street name';
}
if (strlen($values['city']) == 0) {
$error['city'] = 'Please enter your town/city';
}
if (strlen($values['postcode']) == 0) {
$error['postcode'] = 'Please enter your postcode';
}
elseif (strlen($values['postcode']) < 6) {
$error['postcode'] = 'Specified Postcode is too short';
}
elseif (!preg_match("/^([Gg][Ii][Rr]0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))){0,1}[0-9][A-Za-z]{2})$/",$values['postcode'])) {
$error['postcode'] = 'Invalid postcode entered';
}
if (strlen($values['county']) == 0) {
$error['county'] = 'Please enter your county';
}
if (strlen($values['region']) == 0) {
$error['region'] = 'Please select a region';
}
if (strlen($values['telephone']) == 0) {
$error['telephone'] = 'Please enter a contact telephone number';
}
elseif (strlen($values['telephone']) < 11) {
$error['telephone'] = 'telephone number too short';
$values['telephone'] = ereg_replace('[^0-9]', '', $_POST['telephone']);
}
if …
Yes, this is possible through the use of sessions.
Have a look here:
http://php.about.com/od/advancedphp/ss/php_sessions.htm
Solved...
"The special output version, which looks like this:
<?= [output here] ?>
This is the same as writing:
<?php echo "some output"; ?>
If you ever change to another server, the short or special output version options may be disabled."