Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
I think you are missing how a switch works. The value in the constructor is compared to the values in the case statements. So, with this: switch($magnitude) { case $magnitude >=0 && $magnitude <=0.9: $magScale = 'rgb(195, 218, 236)'; break; // . . . The first case statement is checking if $magnitude (in the constructor) is equal to the result of ($magnitude >=0 && $magnitude <=0.9). That would be the same as the following if() condition if($magnitude == ($magnitude >=0 && $magnitude <=0.9)) { What you are wanting is for the case statement to be evaluated to see if it is true or not. So, you need to put TRUE into the switch constructor. You can do that like this: switch(TRUE) { case $magnitude >=0 && $magnitude <=0.9: $magScale = 'rgb(195, 218, 236)'; break; case $magnitude >=1 && $magnitude <=1.9: $magScale = 'rgb(210, 238, 197)'; break; case $magnitude >=2 && $magnitude <=2.9: $magScale = 'rgb(244, 240, 202)'; break; case $magnitude >=3 && $magnitude <=3.9: $magScale = 'rgb(244, 223, 202)'; break; case $magnitude >=4 && $magnitude <=4.9: $magScale = 'rgb(240, 199, 205)'; break; case $magnitude >=5 && $magnitude <=20: $magScale = 'rgb(212, 195, 236)'; break; } FYI: There are gaps in the logic with the comparisons. For example, the first one is $magnitude >=0 && $magnitude <=0.9 And the second is $magnitude >=1 && $magnitude <=1.9 What if the value os >0.9 and less than 1? The logic should be changed to: switch($magnitude) { case $magnitude >=0 && $magnitude <1: $magScale = 'rgb(195, 218, 236)'; break; case $magnitude >=1 && $magnitude <=2: $magScale = 'rgb(210, 238, 197)'; break; case $magnitude >=2 && $magnitude <=3: $magScale = 'rgb(244, 240, 202)'; break; case $magnitude >=3 && $magnitude <=4: $magScale = 'rgb(244, 223, 202)'; break; case $magnitude >=4 && $magnitude <=5: $magScale = 'rgb(240, 199, 205)'; break; case $magnitude >=5 && $magnitude <=20: $magScale = 'rgb(212, 195, 236)'; break; }
-
COUNT NUMBER OF TIMES A VALUE OCCURES IN ARRAY
Psycho replied to sanlike's topic in Application Design
Start with this: http://php.net/manual/en/function.array-count-values.php Also, you state this is an array, but then have the comment That seems to indicate this is from a DB query. If so, the solution is to add the logic in the query.- 1 reply
-
- count
- multidimensio
-
(and 2 more)
Tagged with:
-
@brodinsky, Most of us who regularly help do not mind helping people with their homework, but we expect that people will at least make an attempt. Write some code, then come back and explain what specific problems you have.
-
What happens if two people submit at the same time?
Psycho replied to greenace92's topic in PHP Coding Help
Do not use IP address. That is a bad idea. As mac_gyver stated use the last insert id. User submits the initial information to create an account. Run the INSERT query. Then, right after you run the INSERT query get the "last insert id" using the appropriate database function (e.g. http://php.net/manual/en/mysqli.insert-id.php). The function will get the last insert ID executed in the current instance. Do NOT try to get the last insert id using a SELECT query for the highest id as that would be open to race condition issues. Once you have the id of the last inserted record, you can save the id to a session value and use it on subsequent pages. -
Tom, You need to take a step back and understand what the code is doing. Yes, you define $row in the select user page. First of all, every page request to the server is a new process. After each page is completed processing, and data help in memory is released. Variables don't persist from one request to another. Second, although $row is defined in that page, it is redefined as each record is processed. So, when the script is done executing, it only holds the values of the last record. So, what would make you think that if the user selects the first record, that $row (even if it was saved in memory) would hold the content of the first record. You pass the ID so, you have an identifier to pull the necessary data from the database. Also, I'm pretty sure this won't work as you expect. if(empty(trim($newp))) { You need to trim the value and put into a variable - then check if it is empty. $newp = trim($newp); if(empty($newp)) {
-
If the string values for the categories are consistent, this is a very easy operation: two queries and one alter. First, run one query to populate the non-numeric categories from the book table into the category table INSERT INTO category (cat_name) SELECT DISTINCT category FROM book WHERE ABS(category) = 0 Next update the category field in the book table to the numeric ids from the categories that were just added UPDATE book b JOIN category c ON b.category = c.cat_name SET b.category = c.id Lastly, change the category field in the book table to be an INT type field. ALTER TABLE book CHANGE category category INT NOT NULLE
-
Tom, Exactly what coding have you done previously? I have a feeling you have dove very little PHP coding, especially with using a database. We're happy to help, but this forum is primarily for people to get help with code they have written. I get the feeling this thread is going to turn into a tutorial on basic programming logic. But, I'll be generous and give you a basic example. If you don't understand this, then you really need to do some work to learn the basics. But, definitely come here when you have specific questions. selectUser.php (create a list of users as links to edit them) $sql = "SELECT user_id, user_name FROM users ORDER BY user_name"; $result = $mysqli->query($sql); while ($row = $result->fetch_assoc()) { echo "<a href='editUser.php?id={$row['user_id']}'>{$row['user_name']}</a><br>\n"; } editUser.php (Page to display data about a user and edit them $userID = $_GET['id']; //Run query using the user ID to get their current attributes and provide controls to edit
-
Have you verified that $stmt is an object and that it has properties for errno and error before you pass it to the function? function chk_error($site_mode, $obj) { if( $site_mode == 'dev' ) { echo'Error : ('. $obj->errno .') '. $obj->error; } } var_dump($stmt); //Let't verify what $stmt is and what it contains chk_error($site_mode, $stmt);
-
You're on the right track. You need to implement a JavaScript timer that then makes an AJAX call to get the new data and then writes that new data into the DIV. There's too much to cover in a forum post, but there are plenty of tutorials out there. I will give you this advise however. You should not put the code to create the div content into the page like this <div class="score1" id="score1"> <?php mysql_select_db(scoredb) or die ("Couldn't not find DB"); $query = mysql_query("SELECT * FROM results ORDER BY IDResults DESC 1 "); while($row = mysql_fetch_assoc($query)) { $player1 = $row ["Player1"]; $score1 = $row ["Score1"]; $player2 = $row ["Player2"]; $score2 = $row ["Score2"]; echo $player1" . " " . $scr1 . " " . " " . " - " . " " . $player2" . " " . $scr2 ; } ?> </div> instead, you should create a separate PHP script to create the content. That way you can call that script when you first build the page and you can call the same script when you make the AJAX request to get the updated content. E.g. getScores.php <?php mysql_select_db(scoredb) or die ("Couldn't not find DB"); $query = mysql_query("SELECT * FROM results ORDER BY IDResults DESC 1 "); while($row = mysql_fetch_assoc($query)) { $player1 = $row ["Player1"]; $score1 = $row ["Score1"]; $player2 = $row ["Player2"]; $score2 = $row ["Score2"]; echo $player1" . " " . $scr1 . " " . " " . " - " . " " . $player2" . " " . $scr2 ; } ?> Then in your main page your div would look like this <div class="score1" id="score1"> <?php include('getScores.php'); ?> </div> Then in the JavaScript that makes the AJAX call you would call the same file getScore.php to get the new data.
- 4 replies
-
- timer
- scoreboard
-
(and 1 more)
Tagged with:
-
Using a hidden field with a "token" is fine if the user is recreating the form and submitting it directly, but it still has gaps. It is very easy to use a tool like Fiddler to capture requests from the browser and edit the data before allowing the request to go out to the server. A hidden field holding a token to tie the request to the session would do nothing to prevent such a modification. To put it simply you can NEVER trust any data being supplied from the user. For a select list, you should have logic to create the list of valid values. You need to re-purpose that logic to verify if the submitted value is valid. If you build your select list from a DB query, then you should run a query to see if the submitted value is in the DB. If the list is "fixed" I would suggest creating an array of the values. Use that array to build the list and use the same array to verify the submitted value. If coded properly, you should not need to modify code to add/edit/remove values from a select list to update the list or to verify the values. you should just need to update the DB, edit an array, etc. and it should all just work.
-
I don't really understand what you are trying to accomplish. But, you cannot have dynamic content with only HTML & CSS. PHP is only dynamic on the server. In other words, PHP generates the content (which can be variable) and then send the whole thing to the browser. If you want to have content be dynamic after the page has been received from the server, you will want to use JavaScript
-
1. Don't use "SELECT *" if you don't need ALL the fields. Select only the fields you need. It puts overhead on the server that is unnecessary. 2. Lear to use JOINs - that is the whole point of a relational database. 3. Don't run queries in loops. There are very few instances where you need to run loops. Until you know when those are, look for a non looping solution (hint, this usually requires a JOIN). This should be all you need $sql = "SELECT m.* FROM musics m JOIN playlists p ON m.playlist_id = p.id WHERE p.user_id = :id"; $query = $con->prepare($sql); $query->execute(array("id" => $userID)); $songs = $query->fetchAll(PDO::FETCH_ASSOC); $key['musics'] = $songs;
-
This should do what you need in a much more efficient manner $sql = "SELECT Opposition, DATE_FORMAT('%d-%b-%Y', match_date) as match_date, MONTH(match_date) as month, competition, tbl_clubs.club_name AS club, image, HomeAway, team, opposition_points, points FROM tbl_fixtures INNER JOIN tbl_clubs ON tbl_fixtures.club = tbl_clubs.club_id WHERE season_id = $current_season and MONTH(match_date) = $month UNION SELECT Opposition, DATE_FORMAT('%d-%b-%Y', match_date) as match_date, MONTH(match_date) as month, 'SGP' AS competition, 'SGP' AS club, 'sgp.png' AS image, '' as HomeAway, '' as team, '' as opposition_points, points FROM tbl_gp WHERE season_id = $current_season and MONTH(match_date) = $month ORDER BY match_date"; $result = mysqli_query($dbConn,$sql)or die(mysqli_error($dbConn)); if(mysqli_num_rows($result)) { $currentMonth = false; while($row = mysqli_fetch_assoc($result)) { //Check if month has changed if($currentMonth != $row['month']) { //Close previous fixture table if not first record if($currentMonth) { echo " </table>\n"; echo "</div>\n"; } //Open new fixture table echo "<div class='fixtureMonth'>\n"; echo " <h2>{$months[$row['month']]}</h2>\n"; echo "</div>\n"; echo "<div class='fixtures'>\n"; echo " <table class='fixturesTable'>"; //Set current month to new value $currentMonth = $row['month']; } //Display fixture record echo "<tr>\n"; echo "<td>{date("d-M-Y",strtotime($row['match_date'])}</td>\n"; echo "<td><img src='{$shopConfig['url']}images/{$row['image']}'></td>\n"; echo "<td>{$row['Opposition']}</td>\n"; echo "<td>{$row['HomeAway']}</td>\n"; echo "<td><b>{$row['team']}</b>-{$row['opposition_points']}</td>\n"; echo "<td>{$row['team']}</td>\n"; echo "</tr>\n"; } //Close last fixture table echo " </table>\n"; echo "</div>\n"; }
-
Do NOT run queries in loops. You can run ONE query to get all the data you need. Anyway, your problem is that you are reusing variables $results & $row in processing the queries and they are being overwritten. if(mysqli_num_rows($result)>0) { while($row=mysqli_fetch_assoc($result)) { $result=mysqli_query($dbConn,$sql)or die(mysqli_error($dbConn)); echo '<table class="fixturesTable">'; while($row=mysqli_fetch_assoc($result)) { } }
-
@Barand, If I understand the requirements correctly, each group number should have exactly 5 records, except for the last group number which will have from 1-5 records (based on the total number). I don't believe the query you've provided has any logic to enforce the distribution in that manner.
-
ORDER BY RAND() is highly discouraged. If you have a small amount of data and it is not being run on page requests by users you can probably get away with it. But, it builds bad habits. Getting more than 1 'random' row from MySQL is not a simple task as you've found. I have an idea that should work, although others may have a better idea. 1. Insert a random number into all the records with a single query. This value will be less than 1, e.g. 0.79399610850401 2. Create a loop with an incrementing value starting at 1. In that loop run a query to UPDATE 5 records using the random value above as the ORDER BY and in the WHERE condition. Continue the loop as long as there are affected rows Sample code //Update team values to random number $sql = "UPDATE players SET team = RAND()"; $mysqli->query($sql); //Create var to hold team number $teamNo = 0; do { //Increment team number $teamNo++; //Run query to update 5 rows based on random value $sql = "UPDATE players SET team = {$teamNo} WHERE team < 1 ORDER BY team LIMIT 5"; $mysqli->query($sql); //Continue loop as long as there were rows updated } while($mysqli->affected_rows); I hate running queries in loops, but don't see a good way to do this otherwise. You would have performance issues if you were to have a LOT of data.
-
I am not going to read and analyze all of your code and write it for you, but I will provide the basis for a solution. As I understand it, you want the page to load the current month/year by default with the ability to paginate by months. So, you can simply find any "normal" pagination script as the basis. Then each "page" is calculated as the current month - (page-1) months. One challenge is in calculating the Total Pages. You could get the oldest data and calculate how many months it is from the current month. But, if there are any empty months, you could have pages with no records. if that is possible, and you don't want empty pages, then you would have to run a query to get the count of months with data. Rough example: Logic to determine the parameters to get the selected "page" display //Pass normal page numbers, 1, 2, 3, ... $page = intval($_GET['page']); //Determine the month offset, from current month, based on page selected $monthOffset = $page-1; //Get a timestamp for the selected month $pageDate = strtotime(" -{$monthOffset} months"); //Determine the month & year of the selected month $year = date('Y', $pageDate); $month = date('m', $pageDate); Query to get the data $query1 = "SELECT id, Date, User, Team, Transfer_Number, Agent_Name, Cell_Phone, Customer_Name, Customer_Status FROM $tableName WHERE Customer_Status = 'Sale' AND YEAR(Date) = $year AND MONTH(Date) = $month ORDER BY id DESC LIMIT $start, $limit";
-
Wouldn't the query without that condition include the records for both? There shouldn't be a need for two queries. You could actually add a dynamic field to the output to indicate which ones meet the like query if needed.
-
<div style="margin:0px;"> <img src="1.jpg"> </div> <div style="margin:0px; float: right;"> <img src="2.jpg"> </div> <div style="margin:0px;"> <img src="3.jpg"> </div> <div style="margin:0px; float: right;"> <img src="4.jpg"> </div>
-
Don't use "float" on ALL elements in a "row" at least one should not have a float on it to act as the 'anchor'. There are multiple ways to accomplish what you want, but similar to what you have, this is one <div style="margin:0px; float: left;"> <img src="1.jpg"> </div> <div style="margin:0px;"> <img src="2.jpg"> </div> <div style="margin:0px; float: left;"> <img src="3.jpg"> </div> <div style="margin:0px;"> <img src="4.jpg"> </div>
-
The OP did not ask about "creating" a record and ensuring that the username does not already exist. He asked about verifying that a username does not exist. Many sites implement an AJAX call to check a username after the user enters the value in a form, but before they have submitted the form. So, yes, what I provided was a perfectly acceptable solution for what was asked.
-
Are you wanting to check if a username "exists" or are you trying to authenticate a user? If you are only wanting to know if the username exists, why does the query do a check on the password? To check if a username exists, I would do this SELECT id FROM table_name WHERE username = 'value_to_check' LIMIT 1 Then check if the number of rows returned is 0 or 1. Note that mysql_ extensions are deprecated and should not be used. Use either mysqli_ or PDO. Plus, you shoudl also use a prepared statement to guard against SQL Injection.
-
I think you are mixing up sanitizing and validation. People may argue on the actual terminology, but here is my explanation. Sanitizing is the process of escaping data that could otherwise cause errors (SQL Injection, XSS, etc.). Validation is the process of verifying data is appropriate for its intended use. For example, if you store a value for "age" a value of "blue" would not be valid. You could still store that value if you wish - proper sanitizing would likely convert it to a 0. What you are describing seems to be adding validation logic to prevent possible issue with sanitizing. You should always implement best practice around sanitizing data. Validation logic should be based upon the business rules. Not allowing special characters in a password is a horrible idea. Dictionary attacks primary focus on brute forcing "words". That is why people are encouraged to use 'complex' passwords: upper case, lower case, numbers & special characters. If you limit what can be used, then you are effectively reducing the possible combinations that would have to be used to try and infiltrate a users login.
-
Don't use '*' for your SELECT. Define the fields you actually need. Also, to add to mac_gyver's response, you should define $categoryanme = '' before the loop. But, I would actually use the id and not the name. Give this a try $categoryid = false; while($row = mysqli_fetch_assoc($result)) { //Detect if category has changed if ($categoryid != $row['categoryid']) { //If a previous category existed - close the div if($categoryid) { echo "</div>\n"; } //Create div for new category echo "<div class='category'>\n"; echo "<div class='h'><h2>{$row['categoryname']}</h2></div>\n"; } //create image div for current record echo "<div class='gall'>\n"; echo " <div class='gl-img'><img src='pathway/to/gallery/{$row['photoname']}'></div>"; echo " <div class='gl-cap'>{$row['photocaption']}</div>"; echo "</div>"; } //Close last div, if there were records if($categoryid) { echo "</div>\n"; }
- 2 replies
-
- php
- while loop
-
(and 1 more)
Tagged with: