
Psycho
Moderators-
Posts
12,160 -
Joined
-
Last visited
-
Days Won
130
Everything posted by Psycho
-
Read the two files into separate arrays. I assume each product has something such as a unique ID along with additional data about the product (name, description, etc). Use the unique identifier as the index for each array element and then make each element a subarray with all the other data E.g. $newCSV = array( '1' => array('name' => 'Prod 1', 'Desc' => 'Description for product 1'), '4' => array('name' => 'Prod 4', 'Desc' => 'Description for product 4'), '7' => array('name' => 'Prod 7', 'Desc' => 'Description for product 7') ) Once you have the two arrays $newCSV and $currentCSV (or whatever you want to name them) you can use the function array_diff_key() to determine the new records and the deleted keys - just depends on the order of the parameters $deletions = array_diff_key($currentCSV, $newCSV); $additions = array_diff_key($newCSV, $currentCSV); Look ma - no loops!
-
From the manual When you have these types of problems, take a breath and determine what data you can inspect to determine what the problem may be. As Ch0cu3r proposed, checking the results of the query is a good first step. Once you verify that you could have inspected the HTML code and you would have seen multiple lines of the table rows with no content. The next logic steps would have been to inspect what the value of $img2 is using either print_r() or var_dump(). Either one would have made the problem perfectly evident.
-
Something to consider: If you were to use PDO instead of mysqli_ you can create a prepared statement and pass the entire array to the statement. You do need to specify the named indexes in the prepared statement, which you would have to write out in the code or do it programatically as Ch0cu3r did above. But, you can then create multiple records by passing the arrays. Example //Arrays with values to insert $record1 = array('name' => 'John Smith', 'addr' => '123 Main Street', 'city' => 'New York'); $record2 = array('name' => 'Jane Doe', 'addr' => '425 Elm Street', 'city' => 'Los Angeles'); $record3 = array('name' => 'Alex Williams', 'addr' => '623 Delta Ave', 'city' => 'Austin'); //Create database handle $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); //Create prepared statement handle $sth = $dbh->prepare("INSERT INTO my_table (name, addr, city) value (:name, :addr, :city)"); //Insert records using the arrays $sth->execute($record1); $sth->execute($record2); $sth->execute($record3);
-
Good catch mac_gyver. With the modified code it should be very simple to fix that type of error. There were so many if/else combinations that it made my head spin. And, now that you identified that, now I'm guessing that tables 5 and 6 were to display similar results for phases B and C. If the OP can confirm that, i can easily modify the code to support that.
-
Yeah, I noticed that too and removed the <p> tags from the updated code I provided. I don't think that would cause a problem, but best to leave out things unless they are needed.
-
Ok, I've used the test file and have used it with the code you provided to generate output. I'm not seeing anything wrong. But, I will say you went if/else crazy in your script. It is much more complicated than it should be - which is making this harder to solve than it should be. I am seeing some incorrect HTML syntax. Those could cause different presentations based on your browser. Some browsers are more forgiving of HTML errors than others. For example if ($table4Add) $table4 .='<td><p style="color:red";>'.round($value,2).'</p></td>'; The semicolon after the style parameter is outside the quote mark Anyway, here is a complete rewrite that should produce the same output format using much simpler logic. I don't know that it will sove your problem, but I did clean up some of the invalid HTML as well. I didn't see that the code for table5 and table6 was doing anything, so I removed it. If you need it, please explain what it is supposed to do and I can help with that too. One other change I would probably make to this that I didn't do is that I would probably read the entire file and copy it to the local server and then process it from there rather than read it line by line from the FTP location. <?php session_start(); //Define configuration variables $ftp_server = "server"; $ftp_user_name = "user"; $ftp_user_pass = "password"; $dataFile = "1hdata.csv"; $startRow = 3592; //First row with data //connect to FTP server $conn_id = ftp_connect($ftp_server) or die ("Couldn't connect to $ftp_server"); if(!ftp_login($conn_id, $ftp_user_name, $ftp_user_pass)) { die("Unable to log into FTP server"); } ftp_pasv($conn_id, true); //Get data file $handle = fopen("ftp://user:%pass@server/{$dataFile}", "r"); if($handle===false) { die("Unable to access file {$dataFile}"); } //Process the file $row = 0; $table4Body = false; while (($data = fgetcsv($handle)) !== false) { //Increment row count $row++; //Skip rows before the data we want if($row < $startRow) { continue; } //define values from the data row $time = $data[0]; $voltage = round($data[8], 2); $voltageStyle = ($voltage <=216.2 || $voltage >=253.0) ? 'red' : 'black'; $currentA = round($data[5] * 1250, 2); $currentAStyle = ($currentA >= 1500.0) ? 'red' : 'black'; $phaseA = round($data[1], 2); $phaseAStyle = ($phaseA <= 0) ? 'red' : 'black'; //Create the HTML output $table4Body .= " <tr>\n"; $table4Body .= " <td>$time</td>\n"; $table4Body .= " <td style='color:{$voltageStyle};'>{$voltage}</p></td>\n"; $table4Body .= " <td style='color:{$currentAStyle};'>{$currentA}</p></td>\n"; $table4Body .= " <td style='color:{$phaseAStyle};'>{$phaseA}</p></td>\n"; $table4Body .= "</tr>\n"; } //Close file handle and FTP connection fclose($handle); ftp_close($conn_id); //Define the output $table4 = ''; if(!empty($table4Body)) { $table4 .= "<table border='1'>\n"; $table4 .= "<thead>\n"; $table4 .= " <tr>\n"; $table4 .= " <th>TimeStamp</th>\n"; $table4 .= " <th>Voltage A</th>\n"; $table4 .= " <th>Current A</th>\n"; $table4 .= " <th>Phase A</th>\n"; $table4 .= " </tr>\n"; $table4 .= "</thead>\n"; $table4 .= "<tbody>\n"; $table4 .= $table4Body; $table4 .= "</tbody>\n"; $table4 .= "</table>\n"; } ?> <html> <head></head> <body> <h1>Last 10 second reading for Bridgeford T1</h1> <?php echo $table4; ?> </body> </html>
-
A few comments first: 1. In my experience, these type of issues with tables usually occurs doe to improper opening/closing of the tags 2. Can you provide a sample file that you are using? It is difficult to easily identify the errors in the code and having a sample input and seeing the actual output would help 3. You should really create your output in a way that the source HTML would be readable. From the code you've provided there are no line breaks in the HTML output. I suggest using double quotes in delineating the strings and putting \n at the end of an HTML line so there will be a line break in the output.
-
@mac_gyver, maybe I am missing something but the query and error make perfect sense. @alphasil, You are using BETWEEN, but you are only providing one value for the between comparison. A BETWEEN is used like this WHERE foo BETWEEN 100 AND 200 Based on what you have, I think this is what you wanted SELECT `idsala`, `idtempoInicio`, `idTempoFim`, `data` FROM `req_material_reserva` WHERE `idsala` = 3 AND 12 BETWEEN `idtempoInicio` AND `idTempoFim` AND `data` = "2014-05-05"
-
PHP SQL User Profile Completeness calculation not working
Psycho replied to AshleighCo's topic in MySQL Help
Why are you using a while() loop when there is only one record? It doesn't have a code block associated with it - but that shouldn't cause a problem in how you are using it. It just looks very odd since it isn't needed. Have you output the values from the query? Could be they are all empty. Also, the calculation will work only with that specific max value of 100. That is the wrong way to calculate the percentage. percent x totalvalue = percentvalue You have the totalvalue and the percent value so you need to calculate the percentage like this percent = percentvlaue / totalvalue i.e. percent = 100 / user points Try this <?php $query = "SELECT title, name, surname, identityno, gender FROM cic_candidates WHERE id='{$id}' LIMIT 1"; $result = mysql_query($query); if (!$result) { die("Could not successfully run query " . mysql_error()); } if (!mysql_num_rows($result)) { die("No rows found, nothing to print so am exiting"); } $maximumPoints = 100; $user = mysql_fetch_assoc($result)); $user_points = 0; $user_points += !empty($user['title']) ? 20 : 0; $user_points += !empty($user['name']) ? 20 : 0; $user_points += !empty($user['surname']) ? 20 : 0; $user_points += !empty($user['identityno']) ? 20 : 0; $user_points += !empty($user['gender']) ? 20 : 0; $percentage = $user_points / $maximumPoints * 100; echo "{$percentage}%"; //Debug echo "<br><pre>"; var_dump($user); echo "</pre>"; ?> -
$Post Multiple Variable from a Single <option>
Psycho replied to jperez260's topic in PHP Coding Help
You're doing this the wrong way. The only thing you should be posting is the ID of the selected value. The SELECT field on your form page should use the sender name as the displayed text for the options and the sender ID as the Value. Then on the receiving page you would use the passed ID to run a query to get the name and email address to use in the process of sending the email. What you are doing now would let a malicious user re-purpose your form to send SPAM.- 5 replies
-
- variable
- multiple variables
-
(and 1 more)
Tagged with:
-
I don't think you understood what I was saying. There was a flaw in the logic you had. You had a step to increment the vote. If that passed, you had a step to send the email. If that failed you told the user that their vote wasn't registered. That would be incorrect, because the only way for the user to get to the step that sends the email would be if their vote had already been saved! As for the time, did you try incorporating it in the script? It should affect any functions that deal with time that come after where you use it (hint: put it at the top of your script).
-
Yes, I understand that. But, as I said, what does sending you an email have to do with whether or not the vote was counted? Understanding the available functions and processes of the language only makes up part of the process of being able to program. A LARGE part of programming is just being able to think logically. That can be difficult when you are working out of your element. What will help is if you think through the process before you write the code. Create a flow chart if needed to determine what data you need to capture, what decision need to be made and what output should be generated. It may seem like it will take longer to accomplish your task when you want to start writing code, but by looking at the big picture first and making those decisions you will save your self many hours in having to rework/rewrite code because of a logic error you did not anticipate.
-
Why are you passing four parameters to the check_output(0 function which only accepts two? The problem that you are going to have is that if you are going to limit the comments to a certain length, you will end up with some invalid HTML code because some opening HTML tags may come after the point where you are going to limit the length. This is not a trivial problem to solve. I'd suggest some google searching to find a solution that someone has already built. This seems to include some good resources: https://www.google.com/#q=php+truncate+text+retain+HTML
-
Hmm, that can't be your working script. you define the passed value as the variable $lied, but then use $song in the query. A few other things: 1. Use comments in your code. It will make it easier for you and us 2. You are using the return value of the email() function to determine if the user sees that their vote was registered or not. You should be determining that based upon whether the query passed. If the email is not sent, that doesn't mean their vote wasn't registered. I wouldn't show the user any error based upon the email. It is not pertinent to the process for them. In fact, the fact that the query passed is not an indication that their vote passed. The query would succeed with ANY passed value. Even ones that don't exist in the database - it just wouldn't update any records. You should check that there were affected rows. 3. You should turn off error reporting when putting the script into production. The detailed reporting of errors can leak information that one could use to perform malicious activities. 4. I would suggest not 'bundling' up multiple functions in a single line - especially in an if() condition. If there is a problem, it makes it more difficult to debug Give this a try <?php //Check if the user had voted in the last 24 hours if(isset($_COOKIE['voted'])) { $expireString = date('m-d-Y h:i:s', $_COOKIE['voted']); $output = "Sorry, you can only vote once every 24 hours. You can vote again after $expireString"; } else { //Start session and enable error reporting session_start(); error_reporting(E_ALL | E_STRICT | E_NOTICE); ini_set('display_errors', '1'); //Connect to DB $host="localhost"; $user="jingleko_reload"; $pwd="*******"; $dbname="jingleko_reloader"; $link = mysqli_connect($host,$user,$pwd,$dbname) or die(mysqli_error()); //Update count for selected song $song = mysqli_real_escape_string($link,$_GET['Song']); $query = "UPDATE voting SET Votes = Votes+1 WHERE Song = '$song'"; $result = mysqli_query($link, $query); if (!$result) { //Query failed #die(mysqli_error()); //Uncomment for debugging only $output = "There was a problem processing your request."; } elseif(!mysqli_affected_rows($link)) { //No records were updated $output = "The song you selected doesn't exist." } else { //Vote was registered $songSafeHtml = htmlspecialchars($_GET['Song']); $output = "You voted for <b>$songSafeHtml</b><br> U het gestem vir <b>$songSafeHtml</b></br>"; //Set cookie to prevent multiple votes $expire = time() + (60 * 60 * 24); //Set expiration for 24 hours setcookie('voted', $expire, $expire); //Send confirmation email $to = "[email protected]"; $subject = "There was a vote"; $message = "Someone voted for $songSafeHtml."; $header = "From: [email protected] \r\n"; $retval = mail($to, $subject, $message, $header); } } ?> <html> <head></head> <body> <?php echo $output; ?> </body> </html>
-
Also, You are using the mysql_ version of real_escape_string Plus, it looks like you are putting the song title on the query string. Ideally, you should be using an ID and not a textual value for the song anyway. And, you are not checking for errors. Try this <?php //Get the passed value $song = trim($_GET['Song']); //Create DB connection $host="localhost"; $user="*****"; $pwd="******"; $dbname="jingleko_reloader"; $con = mysqli_connect($host,$user,$pwd, $dbname); //Update record count $songSQL = mysqli_real_escape_string($song); $query = "UPDATE voting SET Votes = Votes+ 1 WHERE Song = '$song'"; mysqli_query($query) or die(mysqli_error()); $songSafeHtml = htmlspecialchars($_GET['Song']); echo ("You voted for $songSafeHtml"); ?>
-
You would, of course, escape content before inserting it into the database to prevent SQL Injection using the proper method for the database engine you are uisng (e.g. mysqli_real_escape_string() or prepared statements). However, some people would also escape the content for use on a web page [e.g. htmlentities()]. I think that is the wrong approach. It makes it easier since you don't have to think about it so much when you pull data from the database to display on your page, but you will lose fidelity. Once you escape content you can not with certainty) revert it back to its original state. I believe you should only escape content using the appropriate method at the time that you will use it. Otherwise, keep the content in it's original format. For example, if you were to run the content through htmlentities() before storing the in the database and later decided you wanted a way to output the data to a text file you would end up with something much different than was intended. So, I would store the content exactly as it is entered (escaping for the database, of course). Then, when building the page I would use htmlentities() or htmlspecialchars() on any of that content to ensure it doesn't get rendered as actual HTML code.
-
Here's another way of explaining the problem that may make sense. That loop is defining a function to run when the links are clicked. If you strip out just that function you end up with this function(){ alert(links[i].href); return false; }; links is not defined when the function is called by the onclick event. It is not inserting the value of links[i].href on each iteration of the loop. But, that's just the wrong way to do this anyway. For that to work you have to dynamically create a unique function for each hyperlink. Instead, just create one function that the links pass an event handler to so the function can reference the href value - as requinix showed.
- 5 replies
-
- javascript closures
- functions
-
(and 1 more)
Tagged with:
-
You marked your own response as the best answer?
-
Did you think to test what the result of ($i % 4) would be for different values of $i? If you had it would have shown that you were on the right track, but made one flaw. for($i=0; $i<14; $i++) { echo "{$i} : mod 4 = " . ($i%4) . "<br>\n"; } Here are the results of that test (I've highlighted the ones that I think you should pay attention to: EDIT: cyberRobot beat me to it (because he took the easy route ), but I wanted to hopefully teach you how to solve problems like this in the future.
-
I had originally wrote the code with the assumption that you had an ID column in your database and then decided to change it to only use the link value. In doing so, I forgot to revert a line to the correct value This $link = mysql_real_escape_string($_GET['id']); Should be this $link = mysql_real_escape_string($_GET['link']); Also, in case it isn't clear. The second block of code in my first reply would be for the page referrer.php that you would create for the links to point to.
-
Help with load balancing redirect script.
Psycho replied to RandomNsanity's topic in PHP Coding Help
This forum is intended for people to get help with code they have written. So there is an expectation that the person has at least a basic knowledge. I left off the DB connection in my code because I assumed you would add that (and anything else you want to include). Also, I mistakenly used the mysql_ versions and not the mysqli_ That sounds correct I always use the same variable to define my queries. Once I run the query, I store the result in $result. After that I no longer need the value stored in $query because I've already run it. Here's a revise of what I provided previously <?php //Connect to DB $con = mysqli_connect('database', 'username', 'password', 'random_link'); if (!$con) { die('Could not connect: ' . mysql_error()); } //Get the first link with the lowest count and lowest ID $query = "SELECT id, link FROM links_table ORDER BY count ASC, id ASC LIMIT 1"; $result = mysqli_query($con, $query); $link = mysqli_fetch_assoc($result); //Update the count for the selected link $query = "UPDATE links_table SET count = count + 1 WHERE id = {$link['id']}"; $result = mysqli_query($con, $query); //Display the link to the user echo "<a href='{$link['link']}'>{$link['link']}</a>"; ?> -
Help with load balancing redirect script.
Psycho replied to RandomNsanity's topic in PHP Coding Help
First off, the terminology "load balancing" means something completely different than what you are asking for. Which may be why no one has responded yet. In any event, you are making this way too complicated. Just keep a count (in the database) of when these links are used. Then you can simply use an ORDER BY in your query to get the next record. This assumes the links have an ID in a specific numerical order to determine the order in which they would be displayed. //Get the first link with the lowest count and lowest ID $query = "SELECT id, link FROM links_table ORDER BY count ASC, id ASC LIMIT 1"; $result = mysql_query($query); $link = mysql_fetch_assoc($result); //Update the count for the selected link $query = "UPDATE links_table SET count = count + 1 WHERE id = {$link['id']}"; $result = mysql_query($query); //Display the link to the user echo "<a href='{$link['link']}'>{$link['link']}</a>"; -
You can do this in one of two ways. 1. Use JavaScript to add an onclick function to the links to run a function that would make an AJAX call to a PHP page to increment the counter for the page being requested then allow the link to open the selected page. 2. Use an intermediary page. Instead of having your links open directly to the external page have them open to a page you host - passing a value to identify the external page. On that intermediary page, perform your Database query to update the hit count and then redirect to the external page. Assuming you have a unique ID for your links, change your current page to something like this: <?php $query = "SELECT link FROM links WHERE link='external'"; $result = mysql_query($query) if (!$result) { echo "Error" . mysql_query(); die(); } if(!mysql_num_rows($result)) { echo "No data"; } else { while ($row = mysql_fetch_assoc($result)) { echo "<a href='referrer.php?link={$row['link']}'>{$row['link']}</a>\n"; } } ?> <?php //Get value from URL and update count $link = mysql_real_escape_string($_GET['id']); $query = "UPDATE link SET count = count + 1 WHERE link='$link'"; $result = mysql_query($query); if (!$result || !mysql_num_rows($result)) { echo "Error" . mysql_query(); die(); } //Redirect user to external link header("Location: {$link}"); exit(); ?>
-
Yeah, no reason to actually fix the underlying problem. Much better to keep putting patchwork band-aids in place that you'll continually need to work around and tweak over time. As stated previously INSERT IGNORE will suppress all errors - not just duplicate checks. Based on the level of code in question, I don't think it makes sense to ignore errors. Plus, the unique constraints would only work for the values in the same columns. If you don't want to fix the real problem, then I would suggest doing a SELECT first to check for existing records. If none are found then do the INSERT. But, as stated previously, you could end up with duplicates due to race conditions - i.e. two people inserting records at the exact same time. It will be pretty rare. But, you could also follow up with the third query to look for duplicates and delete the latter to cover that very small possibility.
-
You're doing this the wrong way. You don't need to run the two queries. You only need one. A good indicator that there's a problem is the user of GROUP_CONCAT(). You should never be dealing with comma separated lists to compare/search for values. $query = "SELECT injuryreport.*, 0 AS section FROM injuryreport JOIN injurylocations ON injuryreport.injury = injurylocations.location WHERE report='yes' AND injurylocations.general='$general'"; $result = mysql_db_query($db, $query, $conn); // check for errors if (!$result) { die("ERROR: " . mysql_error()); } // check for results if (!mysql_num_rows($result)) { echo "I CANT FIND A LIST OF INJURY LOCATION REFERENCES"; } else { //Do something with the results }