Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
You haven't identified the tables to pull records from , i.e. the FROM clause for the query. SELECT Sum(points.promo) AS score, members.name FROM members JOIN points ON members.id = points.memberid Order By members.name ASC
-
This forum is to get help with code you have written. have you even attempted this?
-
Insert dynamic number of checked box values to database
Psycho replied to wright0768's topic in PHP Coding Help
I guess I wasn't clear when I stated Username and user_id (or whatever the primary key is) are not interchangeable. You should not be using the username field as the primary key. Your table should have an auto-incrementing int field (e.g. user_id) to use as the primary key as well as a username field for, well, the username. Look at the modification I made for the checkboxes. The script will still show the username as the label next to the checkbox, but the value will be the user_id. -
Insert dynamic number of checked box values to database
Psycho replied to wright0768's topic in PHP Coding Help
It works because you are implementing a workaround for a problem that shouldn't be there to begin with. You need to be using an int type field for user_id and I suspect you are using varchar or some other text variant. You did not solve the illness you only put a band-aid on a symptom. -
Insert dynamic number of checked box values to database
Psycho replied to wright0768's topic in PHP Coding Help
Why are you putting single quotes around $picklist? The user_id field should be a numeric field and the values from the POST data should be numeric as well. So, you don't need quotes around the values if you set up the database field correctly (should be an int type). Besides, if you did need quotes, you need them around each individual value not around the list of values. So, what type of field is "user_id"? -
Insert dynamic number of checked box values to database
Psycho replied to wright0768's topic in PHP Coding Help
Well, I told you I didn't test it. Hmm, I see an error in that query, but I wouldn't think it would display an error on the username. Well, It shouldn't display an error on the username anyway since I told you that you should be using the user ID. As I stated you need to replace the filed name 'user_id' with whatever you are using for the user id field. There are 2 instances in the queries and one instance in the PHP code. I have made a couple of corrections in the section below as well as added some additional debugging code in case the query fails again. if (isset($_POST['submit1'])) { $pickList = (isset($_POST["pick"])) ? implode(', ', $_POST["pick"]) : ''; echo "People chosen: {$pickList}<br><br>\n"; echo "<br><br>\n"; //Run query to update PICKED/UNPICKED records $query = "UPDATE users SET offer = IF(user_id IN ({$pickList}), 1, 0)"; $result = mysql_query($query, $connection); if (!$result) { die("Query: {$query}<br>Database query failed: " . mysql_error()); } } -
You are using a separate class for your queries, so I can't be sure. But, . . . are you sure about what is returned from $db->fetch_array()? If it is similar to mysql_fetch_array(), then it is returning an array with all fields associated by their field name AND with numerically based indexes. However, if that method does not return the values indexed by field name, then there is no value for "$data['id']". So, when you create the return array using while($data = $db->fetch_array()) { $this->_friends[$data['id']] = $this->get($data['id']); } The result of $data['id'] is 0, so each record is overwriting the last one. So you only get the last record when the loop is complete. Now, if $db->fetch_array() does returned results with named indexes then I think you need to double check the name of the id field. Are you positive it is 'id'? Make sure it isn't a different name or doesn't have a different case (i.e. "ID"). If the field name is not exactly the same then you would have the same problem as I described above.
-
Insert dynamic number of checked box values to database
Psycho replied to wright0768's topic in PHP Coding Help
OK, I have made many changes. I'll try to give you some details about what I did. Also, I didn't test since I don't have your database, so there may be some syntax errors. 1. Well, first off I was wrong. It doesn't require TWO queries - it only requires ONE that uses an IF() statement to set the value appropriately. 2. It looks like there is more code that you left off to handle when the gender is female. Assuming you are doing the exact same thing for females as males, having two sets of code to do the same thing is unnecessary. The code below will work for males and females based upon the selection. 3. I made an assumption as to the field name for the user ID. I used "user_id" - change it to the correct value in the queries and the php code that uses it. 4. I updated the logic for creating the checkboxes to automatically check the box for each record if the "offer" field is already true. if (isset($_POST['submit1'])) { $pickAry = $_POST["pick"]; echo "People chosen: {$pickAry}<br><br>\n"; echo "<br><br>\n"; //Run query to update PICKED/UNPICKED records $pickList = implode(', ', $pickAry); $query = "UPDATE offer SET offer = IF(user_id IN ({$pickList}), 1, 0)"; $result = mysql_query($query, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } } else { $gender = ($_POST['Gender'] != 'Male') ? 0 : 1; $limit = mysql_real_escape_string($_POST['limit']); echo "{$_POST['Gender']}<br />\n"; $query = "SELECT user_id, username, offer FROM users WHERE gender =\"{$gender}\" LIMIT 0, {$limit}"; $result = mysql_query($query, $connection); if (!$result) { die("Database query failed: " . mysql_error()); } echo "<form method=\"post\">\n"; while ($row = mysql_fetch_array($result)) { $checked = ($row['offer']==1) ? ' checked="checked"' : ''; echo "<input name=\"pick[]\" type=\"checkbox\" value=\"{$row['user_id']}\"{$checked}>\n"; echo "{$row['username']}<br />\n"; } echo "<input type=\"submit\" name=\"submit1\" value=\"Make Offer\" />\n"; echo "</form>\n"; } Here is an explanation of the query: UPDATE offer SET offer = IF(user_id IN ({$pickList}), 1, 0) It is an UPDATE query, obviously. It has NO WHERE clause so it will attempt to update all records (if the update value is different than the current value). The real trick in this query is where we set the value for "offer". Basically it says set "offer" equal to and then does a comparison: if the record's "user_id" is in the list of checked records sent in the POST data it sets the value to 1, else it sets it to 0. -
Insert dynamic number of checked box values to database
Psycho replied to wright0768's topic in PHP Coding Help
You NEVER want to run queries in loops. It is extremely inefficient and puts an unnecessary load on the server. The solution to your problem is very simple and only requires two total queries. Give me a few minutes and I'll post some sample code. EDIT: Can you show the field that you want updated and how it should be updated? Is it a tiny int that will be a 0 or 1? -
Just an FYI. If you need a function that is supposed to return a Boolean then it is not necessary to do something such as if($foo==$bar) { return true; } else { return false; } Just return the comparison. Using Pikachu's solution as an example: function checkName($name) { return (ctype_alpha( str_replace(array('-', ' ', '.'), '', $name)) ); }
-
To elaborate on my previous statement I may have a "master" controller file, but that does not mean it is my only controller file - it is simply the controller file that is first called. that way I have one file to put/include configuration data for my site. As an example, let's say my application has, among many different section, an administration area. In that area user's can work with different entities such as users, customers, products, etc. Then for any different type of entity there are different operations that can be performed. So, when the users selects a link or clicks a button. Ok, so now let's say a user brings up a page of products and clicks the link next to one to edit the product. That url may look something like this: mysite.com/admin/edit_product.php?id=123 Now, in that page "edit_product.php" I will set some variables for ($module='admin', $type='product', $action='edit', $id=123). Then I will include the "master" controller script. That master controller script is only looking for the $module variable. If it matches one of the available modules it includes that module controller script (else it includes the default, i.e. home page). Then on the controller file for the admin module it will check for the $type variable to determine with record type controller file to include and that page would perform the actions necessary based on the 'action' variable. This can go as deep or as shallow as makes sense for your application. Of course, this is my methodology - that works for me. Not saying it is the only way or the best way.
-
Plus, there is a significant difference between $i-- and --$i Per the manual (emphasis added): http://php.net/manual/en/language.operators.increment.php ++$a Pre-increment Increments $a by one, then returns $a. $a++ Post-increment Returns $a, then increments $a by one. --$a Pre-decrement Decrements $a by one, then returns $a. $a-- Post-decrement Returns $a, then decrements $a by one.
-
That won't work either as the ones you backquoted are not the problem. I checked the list of MySQL reserved words: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html It seems "read" is a MySQL reserved word. So, you will need to enclose that field name in backquotes But, let's just be really safe and do that to all of the field names $query = "SELECT `userIDTo`, `received`, `read`, `unread`, `sent`, `message` FROM `memberMail` WHERE `userIDFrom` = '92' AND `unread` = '1'";
-
A simple google search for something like "php file modification" would tell you that. I love helping people, but when someone asks me to do something that they can easily do themselves I get peeved.
-
Unless you create an automated process to interrogate the files and update the database with the file modified timestamp, you can't do this through a MySQL query. You will need to query the files, then when processing them add them to an array and at the same time get the modification time and add to the array as well. then you can order the array and finally output the data. However, if this is for a pagination script, this will not help you since you need to have the order of the files so you can get the correct files for the page using LIMIT. In that case you can either create an automated process to continually read the files and update the database OR you will have to query ALL the records, determine their modification dates, order them - in PHP - then use PHP code to determine which ones are for the current page. Neither option is a very good one.
-
Unless the 'State' field in the database is a numeric field, you need to enclose the search value in single quote marks. Your query is likely failing, add some error handling to your code so you can see errors when they occur. mysql_select_db("Kingsbury", $DBConnect); //Don't nee to add to a variable, since you don't use it $query = "SELECT * FROM contacts WHERE State = '$State'"; $queryresult = @mysql_query($query, $DBConnect); if(!$queryresult) { echo "Query: {$query}<br>Error: " . mysql_error(); }
-
I don't see anything wrong with that. I am not a moderator. I am merely someone who has participated on this board for many years and showed the ability to provide "good" solutions. There are many reason not to use '*' and I really didn't want to go into them in a forum post. But, since you both ask: Using the asterisk in your select query will return ALL the rows from the selected tables. If you aren't using all the rows there is no need to hav them returned in the query. It just eats up resources. Especially if you are JOINing tables, you could be pulling much, much more information than you really need. And, when you do JOIN tables you can run into errors if you have fields with the same name in different tables. For example if you need to JOIN products with categories and both tables have a field called 'name'. If you tried to do an ORDER BY on "name" you would get an error because it doesn't know which name field to order on. As long as you have protected your database transactions from infiltration, no. But, lets say you DID have a gap in your code. Then you now have data that may be sensitive that could be exposed. Here is another reason. I never use the numeric index to reference fields from a database query, In fact, you may notice I changed your use of mysql_fetch_array() (which returns results indexed by their field names as well as numerically- i.e. everything is duplicated) to mysql_fetch_assoc() (which only returns field indexed by field name). The reason I do that is I would never make a mistake of referencing the wrong field. But, let's say you, or someone else, has some code that references fields by their numeric index. If the query is only pulling five specific fields then there will always be five fields in the results and they can always be referenced using 0-4. But, if the query uses *, then the developer needs to specify the correct fields by their position in the results (e.g. 2, 3, 6, 7, 9). Ok, so once they have that working and are referencing the right fields everything is good, right? Wrong! A couple months down the road you realize you need a new column in that table to support some other functionality. So, you add that field and when doing so decide to insert it between some other fields because its value is tied to another field. Now, that code above that was returning all fields and referencing them by numeric index will be displaying the wrong data. If you were not changing that page as part of your modification you might not even notice that change before putting the changes into production. And, you could be exposing sensitive data such as SSN, birth-date, etc.
-
Uploading multiple files - How to echo all details?
Psycho replied to leettari's topic in PHP Coding Help
OK, here is a working script. The array of file uploads was in a different format than I thought. I also fixed an error in the logic you had to rename the files to prevent duplicates. The original code would do the following: - filename.txt - 1filename.txt - 21filename.txt - 321filename.txt I also moved the number to the end of the filename component: filename.txt, filename_1.txt, filename_2.txt, etc. <?php define("MAX_COUNT", 10); define("UPLOAD_DIRECTORY", "valokuvat/"); define("MAX_SIZE", 1000000); if(!is_dir(UPLOAD_DIRECTORY)) { mkdir(UPLOAD_DIRECTORY, 0777); } if(isset($_FILES['files'])) { foreach($_FILES['files']['name'] as $index => $filename) { //Check if upload field was empty if(empty($filename)) { continue; } //Go to next field //Check if upload exceeded max size if($_FILES['files']['size'][$index] > MAX_SIZE) { echo "Liian iso tiedosto!<br>".MAX_SIZE." on raja"; break; } //Rename if duplicate $k = 1; while(file_exists(UPLOAD_DIRECTORY.$filename)) { $original = $_FILES['files']['name'][$index]; $extpoint = strrpos($original, '.'); $filename = substr($original, 0, $extpoint) . "_{$k}" . substr($original, $extpoint); $k++; } //Upload the file move_uploaded_file($_FILES['files']['tmp_name'][$index], UPLOAD_DIRECTORY.$filename); echo "xxx/waddap/valokuvat/$filename<br>\n"; } exit(); } $fileInputs = ''; for($i=1; $i<=MAX_COUNT; $i++) { $fileInputs .= " <b><span style=\"color: #00FFFF;\">$i</span></b> <input type=\"file\" name=\"files[]\" size=\"75\"><br>"; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Leettarin Uploader</title> <link href="style.css" rel="stylesheet" type="text/css" /> <link rel="shortcut icon" href="xxx/twg/favicon.ico" /> </head> <body background="Ready.jpg"> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" ENCTYPE="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="102400000"> <?php echo $fileInputs; ?> <input type="submit" value="Upload"> </form> </body> </html> -
Uploading multiple files - How to echo all details?
Psycho replied to leettari's topic in PHP Coding Help
I told you I didn't test it. I only said that you should use a name for the upload input fields so they will be treated as an array. I only posted the "sample" code to get you started. I leave it to YOU to debug the script. There was nothing in your original code to upload anything to a database. you would need to modify that code accordingly too. -
Two things: 1) You first have to add the fields to the SELECT part of the query that you want to use. I would advise NOT using '*'. There are good reasons not to use it unless you really do need it. 2. Don't create the table IN the loop. Create the table outside the loop and create the rows inside it. $query = "SELECT sent, message FROM memberMail WHERE userIDFrom='92' AND unread='1'"; $result = mysql_query($query) or die(mysql_error()); //Display number of unread messages $num_rows = mysql_num_rows($result); echo "You have ($num_rows) unread message(s)."; //If there are unread messages, display them if (mysql_num_rows($result) > 0) { //Open table and create headers echo "<table border=\"1\">\n"; echo " <tr>\n"; echo " <th>Sent</th>\n"; echo " <th>Message</th>\n"; echo " </tr>\n"; //Show messages while($row = mysql_fetch_assoc($result)) { echo " <tr>\n": echo " <td>{$row['sent']}</td>\n"; echo " <td>{$row['message']}</td>\n"; echo " <tr>\n": } //Close table echo "</table>\n"; }
-
I prefer not to have hard-set values for the number of options to show. This should work as well and you can easily set the number fo years back to show by setting the first variable accordingly $years_to_show = 10; $start_year = date('Y'); for($offset=0; $offset<$years_to_show; $offset++) { $year = $start_year - $offset; echo "<option value=\"{$year}\">{$year}</option>\n"; }
-
Uploading multiple files - How to echo all details?
Psycho replied to leettari's topic in PHP Coding Help
You have an exit() in your while() loop. It is exiting the script after the first iteration! instead of naming your upload files as 'file1', 'file2', 'file3', etc. Name them as an array. Then you can create a foreach loop to process each file. <input type="file" name="files[]"> Also, do not use the FONT tag, it has been deprecated for MANY years. I haven't tested this but it should get you in the right direction <?php define("MAX_COUNT", 10); define("UPLOAD_DIRECTORY", "valokuvat/"); define("MAX_SIZE", 1000000); if(!is_dir(UPLOAD_DIRECTORY)) { mkdir(UPLOAD_DIRECTORY, 0777); } if(isset($_FILES['files'])) { foreach($_FILES['files'] as $file) { if($file['size'] > MAX_SIZE) { echo "Liian iso tiedosto!<br>".MAX_SIZE." on raja"; break; } while(file_exists(UPLOAD_DIRECTORY.$file['name'])) { $file['name']="$k".$file['name']; $k++; } move_uploaded_file($file['tmp_name'], UPLOAD_DIRECTORY.$file['name']); echo "xxx/waddap/valokuvat/".$file['name']; } exit(); } $output = ''; for($i=1; $i<=MAX_COUNT; $i++) { $fileInputs .= " <b><font style=\"color: #00FFFF;\">$i</font></b> <input type=\"file\" name=\"files[]\" size=\"75\"><br>"; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Leettarin Uploader</title> <link href="style.css" rel="stylesheet" type="text/css" /> <link rel="shortcut icon" href="xxx/twg/favicon.ico" /> </head> <body background="Ready.jpg"> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" ENCTYPE="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="102400000"> <?php echo $fileInputs; ?> <input type="submit" value="Upload"> </form> </body> </html> -
When you try to reference a variable that does not exist you may get a warning message depending upon the error level set on the server. The correct way to check if a variable has been set or not is . . . wait for it . . . isset()! if(isset($_SESSION['mid'])){ echo $inbox; } else { echo 'Your not logged in!'; } However, if you were really wanting to check if the value of $_SESSION['mid'] is TRUE (when it is set), then you might need to do this: if(isset($_SESSION['mid']) && $_SESSION['mid']){
-
Yes. No need to check which fields have changed. Just do an UPDATE with all the fields that are on the form that you allow to change.
-
Then you should pass parameters to your page to set the field to sort on and the sort order. Then build the ORDER BY part of the query dynamically. You are going about this the wrong way - use MySQL to order the results. $ORDER_BY = ''; if(isset($_GET['sort'])) { $field = mysql_real_escape_string($_GET['sort']); $order = (isset($_GET['order']) && $_GET['order']=="D") ? 'DESC' : 'ASC'; $ORDER_BY = "ORDER BY {$field} {$order}"; } $query = "SELECT model FROM cars {$ORDER_BY}";