PHP - Optimize My Code
Hey so I made a ToDo List as my first php script after starting to learn. I want you guys to just look at my code and tell me where I can improve. I want to drop any bad habits early on so they don't move forward with me. Also tell me where I can optimize and minimize the code so I don't write unnecessary code. Thanks! I'm going to omit things like some html that isn't crucial. You can see it live he https://taziamoma.com/ToDoList/ . Also try to do an SQL injection so I can see if I protected myself from it properly. Thank you! index.php <?php include_once("includes/connection.php"); $errors = ""; if (isset($_POST['submit'])) { if (empty($_POST['task'])) { $errors = "You must fill in the task"; } else { try { $task = $_POST['task']; $sql = "INSERT INTO todopost (title) VALUES ('$task')"; $db->exec($sql);; header('Location: index.php'); } catch(PDOException $e) { echo $sql. "<br>". $e->getMessage(); } } } if (isset($_GET['del_task'])) { $stmt = $db->prepare("DELETE FROM todopost WHERE id = :id"); $stmt->execute(array(':id' => $_GET['del_task'])); header('Location: index.php'); } <body> <div class="outside"> <div class="container"> <div id="myDIV" class="header"> <h2 style="margin:5px">My To Do List</h2> <form method="post" action="index.php" class="input_form"> <?php if (isset($errors)) { ?> <p><?php echo $errors; ?></p> <?php } ?> <input type="text" name="task" class="input"> <button type="submit" name="submit" class="addBtn">Add</button> </form> </div> <ul id="myUL"> <?php try { $stmt = $db->query('SELECT id, title FROM todopost ORDER BY id DESC'); while($row = $stmt->fetch()) { ?> <div class="li_cont"> <li><?php echo $row['title']; ?></li> <a class="right" href="index.php?del_task=<?php echo $row['id'] ?>">x</a> </div> <?php } } catch(PDOException $e) { echo $e->getMessage(); } ?> </ul> </div> </div> </body> </html> connection.php <?php ob_start(); session_start(); $host = "localhost"; $username = "root"; $password = ""; try { $db = new PDO("mysql:host=$host;dbname=tazejesa_todo", $username, $password); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: ". $e->getMessage(); } ?>
Similar TutorialsI am very new to PHP and have tried various techniques but I am getting a 500 error when clicking on the export button to download a csv report. I'm not sure why the previous developer did it this way. Is there a better why in PHP to make this code better? Willing to understand and learn from an PHP expert. The database is MYSQL. $coursefilterid = $_GET['course']; $conn = new mysqli($host, $username, $password, $database); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sqluserenrolled = "select mdl_user.username, mdl_user_enrolments.userid as enrolleduserid, mdl_enrol.courseid from mdl_user_enrolments Inner Join mdl_enrol on mdl_enrol.id = mdl_user_enrolments.enrolid Inner Join mdl_user on mdl_user.id = mdl_user_enrolments.userid where mdl_enrol.courseid = '" . $coursefilterid . "' order by mdl_user.username "; $queryenrolleduser = mysqli_query($conn, $sqluserenrolled); ?> <html> <head> </head> <body> <form method="post" action="<?php echo "userlistssiexport.php?id=$coursefilterid"?>"> <input type="hidden" name="exportcourseid" value="<?php echo $coursefilterid;?>"> <input type="hidden" name="sessid" value="<?php echo $USER->sesskey;?>"> <input class="btn btn-primary" type="submit" name="submit" value="<?php echo "Export";?>"> </form> <?php $noteid = ""; $cmId = ""; ?> <table class="data-table"> <caption class="title">User info</caption> <thead> <tr> <th>Username</th> <th>Firstname</th> <th>Lastname</th> <th>Email</th> <th>Last login</th> <th>Createddate</th> <th>Position</th> <th>Organization</th> <th>Certificate Request Date</th> <th>Role1</th> <th>Role2</th> <th>Role3</th> </tr> </thead> <tbody> <?php while ($row = mysqli_fetch_array($queryenrolleduser)) { $enrolleduserid = $row['enrolleduserid']; $sql = "select mdl_user.username as username, mdl_user.firstname as firstname, mdl_user.lastname as lastname, mdl_user.email as email, mdl_user.lastlogin as lastaccess, mdl_user.timecreated as createddate, mdl_user_info_data.data as position from mdl_user Inner Join mdl_user_info_data on mdl_user_info_data.userid = mdl_user.id Inner Join mdl_user_info_field on mdl_user_info_field.id = mdl_user_info_data.fieldid Inner Join mdl_user_lastaccess on mdl_user_lastaccess.userid = mdl_user.id where mdl_user_info_field.id = 1 and mdl_user.deleted = 0 and mdl_user.id = '" . $enrolleduserid . "' group by mdl_user.username order by mdl_user.username "; $query = mysqli_query($conn, $sql); if (! $query) { die('SQL Error: ' . mysqli_error($conn)); } else {} ?> <?php $no = 1; $total = 0; $username = ''; $coursename = ''; $content = ''; $modulename = ''; $organization = ''; $userid = ''; $certificatedate = ''; $userrole = ''; $enrolleduserid = ''; while ($row = mysqli_fetch_array($query)) { // Do something here $username = $row['username']; $coursename = $row['coursename']; $content = $row['content']; $noteid = $row['noteid']; // $notedatetime = date("d/m/y g:i (A)", $row['notedate']); $notedatetime = date("D M j Y G:i A", $row['notedate']); $lastaccess = date("D M j Y G:i A", $row['lastaccess']); $createddate = date("D M j Y G:i A", $row['createddate']); $datafile = $username . $coursename . $content; echo '<tr> <td>' . $row['username'] . '</td> <td>' . $row['firstname'] . '</td> <td>' . $row['lastname'] . '</td> <td>' . $row['email'] . '</td> <td>' . $lastaccess . '</td> <td>' . $createddate . '</td> <td>' . $row['position'] . '</td> '; $modid = $row['contextid']; // Get module name $sqlmodule = "select mdl_user.username as username, mdl_user.firstname as firstname, mdl_user.lastname as lastname, mdl_user.email as email, FROM_UNIXTIME(mdl_user_lastaccess.timeaccess) as lastaccess, FROM_UNIXTIME(mdl_user.timecreated) as createddate, mdl_user_info_data.data as organization from mdl_user Inner Join mdl_user_info_data on mdl_user_info_data.userid = mdl_user.id Inner Join mdl_user_info_field on mdl_user_info_field.id = mdl_user_info_data.fieldid Inner Join mdl_user_lastaccess on mdl_user_lastaccess.userid = mdl_user.id where mdl_user_info_field.id = 3 and mdl_user.deleted = 0 and mdl_user.username ='" . $username . "'"; $querymodule = mysqli_query($conn, $sqlmodule); ?> <?php $modulenamelink = ""; while ($row = mysqli_fetch_array($querymodule)) { $organization = $row['organization']; } echo '<td>' . $organization . '</td>'; $sqlCertificateDateuid = "select id from mdl_user where username = '" . $username . "'"; $queryCertificateDateuid = mysqli_query($conn, $sqlCertificateDateuid); while ($row = mysqli_fetch_array($queryCertificateDateuid)) { $userid = $row['id']; } $sqlcertificatedate = "select * from mdl_certificateemail where userid = '" . $userid . "' and courseid = '" . $coursefilterid . "'"; $querycertificaterequestdate = mysqli_query($conn, $sqlcertificatedate); while ($row = mysqli_fetch_array($querycertificaterequestdate)) { $certificatedate = date("D M j Y g:i:s A", $row['unixdatetimecertificate']); } echo '<td>' . $certificatedate . '</td>'; $sqluserrole = "select mdl_role_assignments.userid, mdl_role_assignments.roleid,mdl_course_modules.course, mdl_role.shortname as rolename,FROM_UNIXTIME(mdl_role_assignments.timemodified) from mdl_role_assignments Inner Join mdl_context on mdl_context.id = mdl_role_assignments.contextid Inner Join mdl_course_modules on mdl_course_modules.instance = mdl_context.instanceid Inner Join mdl_role on mdl_role.id = mdl_role_assignments.roleid where mdl_course_modules.course = '" . $coursefilterid . "' and mdl_role_assignments.userid = '" . $userid . "' group by mdl_role_assignments.userid, mdl_role_assignments.roleid, mdl_course_modules.course, mdl_role.shortname, mdl_role_assignments.timemodified order by mdl_role_assignments.timemodified "; $userlistrole = ''; $queryuserrole = mysqli_query($conn, $sqluserrole); while ($row = mysqli_fetch_array($queryuserrole)) { $userrole = $row['rolename']; $userlistrole = array( array( $userrole ) ); // echo '<td>'.$userrole.'</td>'; } foreach ($userlistrole as $listrole) { // echo $listrole; } $teacherrole = array( 'student' ); foreach ($teacherrole as $rolename) { $role = $DB->get_record('role', array( 'shortname' => $rolename )); $context = get_context_instance(CONTEXT_COURSE, $coursefilterid); // $context = context_course::instance($cid1); $teachers = get_role_users($role->id, $context); foreach ($teachers as $teacher) { $teacherid = $teacher->id; if ($teacherid == $userid) { echo '<td>student</td>'; } } } $teacherrole = array( 'editingteacher' ); foreach ($teacherrole as $rolename) { $role = $DB->get_record('role', array( 'shortname' => $rolename )); $context = get_context_instance(CONTEXT_COURSE, $coursefilterid); // $context = context_course::instance($cid1); $teachers = get_role_users($role->id, $context); foreach ($teachers as $teacher) { $teacherid = $teacher->id; if ($teacherid == $userid) { echo '<td></td>'; echo '<td>editingteacher</td>'; } } } $teacherrole = array( 'manager' ); foreach ($teacherrole as $rolename) { $role = $DB->get_record('role', array( 'shortname' => $rolename )); $context = get_context_instance(CONTEXT_COURSE, $coursefilterid); // $context = context_course::instance($cid1); $teachers = get_role_users($role->id, $context); foreach ($teachers as $teacher) { $teacherid = $teacher->id; if ($teacherid == $userid) { echo '<td>manager</td>'; } } } echo '</tr>'; } } ?> </tbody> <tfoot> </tfoot> </table> </body> </html> <?php } } else { header("Location:/index.php"); // echo "something"; die(); } } else { header("Location:/index.php"); die(); } ?>
Hi guys,
Having some trouble entering some php into my wordpress site that runs on Optimize Press.
I'm trying to insert this URL/ tracking code into my page as a hyperlink - 'Click Here Now'.
http://www.mysite.co...1_50onRed&sub1=<?php echo $sub1; ?>&sub2=<?php echo $sub2; ?>&sub3=<?php echo $sub3; ?>&sub4=<?php echo $sub4; ?>&sub5=<?php echo $sub5; ?>&lpid=<?php echo $lpid; ?>
This is what I have done so far:
<a href="http://www.mysite.co...;sub1=<?php echo $sub1; ?>&sub2=<?php echo $sub2; ?>&sub3=<?php echo $sub3; ?>&sub4=<?php echo $sub4; ?>&sub5=<?php echo $sub5; ?>&lpid=<?php echo $lpid; ?>">Click Here Now</a>
This does generate a hyperlink, however when I click it, I get: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=' at line 2
I understand for this code to work the page has to be saved in php. I thought wordpress did this automatically?
Can anyone help please? Also, please bear in mind I am using the Optimize Press plugin.
Many thanks in advance!
Tom
Hi, There is a feature in cpanel called optimize website and when you go in it there is a field to fill Compress the specified MIME types. My question is this the correct way to optimize PHP CSS JS did i enter the mime types correctly? text/html text/plain text/xml/css/application/x-httpd-php/application/x-javascript This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=321105.0 Hello everyone... I made point system that ranks users in my app. There are two parts to the system, a primary score and a dynamic score. The primary score is based on how you well you perform and the dynamic score is based on how well your friends perform. Both of these get added together to equal your total score. The problem is that I have a lot of looping occurring which results in about 400 queries being run when I access the page that executes this class. Can this be optimized? What's the best way to do this? I don't want to store the data as I want this presented in real-time. Code: [Select] <?php class edge { public function get_all_users_edge() { $sql = "SELECT id FROM users WHERE status = 3"; $result = mysql_query($sql) or die(mysql_error()); $ids = array(); while (($row = mysql_fetch_assoc($result)) !== false) { $ids[] = $row; } $all_edges = array(); foreach ($ids as $k => $id) { $edge = $this->get_users_edge($id['id']); $all_edges[$k] = $edge; } return $all_edges; } public function get_users_edge($uid) { $users_primary_edge = $this->get_users_primary_edge($uid); $users_dynamic_edge = $this->get_users_dynamic_edge($uid); return $users_primary_edge + $users_dynamic_edge; } public function get_users_primary_edge($uid) { if (active_id($uid) === false) { return false; } $uid = (int)$uid; $sql = "SELECT CHAR_LENGTH(`users`.`credentials`) AS `cred_chars`, CHAR_LENGTH(`users`.`specialties`) AS `spec_chars`, `companies`.`companyvideo` AS `video`, `investor_info`.`accredited` AS `accredited`, ( SELECT COUNT(`user_id`) FROM `blog_posts` WHERE `user_id` = '${uid}' ) AS `post_count`, ( SELECT COUNT(`uid`) FROM `votes` WHERE `uid` = '${uid}' ) AS `vote_sent_count`, `votes_received`.`inv_vote_received_count`, `votes_received`.`pub_vote_received_count`, ( SELECT COUNT(`userid`) FROM `employees` WHERE `userid` = '${uid}' ) AS `joined_count`, `votes2`.`ent_count`, `votes2`.`inv_count`, ( SELECT COUNT(`company_id`) FROM `company_fans` LEFT JOIN `companies` ON `company_fans`.`company_id` = `companies`.`companyid` LEFT JOIN `employees` ON `employees`.`companyid` = `companies`.`companyid` WHERE `userid` = '${uid}' ) AS `company_fans_count`, ( SELECT COUNT(`user_id`) FROM `recommendations` WHERE `user_id` = '${uid}' ) AS `recommendation_count`, ( SELECT COUNT(`partner_id`) FROM `partners` WHERE (`user_id` = '${uid}' OR `friend_id` = '${uid}') AND `approved` = '1' ) AS `associate_count` FROM `users` LEFT JOIN `investor_info` ON `investor_info`.`uid` = `users`.`id` LEFT JOIN `employees` ON `employees`.`userid` = `users`.`id` LEFT JOIN `companies` ON `employees`.`companyid` = `companies`.`companyid` LEFT JOIN ( SELECT `employees`.`userid`, SUM( IF( `votes`.`vote_type` = 1, 1, 0 ) ) AS `inv_vote_received_count`, SUM( IF( `votes`.`vote_type` = 0, 1, 0 ) ) AS `pub_vote_received_count` FROM `votes` INNER JOIN `employees` ON `employees`.`companyid` = `votes`.`company_id` WHERE `employees`.`userid` = '${uid}' GROUP BY `employees`.`userid` ) AS `votes_received` ON `votes_received`.`userid` = `users`.`id` LEFT JOIN ( SELECT `beta_keys`.`ref_id`, SUM( IF( `users`.`accounttype` = 1, 1, 0 ) ) AS `ent_count`, SUM( IF( `users`.`accounttype` = 0, 1, 0 ) ) AS `inv_count` FROM `beta_keys` INNER JOIN `users` ON `users`.`id` = `beta_keys`.`userid` WHERE `beta_keys`.`ref_id` = '${uid}' AND `users`.`status` = 3 GROUP BY `users`.`id` ) AS `votes2` ON `votes2`.`ref_id` = `users`.`id` WHERE `users`.`id` = '${uid}'"; $result = mysql_query($sql) or die(mysql_error()); $row = mysql_fetch_assoc($result); $score = 0; if((!empty($row['cred_chars'])) && (!empty($row['spec_chars']))) { $score += 200; } if(!empty($row['video'])) { $score += 50; } if($row['accredited'] == 1) { $score += 100; } $score += (50 * $row['post_count']); $score += (5 * $row['vote_sent_count']); $score += (3 * $row['inv_vote_received_count']); $score += (1 * $row['pub_vote_received_count']); $score += (200 * $row['joined_count']); $score += (40 * $row['ent_count']); $score += (200 * $row['inv_count']); $score += (10 * $row['company_fans_count']); $score += (30 * $row['recommendation_count']); $score += (20 * $row['associate_count']); return $score; } public function get_users_dynamic_edge($uid) { $uid = (int)$uid; $sql = "( SELECT `users`.`id` FROM partners INNER JOIN `users` ON `partners`.`user_id` = `users`.`id` WHERE partners.friend_id = '${uid}' AND `approved` = 1 ) UNION ALL ( SELECT `users`.`id` FROM `partners` INNER JOIN `users` ON `partners`.`friend_id` = `users`.`id` WHERE `partners`.`user_id` = '${uid}' AND `approved` = 1 )"; $result = mysql_query($sql) or die(mysql_error()); $i = 0; $score = 0; while (($row = mysql_fetch_assoc($result)) !== false) { $dynamic_scores[$i] = array( 'uid' => $row['id'], 'score' => $this->get_users_primary_edge($row['id']), ); $i++; } if(!empty($dynamic_scores)) { foreach($dynamic_scores as $k => $dynamic_score) { $score += $dynamic_score['score']; } } return ($score * 0.1); } } ?> This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=320813.0 Hi sorry for my bad English I have this queries but when I using num_queries show over 40 for this code!! how can I optimize it for best performance category table is : ".$prefix."_modules_categories item table is : ".$prefix."_modules $display = $openclose; if ($display == 0) { $show = "none"; $catimg = "<img src=\"$closedimg\" align=\"absmiddle\" border=\"0\">"; } else { $show = "show"; $catimg = "<img src=\"$openimg\" align=\"absmiddle\" border=\"0\">"; } //Categories $result = $db->sql_query("select mcid, mcname FROM ".$prefix."_modules_categories WHERE visible='1' ORDER BY mcposition"); //$coin=0; global $multilingual, $currentlang; while ($row = $db->sql_fetchrow($result)) { $mcid = $row['mcid']; $mcname = $row['mcname']; //$coin++; $mcname1 = $mcname; if(strlen($mcname1) == 0){ if ($multilingual == 1) { include("modules/languages/lang-".$currentlang.".php"); $mcname = "$mcnamed[$mcid]"; } else { include("modules/languages/lang-english.php"); $mcname = "$mcnamed[$mcid]"; } }else{ $mcname = "$mcname1"; } $content .= "</div><table border=0 cellpadding='1' cellspacing=1><tr><td width='16'><a id=\"x".$mcname."\" href=\"javascript:Toggle('".$mcname."','$align');\">$catimg</a></td><td><b>".$mcname."</b></table>\n"; $content .= "<div id=\"".$mcname."\" style=\"display: $show; margin-left: 1em;\">\n"; $result2 = $db->sql_query("SELECT title, custom_title, view, url FROM " . $prefix . "_modules WHERE active='1' AND inmenu='1' AND title!='$def_module' AND mcid='$mcid' ORDER BY custom_title ASC"); while ($row = $db->sql_fetchrow($result2)) { $title = $row['title']; $custom_title = $row['custom_title']; $view = $row['view']; $url = $row['url']; $arraymodules[] = "$title:$custom_title:$view:$url"; $m_title = $title; $m_title2 = ereg_replace("_", " ", $m_title); include("modules/".$title."/language/lang-".$currentlang.".php"); if ($custom_title != ""){$m_title2 = $custom_title;}else{ if(strlen($mudulename) != 0){ $custom_title = "$mudulename"; } $m_title2 = $custom_title; } if ($m_title != $main_module) { $showit = 0; switch($view){ case 0: // All users case $showit = 10; break; case 1: // Registered user access if (is_user($user) || is_admin($admin)) $showit = 1; break; case 2: // Admin only access if (is_admin($admin)) $showit = 2; break; default: // Subscriber only access if (is_user($user) || paid()) $showit = 3; break; } global $db , $prefix; $rowz = $db->sql_fetchrow($db->sql_query("SELECT gtset FROM ".$prefix."_config")); $gtset = intval($rowz['gtset']); if ($showit != 0) { $adds = $_SERVER['SERVER_NAME']; if ($url != "" AND $gtset != 0) { $content .= "<table border=0 cellpadding='1' cellspacing=1><tr><td width='16'><img src=\"$arrowimg\" align=\"absmiddle\" border=\"0\"></td><td><a href=\"$url\" title=\"$m_title2\" onMouseOver=\"self.status=' $m_title2 ';return true\" onmouseout=\"self.status='';return true\">$m_title2</a></td></tr></table>\n"; } else { $content .= "<table border=0 cellpadding='1' cellspacing=1><tr><td width='16'><img src=\"$arrowimg\" align=\"absmiddle\" border=\"0\"></td><td><a href=\"modules.php?name=$m_title\" title=\"$m_title2\" onMouseOver=\"self.status=' $m_title2 ';return true\" onmouseout=\"self.status='';return true\">$m_title2</a></td></tr></table>\n"; } } } $mudulename = ""; } } $content .= "</div>"; $db->sql_freeresult($result); $db->sql_freeresult($result1); We are toying with the idea of using PHP to do sorting instead of our database to reduce load and scale. Basically what we would have is multidimensional arrays that are resturned from the SQL engine and we will need to sort them on a specific key in PHP. We have written this functionality, but are looking to make it faster ANYWAY possible. Do you guys see anyway to speed up this code, without throwing more hardware at the problem yet? Currently on our test server this code takes approx 2.4 - 2.6 seconds to execute. We would love others to try this code and report what it takes them to execute. We are shooting for sub 1 second time. Code: [Select] $array = array(); $temp = array(); for($i = 0; $i < 100000; $i++) { $temp['id'] = rand(10000, 99999); $temp['history_id'] = rand(100000000, 999999999); $array[] = $temp; } //// // Start timer //// $mtime = microtime(); $mtime = explode(" ",$mtime); $mtime = $mtime[1] + $mtime[0]; $starttime = $mtime; //// // Actual sort //// usort($array, function($a, $b) { //Compare numbers if ($a['history_id'] == $b['history_id']) { return 0; } return ($a['history_id'] < $b['history_id']) ? -1 : 1; }); //// // End timer //// $mtime = microtime(); $mtime = explode(" ",$mtime); $mtime = $mtime[1] + $mtime[0]; $endtime = $mtime; $totaltime = ($endtime - $starttime); //// // Output execution time //// echo "Executed in: <strong>". $totaltime ."</strong> seconds."; I have a script to write out the number of hits each of my websites got each day of the week since I don't trust Google Analytics spying on my websites. The problem is that I have to query each day individually and count how many instances there are with that domain. Since I setup my database give me the time, location, demographics, etc. on each line I'm not sure how to optimize this further. Help would be greatly appreciated. Code: [Select] echo '<table><tr><td>Domain</td>'; foreach($timearray as $t){ echo '<td>'.$t.'</td>'; } echo '</tr>'; $i = 0; foreach($urlarray as $u){ $today = date("Y-m-d"); $yesterday = date("Y-m-d", mktime(0,0,0,date("m") , date("d")-1, date("Y"))); $lastmonth = date("Y-m-d", mktime(0,0,0,date("m")-1 , date("d")-1, date("Y"))); $twoweeks = date("Y-m-d", mktime(0,0,0,date("m") , date("d")-15, date("Y"))); $result3 = mysql_query("SELECT refer,Count(*) as count FROM `approved` WHERE time>'$lastmonth 23:59:59' AND time<'$today' AND refer LIKE '%$u%'"); $row3 = mysql_fetch_array($result3); $result4 = mysql_query("SELECT refer,Count(*) as count FROM `approved` WHERE time>'$twoweeks 23:59:59' AND time<'$today' AND refer LIKE '%$u%'"); $row4 = mysql_fetch_array($result4); if($row3['count']==0){echo "<tr style='background:red'>";}elseif($row4['count']>0){echo "<tr style='background:green'>";}elseif($i % 2){echo "<tr style='background:#CCC'>";}else{echo "<tr style='background:#FFF'>";} echo '<td>'.$u.' '.$row3['count'].' '.$row4['count'].'</td>'; foreach($timearray as $t){ $result = ''; $result = mysql_query("SELECT COUNT(*) AS count FROM `approved` WHERE time LIKE '$t%' AND refer LIKE '%$u%'"); while($row = mysql_fetch_array($result)){ echo '<td>'.$row['count'].'</td>'; } } echo '</tr>'; $i++; } echo '</tr></table>'; I have the following code in html: <html> <head> <script type="text/javascript"> <!-- function delayer(){ window.location = "http://VARIABLEVALUE.mysite.com" } //--> </script> <title>Redirecting ...</title> </head> <body onLoad="setTimeout('delayer()', 1000)"> <script type="text/javascript"> var sc_project=71304545; var sc_invisible=1; var sc_security="9c433fretre"; </script> <script type="text/javascript" src="http://www.statcounter.com/counter/counter.js"></script><noscript> <div class="statcounter"><a title="vBulletin statistics" href="http://statcounter.com/vbulletin/" target="_blank"><img class="statcounter" src="http://c.statcounter.com/71304545/0/9c433fretre/1/" alt="vBulletin statistics" ></a></div></noscript> </body> </html> Is a basic html webpage with a timer redirect script and a stascounter code. I know a bit about html and javascript, but almost nothing about php. My question is: How a can convert this html code into a php file, in order to send a variable value using GET Method and display this variable value inside the javascript code where says VARIABLEVALUE. Thanks in adavance for your help. Hi, I have some code which displays my blog post in a foreach loop, and I want to add some social sharing code(FB like button, share on Twitter etc.), but the problem is the way I have my code now, creates 3 instances of the sharing buttons, but if you like one post, all three are liked and any thing you do affects all of the blog post. How can I fix this? <?php include ("includes/includes.php"); $blogPosts = GetBlogPosts(); foreach ($blogPosts as $post) { echo "<div class='post'>"; echo "<h2>" . $post->title . "</h2>"; echo "<p class='postnote'>" . $post->post . "</p"; echo "<span class='footer'>Posted By: " . $post->author . "</span>"; echo "<span class='footer'>Posted On: " . $post->datePosted . "</span>"; echo "<span class='footer'>Tags: " . $post->tags . "</span>"; echo ' <div class="addthis_toolbox addthis_default_style "> <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> <a class="addthis_button_tweet"></a> <a class="addthis_counter addthis_pill_style"></a> </div> <script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=webguync"></script>'; echo "</div>"; } ?> hey gurus, i am a newbie php coder.. i am learning by example. what i am trying to do is write a piece of code which will alter 3 tables (user, bonus_credit, bonus_credit_usage) ---------------------------------------------------------------- the table structure that will be used is as follows: user.bonus_credit user.ID bonus_credit.bonusCode bonus_credit.qty bonus_credit.value bonus_credit_usage.bonusCode bonus_credit_usage.usedBy ---------------------------------------------------------------- so lets say, in bonus_credit i have the following bonusCode = 'facebook' (this is the code they have to type to redeem the bonus qty = '10' ( number of times the bonusCode can be redeemed, but same person can't redeem it more than once) value = '5' (this is the amount of bonus_credit for each qty) Now, I need to write a code that check to see if the code has been redeemed in the bonus_credit_usage table and if the user.ID exists in this table as bonus_code_usage.usedBy, then give an error that its already been used and if it hasn't been used, then subtract 1 from qty, add ID to usedBy and then add the value to the bonus_credit ----------------------- i have started the steps just to create a simple textbox and entering a numeric value to bonus_credit, and that works.. but now i have to use JOIN and IF and ELSE.. which is a little too advanced for me.. so i'd appreciate a guide as i write the code. if(isset($_REQUEST['btnBonus'])) { $bonus_credit = addslashes($_REQUEST['bonusCode']); $query = "update user set bonus_credit=bonus_credit+'".$bonus_credit."' where id='".$_SESSION['SESS_USERID']."'"; echo "<script>window.location='myreferrals.php?msgs=2';</script>"; mysql_query($query) or die(mysql_error()); } Advance thank you. Can you help please. The error..... Warning: mysql_fetch_assoc() expects parameter 1 to be resource, string given in C:\wamp\www\test_dabase.php on line 24 code. Code: [Select] <?php //database connection. $DB = mysql_connect("localhost","root") or die(mysql_error()); if($DB){ //database name. $DB_NAME="mysql"; //select database and name. $CON=mysql_select_db($DB_NAME,$DB)or die(mysql_error()."\nPlease change database name"); // if connection. }if($CON){ //show tables. $mysql_show="SHOW TABLES"; //select show and show. $mysql_select2="mysql_query(".$mysql_show.") or die(mysql_error())"; } //if allowed to show. if($mysql_select2){ //while it and while($data=mysql_fetch_assoc($mysql_select2)){ //show it. echo $data; } } ?> Hi, I need to insert some code into my current form code which will check to see if a username exist and if so will display an echo message. If it does not exist will post the form (assuming everything else is filled in correctly). I have tried some code in a few places but it doesn't work correctly as I get the username message exist no matter what. I think I am inserting the code into the wrong area, so need assistance as to how to incorporate the username check code. $sql="select * from Profile where username = '$username'; $result = mysql_query( $sql, $conn ) or die( "ERR: SQL 1" ); if(mysql_num_rows($result)!=0) { process form } else { echo "That username already exist!"; } the current code of the form <?PHP //session_start(); require_once "formvalidator.php"; $show_form=true; if (!isset($_POST['Submit'])) { $human_number1 = rand(1, 12); $human_number2 = rand(1, 38); $human_answer = $human_number1 + $human_number2; $_SESSION['check_answer'] = $human_answer; } if(isset($_POST['Submit'])) { if (!isset($_SESSION['check_answer'])) { echo "<p>Error: Answer session not set</p>"; } if($_POST['math'] != $_SESSION['check_answer']) { echo "<p>You did not pass the human check.</p>"; exit(); } $validator = new FormValidator(); $validator->addValidation("FirstName","req","Please fill in FirstName"); $validator->addValidation("LastName","req","Please fill in LastName"); $validator->addValidation("UserName","req","Please fill in UserName"); $validator->addValidation("Password","req","Please fill in a Password"); $validator->addValidation("Password2","req","Please re-enter your password"); $validator->addValidation("Password2","eqelmnt=Password","Your passwords do not match!"); $validator->addValidation("email","email","The input for Email should be a valid email value"); $validator->addValidation("email","req","Please fill in Email"); $validator->addValidation("Zip","req","Please fill in your Zip Code"); $validator->addValidation("Security","req","Please fill in your Security Question"); $validator->addValidation("Security2","req","Please fill in your Security Answer"); if($validator->ValidateForm()) { $con = mysql_connect("localhost","uname","pw") or die('Could not connect: ' . mysql_error()); mysql_select_db("beatthis_beatthis") or die(mysql_error()); $FirstName=mysql_real_escape_string($_POST['FirstName']); //This value has to be the same as in the HTML form file $LastName=mysql_real_escape_string($_POST['LastName']); //This value has to be the same as in the HTML form file $UserName=mysql_real_escape_string($_POST['UserName']); //This value has to be the same as in the HTML form file $Password= md5($_POST['Password']); //This value has to be the same as in the HTML form file $Password2= md5($_POST['Password2']); //This value has to be the same as in the HTML form file $email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file $Zip=mysql_real_escape_string($_POST['Zip']); //This value has to be the same as in the HTML form file $Birthday=mysql_real_escape_string($_POST['Birthday']); //This value has to be the same as in the HTML form file $Security=mysql_real_escape_string($_POST['Security']); //This value has to be the same as in the HTML form file $Security2=mysql_real_escape_string($_POST['Security2']); //This value has to be the same as in the HTML form file $sql="INSERT INTO Profile (`FirstName`,`LastName`,`Username`,`Password`,`Password2`,`email`,`Zip`,`Birthday`,`Security`,`Security2`) VALUES ('$FirstName','$LastName','$UserName','$Password','$Password2','$email','$Zip','$Birthday','$Security','$Security2')"; //echo $sql; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } else{ mail('email@gmail.com','A profile has been submitted!',$FirstName.' has submitted their profile',$body); echo "<h3>Your profile information has been submitted successfully.</h3>"; } mysql_close($con); $show_form=false; } else { echo "<h3 class='ErrorTitle'>Validation Errors:</h3>"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { echo "<p class='errors'>$inpname : $inp_err</p>\n"; } } } if(true == $show_form) { ?> I use this type of a code to send automatic emails from my website: Code: [Select] $headers = ; $headers .= ; $to = ; Click here to go to Google. ", $headers); I am having hard time figuring out how to do hyperlink on words (like here). If I do something like this: Code: [Select] <a href='http://www.google.com'>here</a> it spits out that exact thing out. Thanks you for your input Hi, Look at this code below: Code: [Select] <?php function outputModule($moduleID, $moduleName, $sessionData) { if(!count($sessionData)) { return false; } $markTotal = 0; $markGrade = 0; $weightSession = 0; $grade = ""; $sessionsHTML = ""; foreach($sessionData as $session) { $sessionsHTML .= "<p><strong>Session:</strong> {$session['SessionId']} <strong>Session Mark:</strong> {$session['Mark']}</strong> <strong>Session Weight Contribution</strong> {$session['SessionWeight']}%</p>\n"; $markTotal += round($session['Mark'] / 100 * $session['SessionWeight']); $weightSession += ($session['SessionWeight']); $markGrade = round($markTotal / $weightSession * 100); if ($markGrade >= 70) { $grade = "A"; } else if ($markGrade >= 60 && $markGrade <= 69) { $grade = "B"; } else if ($markGrade >= 50 && $markGrade <= 59) { $grade = "C"; } else if ($markGrade >= 40 && $markGrade <= 49) { $grade = "D"; } else if ($markGrade >= 30 && $markGrade <= 39) { $grade = "E"; } else if ($markGrade >= 0 && $markGrade <= 29) { $grade = "F"; } $moduleHTML = "<p><br><strong>Module:</strong> {$moduleID} - {$moduleName} <strong>Module Mark:</strong> {$markTotal} <strong>Mark Percentage:</strong> {$markGrade} <strong>Grade:</strong> {$grade} </p>\n"; return $moduleHTML . $sessionsHTML; } $output = ""; $studentId = false; $courseId = false; $moduleId = false; while ($row = mysql_fetch_array($result)) { if($studentId != $row['StudentUsername']) { //Student has changed $studentId = $row['StudentUsername']; $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})\n"; } if($courseId != $row['CourseId']) { //Course has changed $courseId = $row['CourseId']; $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong> <strong>Grade</strong> <br><strong>Year:</strong> {$row['Year']} </p>\n"; } if($moduleId != $row['ModuleId']) { //Module has changed if(isset($sessionsAry)) //Don't run function for first record { //Get output for last module and sessions $output .= outputModule($moduleId, $moduleName, $sessionsAry); } //Reset sessions data array and Set values for new module $sessionsAry = array(); $moduleId = $row['ModuleId']; $moduleName = $row['ModuleName']; } //Add session data to array for current module $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark'], 'SessionWeight'=>$row['SessionWeight']); } //Get output for last module $output .= outputModule($moduleId, $moduleName, $sessionsAry); //Display the output echo $output; } } } ?> This code allallows me to make calculations and display a student's course and linked with it the course the modules in the course and linked with modules are all the sessions. It is able to display what marks each student have got for each module and session. Now look at code below, it is able to display modules and in those modules the sessions that link to those modules: Code: [Select] <?php if($moduleId != $row['ModuleId']) { //Module has changed if(isset($sessionsAry)) //Don't run function for first record { //Get output for last module and sessions $output .= outputModule($moduleId, $moduleName, $sessionsAry); } //Reset sessions data array and Set values for new module $sessionsAry = array(); $moduleId = $row['ModuleId']; $moduleName = $row['ModuleName']; } //Add session data to array for current module $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark'], 'SessionWeight'=>$row['SessionWeight']); } What I want to know is how can I do something similar for course so that it picks out the right modules depending on the course it displays. There maybe some code that needs to be added in the function. Can I combine also HTML code in PHP function? For example, can a PHP function include HTML form and the PHP code to handle this form? If yes, this will make my main code much more smaller and readable. If not, is there a way to define an "external macro" like, which allow me to replace pre-defined lines of code with short alias? Can you help me integrate this code :
<form method="post" action="submit.php"> <input type="checkbox" class="required" /> Click to check <br /> <input disabled="disabled" type='submit' id="submitBtn" value="Submit"> </form>In to this Contact Form code, please? <form action="../page.php?page=1" method="post" name="contact_us" onSubmit="return capCheck(this);"> <table cellpadding="5" width="100%"> <tr> <td width="10" class="required_field">*</td> <td width="80">Your Name</td> <td><input type="text" name="name" maxlength="40" style="width:400px;/></td> </tr> <tr> <td class="required_field">*</td> <td>Email Address</td> <td><input type="text" name="email" maxlength="40" style="width:400px;/></td> </tr> <tr> <td></td> <td>Comments:</td> <td><textarea name="comments" style="width: 400px; height: 250px;"></textarea></td> </tr> </table> </form How can I make sure that when I submit an new form and new ID (record) is created it is always 4-Digits. record 14 = 0014, record 225 = 0225. Thanks |