Jump to content

Search the Community

Showing results for tags 'php'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. I have created a JSON file from the database, which has two table semone with attributes id, semester, cname and table courses with attributes coname and credit. Code I am writing in php is following. main.php <?php $user = "root"; $password = ""; $database = "scheduler"; $con = mysqli_connect("localhost", $user, $password, $database) or die ("Unable to connect"); $query = "SELECT semone.userid AS sbuid, semone.semester AS semester, semone.cname AS name, courses.credit AS value, courses.progskill AS skill FROM semone INNER JOIN courses ON semone.cname = courses.coname" ; $result = mysqli_query($con,$query)or die ("Unable to connect"); $info = array(); $test = array(); while ($row = $result->fetch_array(MYSQLI_ASSOC)) { $row['xyz'] = array( 'name'=> $row['name'], 'value'=> $row['value'] ); $info[$row['semester']]['children'][]= $row['xyz']; $data = json_encode(array('id' => $row['sbuid'], 'children' => $info)); } echo $data; ?> I want to get JSON file as seen in the following code, but I am getting something like this. **output.json** {"id":"12345", "children": {"first": {"children": [{"name":"CSE101","value":"100"}, {"name":"CSE102","value":"100"}]}, "second": {"children": [{"name":"CSE103","value":"50"}, {"name":"CSE104","value":"100"}, {"name":"CSE105","value":"100"}]}, "third": {"children": [{"name":"CSE106","value":"50"}]} }} But this is what I am expecting. **expected.json** { "id": 12345, "children": [{ "semester": "first", "children": [{ "name": "C101","value": 100}, { "name": "C102","value": 100}] }, { "semester": "second", "children": [{ "name": "C103", "value": 50}, {"name": "C104","value": 100}, {"name": "C105","value": 100}] }, { "semester": "third", "children": [{"name": "C106","value": 50}] } }
  2. Hey guys, I am looking for someone who can design an audio player that can also play a playlist for a website. The player I am looking for needs certain details. 1) Needs to hide src of file 2) Needs to have controls including attractive progress bar 3) Needs to read from mysql database. I am a bit of a programmer myself so I will be tweaking it but the skeleton must be there. Obviously willing to pay for your time please contact back.
  3. I am building a site that requires users to register and login to view and use certain parts of the site. When a user registers, an email is sent to them with a link that they need to click to activate their account. The link in the email contains the users email and an activation code and takes them to a page named 'activate' and checks the following conditions... If the email in the url exists in the database (This works) If the activation code in the url exists in the database (This works) If both of the previous conditions are true and the account active state is N then UPDATE `active` in database to Y thus allowing the user to login. (This works but not correctly) What I want to happen is... User registers > User gets email > *** (Anything before this point users cannot login. They will get a message telling them that their account has not been activated) *** > User clicks link > Users account is activated (`active` is changed from N to Y) > User can log in What I have is... User registers > *** (If the user logs in anytime after registration they can log in and the account is activated without clicking on the link in the email) > *** User gets email and clicks on the link > Goes to page and gets a message saying the account has already been activated. I have tested the conditions and if the email does or does't exist I get the correct messages and the same goes for the activation code, but the third seems to happen as soon as the email is sent to the user allowing them to log in before they click the link. Here is the where the email is sent... if ($OK) { // If OK insert data to database mysqli_query($db_connect, "INSERT INTO `users` (`uname`, `password`, `email`, `fname`, `lname`, `contact`, `house`, `street` `postcode`, `regdate`, `activationCode`, `active`) VALUES ('".$uname."', '".$passHash."', '".$email."', '".$fname."', '".$lname."', '".$contact."', '".$house."', '".$street."', '".$postcode."', '".$regdate."', '".$activationCode."', 'N')") or die(mysqli_connect_error()); // Set up email to send function email($to, $subject, $body) { @mail($to, $subject, $body, 'From: Example <info@example.com>'); } // Send email to user for account activation email($email, 'Activate your account', "Hello ".$uname."\nYou have recently created an account using the credentials...\n\nUsername - ".$uname."\nPassword - ".$password."\n\nPlease click the link below to activate your account.\nhttp://www.example.com/activate?email=".$email."&activationCode=".$activationCode."\n\nThank You.\n\n"); echo "<p>A message has been sent to ".$email.", please check your emails to activate your account.<p>"; echo "<p>If you do not receive the message in your inbox please be sure to check your junk mail too.</p>"; session_destroy(); } else { back(); exit(); } Here is the ACTIVATE page... if (isset($_GET['email'], $_GET['activationCode']) === true) { // If email and email code exist in URL $email = mysqli_real_escape_string($db_connect, trim($_GET['email'])); $activationCode = mysqli_real_escape_string($db_connect, trim($_GET['activationCode'])); $query = mysqli_query($db_connect, "SELECT * FROM `users` WHERE `email` = '".$email."' ") or die(mysqli_connect_error()); $result = (mysqli_num_rows($query) > 0); if ($result) { // Check email exists in database while($row = mysqli_fetch_assoc($query)) { if ($row['activationCode'] == $activationCode) { // Check activation code exists in database // THIS IS THE PART NOT WORKING CORRECTLY ----------------------------------------------------------------------------------------------------------------------------------------------------- if ($row['active'] == 'Y') { // Account is active echo $failed."<p>Your account has already been activated. You may <a href='/login'>Log In</a></p>"; } else { // Account not active mysqli_query($db_connect, "UPDATE `users` SET `active` = 'Y' WHERE `email` = '".$email."' LIMIT 1"); // Activate account echo $success."<p>Your account is now activated. You may <a href='/login'>Log In</a></p>"; } // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- } else { // Activation code is invalid echo $failed."<p>Hmmm, the activation code seems to be invalid!</p>"; } } } else { // Email does not exist echo $failed."<p>Hmmm, ".$email." does not seem to exist in our records!</p>"; } } else { header("Location: /login"); exit(); } Here is the LOGIN page... if (isset($_POST['login'])) { // Create variables from submitted data $uname = mysqli_real_escape_string($db_connect, $_POST['uname']); $password = mysqli_real_escape_string($db_connect, $_POST['loginPassword']); $password = md5($password); // Encrypt password $query = mysqli_query($db_connect, "SELECT * FROM `users` WHERE `uname` = '".$uname."' AND `password` = '".$password."' ") or die(mysqli_connect_error()); // Check if uname and password match $result = (mysqli_num_rows($query) > 0); if ($result) { // If uname and password match while($row = mysqli_fetch_assoc($query)) { if ($row['active'] == 'N') { // Account is not active echo "<p>Your account has not been activated! Please check your email inbox.</p><br />"; } else if ($row['active'] == 'Y') { // Account is active $_SESSION['uname'] = $_POST['uname']; header("Location: /profile"); } } } else { // If uname and password do not match echo "<p>The combination of username and password is incorrect!</p><br />"; } } else { // Default login(); register(); exit(); } Why it is not working correctly or what I am doing wrong? All help appreciated in advance.
  4. how to display image and data of user from mysql database on grid bootstrap index.php that is picture this my index.php index.php
  5. Hi I'm using PHP for my Navigation Menu, My navbar is in a file named "home.php" looks like this: <ul class="nav navbar-nav navbar-right"> <li><a href="?page=home">Home</a></li> <li><a href="?page=about">About</a></li> <li><a href="?page=services">Services</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="?page=service2">Service 2</a></li> </ul> </ul> Then in my index.php: $page = $_GET['page']; if (!isset($page)) { include('home.php'); } if ($page == "home") { include('home.php'); } if ($page == "about") { include('about.php'); } if ($page == "services") { include('services.php'); } if ($page == "service2") { include('service2.php'); } It all works how I want it to except for one thing; I'd like to add; <li class="active"> To the page that is currently being viewed. How can I do this? Thank you in advance.
  6. Howdy, I am currently re-writing some of the code of my history blog and I am thinking of uploading it to GitHub, since the newest codes seems very well written, in a way that I have gotten way better at programming. Since all of the future employers look at GitHub and they keep complaining I have merely tiny programs there, for some reason. Do you think this is a good idea, or my website will get hacked straight away? Also that will motive me to document it well and stuff. Of course I will skip the login script and all DB info. I am mainly doing it for my future employers to see the code I write, generally, without having to send tons of .rarS via email. Many Thanks in advance.
  7. Hello, I have stuck in here. Let me explain the background. Each Fiscal Year have Q1 until Q4. Each Quarter have different type form name. In a quarter may have more than 4 forms. So, each form is to track the points that the participant earn. One form allow more than one participant. One participant can participate in multiple form. So each participant have a total marks for each form. Please Have A Look The Attachment. Right now, I need to design a report to show Top 20 highest score participant. It can be cumulative from Q1 + Q2 + Q3 + Q4. Mean that, for example:- In This case. The data is less, so i highlighted Top 3 highest score. +---------------+ |Bill | 41 | |Aaron | 36 | |Gates | 27 | +---------------+ To produce this filter, the only way i can think off is to sum all the data in a database by name?? is that a good way? or is there any better way? Thank You
  8. [ code ]<?php $iKolommen = 5; $iGamesPerPagina = 60; $aSpelNamen = array( "bratz", "yasmine ski dressup", ); ?> [ / code ] I use above code to determine all games with name bratz and yasmin ski dressup in my database and to print them on my webpage. How can i print the exact number of all the games with those names ? Can you give me the exact code because i am a newbie in php. I tried a code but it only gives the number 2 because it counts the names and not the amount. Many thanks for your help in advance.
  9. Hey guys. I need some help to design some code(i prefer php/mysql). The project: The "Admins" must be able to mark if members shown up. The "Admins" must be able to add new members at the same time as they check them off.(this is where my problem is) The whole thing must create a new table in mysql when the day is over, and send a copy of the list to email. Im not that good at php, im only 16 years old. Hope that some of you can help me. I made a drawing of my idea (Paint ), Not pretty
  10. I am using this for multi image upload. https://github.com/CreativeDream/jquery.filer Since it doesn't show example of how to use it with a database, I am having a bit of an issue. The following is my code. Couple things. 1. It won't insert into database with the "tokens". If I remove the token code, then it'll work. The same token works in other forms that I use. 2. Yes It inserts into the database. The issue is that it inserts only 1 file at a time and not all the selected files. <?php require_once ($_SERVER['DOCUMENT_ROOT'] . '/home/templates/header.php'); if(isset($_POST['submit'])) { if($_POST['token'] === $_SESSION['token']) { if(isset($_FILES['files'])){ $date_added = date('Y-m-d H:i:s'); // Setting up folder for images $user_dir = $_SERVER['DOCUMENT_ROOT'] .'/home/members/images/'.$db_userid.'/records/'; if(!is_dir($user_dir)){ mkdir($_SERVER['DOCUMENT_ROOT'] .'/home/members/images/'.$db_userid.'/records/', 0775, true); } else { $uploader = new Uploader(); $data = $uploader->upload($_FILES['files'], array( 'limit' => 10, //Maximum Limit of files. {null, Number} 'maxSize' => 10, //Maximum Size of files {null, Number(in MB's)} 'extensions' => null, //Whitelist for file extension. {null, Array(ex: array('jpg', 'png'))} 'required' => false, //Minimum one file is required for upload {Boolean} 'uploadDir' => '../uploads/', //Upload directory {String} 'title' => array('auto', 10), //New file name {null, String, Array} *please read documentation in README.md 'removeFiles' => true, //Enable file exclusion {Boolean(extra for jQuery.filer), String($_POST field name containing json data with file names)} 'perms' => null, //Uploaded file permisions {null, Number} 'onCheck' => null, //A callback function name to be called by checking a file for errors (must return an array) | ($file) | Callback 'onError' => null, //A callback function name to be called if an error occured (must return an array) | ($errors, $file) | Callback 'onSuccess' => null, //A callback function name to be called if all files were successfully uploaded | ($files, $metas) | Callback 'onUpload' => null, //A callback function name to be called if all files were successfully uploaded (must return an array) | ($file) | Callback 'onComplete' => null, //A callback function name to be called when upload is complete | ($file) | Callback 'onRemove' => 'onFilesRemoveCallback' //A callback function name to be called by removing files (must return an array) | ($removed_files) | Callback )); if($data['isComplete']){ $files = $data['data']; print_r($files); } if($data['hasErrors']){ $errors = $data['errors']; print_r($errors); } function onFilesRemoveCallback($removed_files){ foreach($removed_files as $key=>$value){ $file = '../uploads/' . $value; if(file_exists($file)){ unlink($file); } } return $removed_files; } for($i = 0; $i < count($_FILES['files']['name']); $i++) { $name = $_FILES['files']['name'][$i]; $temp = $_FILES['files']['tmp_name'][$i]; $ext = pathinfo($name, PATHINFO_EXTENSION); $upload = md5( rand( 0, 1000 ) . rand( 0, 1000 ) . rand( 0, 1000 ) . rand( 0, 1000 )); $image_thumb_path = $user_dir . 'thumb_' . $upload . $ext; try { $insert_image = $db->prepare("INSERT INTO images(user_id, image_path, date_added) VALUES(:user_id, :image_path, :date_added)"); $insert_image->bindParam(':user_id', $db_userid); $insert_image->bindParam(':image_path', $image_thumb_path); $insert_image->bindParam(':date_added', $date_added); $result_image = $insert_image->execute(); if($result_image == false) { $error = 'There was a problem inserting images!'; } else { move_uploaded_file($temp, $image_thumb_path); $success = 'Your images has been saved.'; } } catch(Exception $e) { $error = die($e->getMessage()); } } } } } } ?> <h1>Upload Images</h1> <?php include_once ($dir_path . '/home/snippets/success-errors.php'); ?> <form action="" method="post" enctype="multipart/form-data"> <fieldset> <input type="file" multiple="multiple" name="files[]" id="input2"> <fieldset> <input type="hidden" name="token" value="<?php echo $_SESSION['token'] = md5(rand(time (), true)); ?>" /> <input type="submit" name="submit" class="red-btn" value="upload" /> </fieldset> </form> <?php require_once ($_SERVER['DOCUMENT_ROOT'] . '/home/templates/footer.php');
  11. Say I am uploading an image that gets resized. The resized image is a thumb. I have it's file path saved in the database and the image itself saved in a folder. Originally I was saving both to the database and folder. But now that I think about it, do I have to save the orginal image? Wouldn't I be saving up a lot of space if I only save the thumb image? What do you think?
  12. HI, first time making a website... would really appreciate help with any errors in my code. Thanks! <div id="site_content"> <div class="sidebar"> <!-- form to select what books would like to be viewed, i.e. what category? --> <h3>Search Our Library!</h3> <div class="form_style"> <form action='titleSearch.php' method='GET'> <center> <h1>Search Any Book Title: </h1> <input type='text' size='90' name='search'> <input type='submit' name='submit' value='Search' > </center> </form> <form action='catSearch.php' method='GET'> <center> <h1>Search Book Categories:</h1> <?php // make an sql query to show all of the book titles $titleSQL = "select class, description from l_classification order by class"; // connect to the database require_once('dbconnect.php'); // execute the query $rsTitle = mysql_query($titleSQL); echo "<select name=\"class\">\n"; echo "<option value=\"all\">Show all books</option>"; // loop through all of the book titles in the record set // while while($row = mysql_fetch_array($rsTitle)) { $class = $row['class']; $description = $row['description']; echo "\t<option value=\"$class\">$class : $description</option>\n"; } // each record i'll display as an option in the form // end loop ?> <input type='submit' name='submit' value='Search' ></br></br></br></center> </form> </select> </div> </body> </html>
  13. how can i use php to enter records into mysql using a transaction ; I have this stored procedure below.how can i excute itt using php to insert data from an array like this one: Array ( [Japanese] => Array ( [hot] => wasabi [salty] => soy sauce [sweety] => soy rdsauce [bitter] => pepper sauce ) [Chinese] => Array ( [hot] => wasabi [salty] => soy sauce [sweety] => soy rdsauce_one [bitter] => pepper sauce3 ) [indian] => Array ( [hot] => wasabi [salty] => soy sauce [sweety] => soy rdsauce [bitter] => pepper sauce4 ) [mexican] => Array ( [hot] => soanzo [salty] => soy sauce1 [sweety] => soy sauceeur [bitter] => pepper sauce_sausage ) [russian] => Array ( [hot] => soanzo [salty] => soy sauce1 [sweety] => soy sauceeur [bitter] => pepper sauce_pork ) [ganda] => Array ( [hot] => soanzo [salty] => soy sauce1 [sweety] => soy sauce_beef [bitter] => luwombo_chicken ) ) i have tried this so far but no good: include("config.php"); $strat_sql="call sp_addnewetails(?,?,?,?,?,?)"; $insert_t_stmt=$mysqli->prepare($strat_sql)or die($mysqli->error); #associate variables with the input parameters $insertt_stmt->bind_param("isssss",$my_prioid,$my_planid,$my_outcome_id,$my_Activities_id,$my_performanceIndicator_id,$my_target_id); #i=integer //aggregate the records to save $my_prioid =$_POST['strat_priorities']; $my_planid=stripslashes($plan); for ($i = 0, $num_specials = count($arr); $i < $num_specials; $i++) { for ($m = 0, $num_sub = count($arr[$i]); $m < $num_sub; $m++) { //save record $my_id=stripslashes($arr[$i][$m]); $my_Act_id=stripslashes($arr[$i][$m]); $my_p_id=stripslashes($arr[$i][$m]); $my_t_id=stripslashes($arr[$i][$m]); #Execute the statement $insert_t_stmt->execute( ) or die ($insert_t_stmt->error); $insert_t_stmt->bind_result($Entryerr); while ($insert_strat_stmt->fetch( )) { $error12=$Entryerr; if(substr($error12,0, 4)=="succ"){$suc=$error12;} } }//inner for } $insert_t_stmt->close( ); $mysqli->close( );
  14. I have a simple user login where it inserts the user session into database like this (id, user_id, hash). It works fine. I can delete the session from the database when the user logs out. Now I realized something. When I close the browser window, it'll destroy the session(log out the user) as intended but it won't delete the session from the database. I was wondering if there is a way to do that?
  15. Hi I'm trying to compare two tables with each other and update the 2nd table with the new updated name from table 1 via their unique identical ID $resultus = mysql_query("SELECT * FROM Users2"); $rowus = mysql_fetch_array($resultus); $naamus = urldecode($rowus['Username']); $mxitus = $rowus['mxitid']; $resultnup = mysql_query("SELECT * FROM pm"); $rownup = mysql_fetch_array($resultnup); $naamup = $rownup['username']; $ipup = $rownup['ip']; while($ipup == $mxitus){ $updatename = "UPDATE pm SET username= \"$naamus\" WHERE ip = \"$mxitus\""; mysql_query($updatename) or die("Error: ".mysql_error()); } The $mxitus and $ipup is the 2 fields that would be identical in both tables now Im trying to update the pm table username field with the naamus field from Users 2 any assistance please?
  16. $read1 = "unread"; $query = "INSERT INTO pm (username,mxitid,message,time,read,ip) VALUES (\"$naam\",\"$ip1\",\"$message\",\"$date\",\"$read1\",\"$banby2\")"; I'm getting the error This only happened when I added the read and value $read I got the field named read in my database.... any suggestion where im going wrong? If I remove the read field the rest of the query works 100%
  17. I am trying to include a file from another directory and so far I keep getting errors such as "failed to open stream: No such file or directory in...". Here's my directory setup. home/ /template/header.php /members/private/settings.php All I want to do is include "header.php" file on my "settings.php" page. Here's an example. settings.php <?php $dir = dirname(__FILE__); require_once $dir.'/template/header.php'; Can you tell me what's wrong with it? It's not working.
  18. I'm looking for an application or a social wall plugin to be added to a project. After looking at Wordpress and finally sifting through all the plugins (maybe all), I have come to a conclusion the plugins are not giving me enough customization options. For example, customizing the registration form. I need to add javascript for a combo box in order to display different options depending on what was selected. What I need - Your Opinion on a good social wall that's easy to make changes. I need a secure login and password --- PDO based A control panel would be nice to activate users or deactivate. A customized registration form Ability to add more pages, add php to customize it to work like I need it to. Responsive. If anyone has an opinion with experience on this matter it would be great to hear from you.
  19. I need new pair of eyes to look at this and tell me what's wrong with it. All I am trying to do is have a simple form that submits data to database. It works without the "token". With the token code added, it won't let process. I even did var_dump and the session and the $_post code doesn't match. Here's the code. Btw, session_start() and the database connection are in the init.php file. <?php require_once 'init.php'; $token = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM); $_SESSION['token'] = $token; if(isset($_POST['register'], $_POST['token'])) { if($_POST['token'] === $_SESSION['token']) { $email = trim($_POST['email']); $password = trim($_POST['password']); if(empty($email)) { $error = 'Email is required!'; } else if(empty($password)) { $error = 'Password is required!'; } else if(strlen($password) < 6) { $error = 'Password must be at least 6 characters long!'; } else { $findUser = $db->prepare("SELECT email FROM users WHERE email = :email"); $findUser->bindParam(':email', $email); $findUser->execute(); $resultFind = $findUser->fetchAll(PDO::FETCH_ASSOC); if(count($resultFind) > 0) { $error = 'The email already exists! Please try a different email!'; } else { //Hash the password as we do NOT want to store our passwords in plain text. $passwordHash = password_hash($passward, PASSWORD_BCRYPT, array("cost" => 12)); $insertUser = $db->prepare("INSERT INTO users(email, password) VALUES(:email, :password)"); $insertUser->bindParam(':email', $email); $insertUser->bindParam(':password', $passwordHash); $resultInsert = $insertUser->execute(); if($resultInsert == false) { $error = 'There was a problem creating your account. Please try again later!'; } else { $success = 'Your account has been created.'; unset($_SESSION['token']); } } } } else { $error = 'The tokens do not match!'; } } ?> <h1>Sign up</h1> <form action="" method="post"> <fieldset> <input type="email" name="email" value="<?php echo $email; ?>" placeholder="Email" /> </fieldset> <fieldset> <input type="password" name="password" placeholder="Password" /> </fieldset> <fieldset> <input type="hidden" name="token" value="<?php echo $token; ?>" /> <input type="submit" name="register" value="Sign up" /> </fieldset> </form>
  20. Hi, I have all the elements I need but I need to connect the dots... Situation... I have a job table that is brought in with this variable <?php $row = 1; if (($handle = fopen($statfile, "r")) !== FALSE) { echo '<table class="sortable" border="0">'; while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { if (substr($data[0],0,3)!='HDR' && substr($data[0],0,3) != 'JOB' ) continue; $num = count($data); if (substr($data[0],0,3)=='HDR') { echo '<thead><tr>'; }else{ echo '<tr>'; } for ($c=1; $c <= 4; $c++) { //echo $data[$c] . "<br />\n"; if(empty($data[$c])) { $value = " "; }else{ $value = trim($data[$c]); } if (substr($data[0],0,3)=='HDR') { echo '<th style="text-align:center">'.$value."</th>\n"; }else{ if ($c==1) { echo '<td style="text-align:center"><a href="http://wfbscd13/cgi-bin/aplog.cgi?type=job&logname='.$value.'&hostname='.$host.'" target="_blank">'.$value."</a></td>\n"; }else{ echo '<td style="text-align:center">'.$value."</td>\n"; } } } if (substr($data[0],0,3)=='HDR') { echo '</tr></thead><tbody>'; }else{ echo '</tr>'; } $row++; } echo '</tbody></table>'; fclose($handle); } ?> I attached a picture to show my screen... The right hand div with the list of jobs is on the right. I have it set so I can hover over the row and it highlights a row. Here is that code... It is jquery (1.9.1) <script type="text/javascript"> $("tr").not(':first').hover( function () { $(this).css("background","#d3d3d3"); }, function () { $(this).css("background",""); } ); </script> And finally the php query for the header.... <?php $row = 1; if (($handle = fopen("status.txt", "r")) !== FALSE) { echo '<table class="sortable" border="0">'; while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { if ($row > 1 && substr($data[0],0,3) != 'JOB' ) continue; $num = count($data); if ($row == 1) { echo '<thead><tr>'; }else{ echo '<tr>'; } for ($c=4; $c <$num; $c++) { //echo $data[$c] . "<br />\n"; if(empty($data[$c])) { $value = " "; }else{ $value = trim($data[$c]); } if (substr($data[0],0,3)=='HDR') { echo '<th style="text-align:center">'.$value."</th>\n"; }else{ if ($c==1) { echo '<td style="text-align:center">'.$value."</td>\n"; }else{ echo '<td style="text-align:center">'.$value."</td>\n"; } } } if (substr($data[0],0,3)=='HDR') { echo '</tr></thead><tbody>'; }else{ echo '</tr>'; } $row++; } echo '</tbody></table>'; fclose($handle); } ?> What I need is to show this last query in the header on hover of the first query.... But I can't seem to connect the dots... Can anyone help me?
  21. Hi all, I currently have a web app (php my first once actually) that accesses a MySql database. How I was handling the login was like this: This user enters the username and pw which gets sent to a stored procedure. If they successfully are validated I output a record (contains userid, first name and if they are logged in or not) and I set two session variables, 1 that stores a boolean if they are logged in (1 if they are, 0 if they are not) and the other stores the user id of that user (so I can use later to make sure they only get their data). I then check these session variables to 1.Make sure they are logged in and 2. Make sure they are only requesting their data (userid) I'm now going to be working on an Android app and make all the data access stuff a rest api that both the app and the website can consume. I modified the login stored procedure so it now will return a token as well. The token is generated on the DB(a hashed value of a couple of fields concatenated). When they log in successfully the token generated is stored in a user token table.(one user, one token) The table also stores a token_expire timestamp. Every time they log in a new token is created(and token_expire is updated). If they try to do something after the token expired (based on the token_expire field) then it should redirect them to login so a new token can be created. When I do the Android app, dealing with this and storing this token on the client is easy and there are many ways to store it (I was thinking storing it in a local sqlite table, shared_prefs (prob not the best way) etc..) and I would just parse through the json result. So keeping track of the token is easy with the app but my problem comes in with the PHP web site. So I'm faced with two issues: Issue 1. Right now I have a php form (with login and password fields) and it posts to a login process page which calls the stored procedure and if all is good redirects them to a dashboard page. Now if I use rest the post action would be something like: api/users/login instead of loginprocess.php correct? But then the api just spits out json and I'm not sure how to hand the result from the api to the php code. As when I change the post action I just get a white page with the json result string. So I need help knowing what to do once the api returns the result. Does this have to be called differently than a normal form submit? Do I just have the form submit call a js funcation that makes the call to the page and parses the result? Similar to something like this but instead of passing the cookie passing the login information? $opts = array('http' => array('header'=> 'Cookie: ' . $_SERVER['HTTP_COOKIE']."\r\n")); $context = stream_context_create($opts); session_write_close(); // unlock the file $contents = file_get_contents(url, false, $context); Issue 2. Once this token is generated in MySQL and sent back to the api, I need to pass it back to the PHP(related to #1) but How do I store it so that other pages of the site can send it when it requests the data? I know it has to be sent in the header in future requests and that's not my issue. My issue is where do I store the token on the web client so that other pages can use it? Should I store it in a client cookie? (but then doesn't this go against rest?) Store it in local storage? I'm pretty new to PHP and REST (was a classic ASP guy and just getting back into this stuff. This project is the first personal project for myself to learn this stuff and get the rust out) so I'm just trying to figure out the best way. I do not want to use sessions as that violates REST. I also do not want to use oauth or any 3rd party solution. I have been reading a lot about this but I'm still unclear as to how to go about these changes to the web version of the app and have it function properly. This is what my rest login api looks like so far (I know this will have to change but I'm stuck here with it): function loginUser() { global $app; $req = $app->request(); $paramUsername = $req->params('username'); $paramPassword = $req->params('password'); $sql = "CALL checkPassword(:username,:password)"; try { $dbCon = getConnection(); $stmt = $dbCon->prepare($sql); $stmt->bindParam("username", $paramUsername); $stmt->bindParam("password", $paramPassword); $stmt->execute(); $result = $stmt->fetchAll(); $loggedin=$result[0]["loggedin"]; $uid= $result[0]["uid"]; $fname=$result[0]["firstname"]; $token=$result[0]["token"]; $response["uid"]=$uid; $response["loggedin"]=$loggedin; $response["firstname"]=$fname; $response["token"]=$token; echo json_encode($response); $dbCon = null; } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } } Which returns: {"uid":"100","loggedin":"1","firstname":"John","token":"f0165d67221563bef150018276f4f77b7bd1e1763223e"} Here is what the form looks like calling the api currently: <form id="login" method="post" action="webservices/api/users/login"> <input class="my-class" style="width:20em" type="email" name="username" required> <input class="my-class" style="width:20em" type="password" name="password" required> <button type="submit" id="SubmitButton" name="submit" "></button> </form> Can anyone recommend the best way to deal with these two issues? Any help would be appreciated. Oh I should mention I'm using slim to help with the rest api's. TIA
  22. I have 3 variables coming from 3 columns from a table. I want to insert these variables into 3 columns in a different table. Variables are name, cover, and pageno. The issue is I can see the values in the hidden inputs this is when the page loads when nothing is selected in the combobox??? If I select book number two the same values are in the hidden inputs. If I select book one this is what I see because when the page loads it populates the values as book 1. <input type="hidden" name="cover" value="cover 1"> <input type="hidden" name="pageno" value="pageno 1"> If I select book two this is what I see. <input type="hidden" name="cover" value="cover 1"> <input type="hidden" name="pageno" value="pageno 1"> Make sense? If not, no matter which book I select I see the same values. Here's the code. <select name="name"> <option value="<?php echo "{$_POST['name']}"; ?>"> </option> <?php include('theconnection.php'); $con = mysqli_connect($host,$user,$pass,$dbName); if (!$con) { die('cannot connect: ' . mysqli_error($con)); } mysqli_select_db($con,"thebooks"); $result = mysqli_query($con,"SELECT * FROM books"); $result = mysqli_query($con,"SELECT b.id, b.name, b.cover, b.pageno FROM books"); $cover = ''; $pageno = ''; while($row = mysqli_fetch_array($result)) { echo ("<option value='$row[name]'>$row[name] $row[cover], $row[pageno] </option>"); $cover = "$row[cover]"; $pageno = "$row[pageno]"; } ?> </select> <input type="hidden" name="cover" value="<?php echo $cover; ?>"> <input type="hidden" name="pageno" value="<?php echo $pageno; ?>"> Maybe Javascript will work? I can't figure out how to do this with Javascript either.
  23. As you may know by now... I have some functions that generate the articles on my page + the comments associated with them (thanks to Barand and mac_gyver) function comment_form($id) { // generates a comment box form for every article on the page global $user_data; if (logged_in() === true) { echo " <form method='post' action='' class='comments_form'> <input type='text' name='username' placeholder='your name... *' id='name' value='{$user_data['username']}'> <div class='captcha'>" . create_captcha() . "</div> <textarea name='comments' id='textarea' placeholder='your comment... *' cols='30' rows='6'></textarea> <input type='hidden' name='blog_id' value='$id'> <input type='submit' name='submit' id='post' value='post'> </form> <hr class='artline'>"; } } function list_articles($rows) { if(empty($rows)){ return "There are no Articles to display"; } $previous_blog_id = 0; $content = ''; foreach($rows as $row) { if ($previous_blog_id != $row['content_id']) { // the blog id changed if($previous_blog_id != 0) { // not the first section, close out the previous section $content .= comment_form($previous_blog_id); } // start a new blog section $content .= "<h5 class='posted_by'>Posted by {$row['posted_by']} on {$row['date']}</h5> <h1 class='content_headers'>{$row['title']}</h1> <article>{$row['content']}</article> <hr class='artline'>"; $previous_blog_id = $row['content_id']; } if (!empty($row['comment_by']) && !empty($row['comments'])) { $content .= "<div class='commented_by'>User: {$row['comment_by']} </div> <div class='comments'>Comment: {$row['comments']}</div> <hr class='artline2'>"; } } if($previous_blog_id != 0){ $content .= comment_form($previous_blog_id); } return $content; } function insert_comments($comments, $comment_by, $blog_id) { include('core/db/db_connection.php'); $comment_by = sanitize($comment_by); $comments = sanitize($comments); $blog_id = (int)$blog_id; $sql = "INSERT INTO article_comments (comments, comment_by, blog_id) VALUES ('$comments', '$comment_by', '$blog_id')"; mysqli_query($dbCon, $sql); } I generate a simple math captcha like per below: function generate_captcha($num1, $num2) { // generates 2 random numbers $num1 = (int)$num1; $num2 = (int)$num2; $rand_num_1 = mt_rand($num1, $num2); $rand_num_2 = mt_rand($num1, $num2); $result = $rand_num_1 + $rand_num_2; return $result; } function create_captcha() { // displays captcha on the page $num1 = generate_captcha(1, 20); $num2 = generate_captcha(1, 20); echo $num1 . ' + ' . $num2 . ' = '; echo '<input type="text" name="captcha_results" size="2">'; echo '<input type="hidden" name=\'num1\' value=' . $num1 . '; ?>'; echo '<input type="hidden" name=\'num2\' value=' . $num2 . '; ?>'; } As you can see, I'm using the create_captcha() function into my comment_form() function because I want every comment box to have a captcha associated with it. The same way every article has it's own comment box. The above code is displaying a captcha field for each comment box I have, which is what I want. However - it moves all the comment boxes above the content making it look something like this: |-------------------------------------| // comments form for article 1 |Name: New User | |Comment: New comment ! | | | |-------------------------------------| [Submit] [captcha field] |-------------------------------------| // comments form for article 2 |Name: New User | |Comment: New comment ! | | | |-------------------------------------| [Submit] [captcha field] ========================================================== Article_1 title: LOREM IPSUM Content: LOREM IPSUM DOLOR SIT AMET.... -------------------------------------- //comments Name: User0 Comment: Great article! -------------------------------------- Name: User1 Comment: Great article! - 2nd comment -------------------------------------- // end comments ============================================================ Article_2 title: LOREM IPSUM Content: LOREM IPSUM DOLOR SIT AMET.... -------------------------------------- //comments Name: User0 Comment: Great article! -------------------------------------- Name: User1 Comment: Great article! - 2nd comment -------------------------------------- // end comments The behavior I am expecting is this: Article_1 title: LOREM IPSUM Content: LOREM IPSUM DOLOR SIT AMET.... -------------------------------------- //comments Name: User0 Comment: Great article! -------------------------------------- Name: User1 Comment: Great article! - 2nd comment -------------------------------------- // end comments |-------------------------------------| // comments form for article 1 |Name: New User | |Comment: New comment ! | | | |-------------------------------------| [Submit] [captcha field] ============================================================ Article_2 title: LOREM IPSUM Content: LOREM IPSUM DOLOR SIT AMET.... -------------------------------------- //comments Name: User0 Comment: Great article! -------------------------------------- Name: User1 Comment: Great article! - 2nd comment -------------------------------------- // end comments |-------------------------------------| // comments form for article 2 |Name: New User | |Comment: New comment ! | | | |-------------------------------------| [Submit] [captcha field] Is it something to do with the position in which I'm inserting the generate_captcha function that causes the comment boxes to float above content? I figured that in order to execute the captcha function I must insert in into the one that generates the comment form for the articles. Thank you.
  24. Hi I have 3 files profilepicf.php <html> <head> </head> <body> <form enctype="multipart/form-data" method="post" action="profilepic_new.php"> Choose your file here: <input name="uploaded_file" type="file"/><br /><br /> <input type="submit" value="Upload It"/> </form> </body> </html> profilepic_new.php <?php include $_SERVER['DOCUMENT_ROOT'] . '/chat2/chat_code_header.php'; $ip = $_SERVER["HTTP_X_MXIT_USERID_R"]; if(!isset($ip)) { $ip = "Debater"; } $result9 = mysql_query("SELECT * FROM Users2 WHERE mxitid = \"$ip\""); $row = mysql_fetch_array($result9); $id = $row['ID']; // Access the $_FILES global variable for this specific file being uploaded // and create local PHP variables from the $_FILES array of information $fileName = $_FILES["uploaded_file"]["name"]; // The file name $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true $fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename $kaboom = explode(".", $fileName); // Split file name into an array using the dot $fileExt = end($kaboom); // Now target the last array element to get the file extension // START PHP Image Upload Error Handling -------------------------------- if (!$fileTmpLoc) { // if file not chosen echo "ERROR: Please browse for a file before clicking the upload button."; exit(); } else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes echo "ERROR: Your file was larger than 5 Megabytes in size."; unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder exit(); } else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) { // This condition is only if you wish to allow uploading of specific file types echo "ERROR: Your image was not .gif, .jpg, or .png."; unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder exit(); } else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1 echo "ERROR: An error occured while processing the file. Try again."; exit(); } // END PHP Image Upload Error Handling ---------------------------------- // Place it into your "uploads" folder mow using the move_uploaded_file() function $moveResult = move_uploaded_file($fileTmpLoc, "images/".$id.".".$fileExt); // Check to make sure the move result is true before continuing if ($moveResult != true) { echo "ERROR: File not uploaded. Try again."; exit(); } // Include the file that houses all of our custom image functions include_once("ak_php_img_lib_1.0.php"); // ---------- Start Universal Image Resizing Function -------- $target_file = "images/".$id.".".$fileExt; $resized_file = "images/resized_".$id.".".$fileExt; $wmax = 320; $hmax = 240; ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt); unlink($target_file); // ----------- End Universal Image Resizing Function ---------- // ---------- Start Convert to JPG Function -------- if (strtolower($fileExt) != "jpg") { $target_file = "images/resized_".$id.".".$fileExt; $new_jpg = "images/resized_".$id.".jpg"; ak_img_convert_to_jpg($target_file, $new_jpg, $fileExt); unlink($target_file); } $new_jpg = "images/resized_".$id.".jpg"; if(!get_magic_quotes_gpc()) { $new_jpg = addslashes($new_jpg); $filePath = addslashes($filePath); } $result = mysql_query("UPDATE Users2 SET pprofilepic='$new_jpg', aprove='requested' WHERE mxitid='$ip'") or die(mysql_error()); // ----------- End Convert to JPG Function ----------- // Display things to the page so you can see what is happening for testing purposes echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />"; echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />"; echo "It is an <strong>$fileType</strong> type of file.<br /><br />"; echo "The file extension is <strong>$fileExt</strong><br /><br />"; echo "The Error Message output for this upload is: $fileErrorMsg"; ?> ak_php_img_lib_1.0.php <?php // ----------------------- RESIZE FUNCTION ----------------------- // Function for resizing any jpg, gif, or png image files function ak_img_resize($target, $newcopy, $w, $h, $ext) { list($w_orig, $h_orig) = getimagesize($target); $scale_ratio = $w_orig / $h_orig; if (($w / $h) > $scale_ratio) { $w = $h * $scale_ratio; } else { $h = $w / $scale_ratio; } $img = ""; $ext = strtolower($ext); if ($ext == "gif"){ $img = imagecreatefromgif($target); } else if($ext =="png"){ $img = imagecreatefrompng($target); } else { $img = imagecreatefromjpeg($target); } $tci = imagecreatetruecolor($w, $h); // imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h) imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig); if ($ext == "gif"){ imagegif($tci, $newcopy); } else if($ext =="png"){ imagepng($tci, $newcopy); } else { imagejpeg($tci, $newcopy, 84); } } // ---------------- THUMBNAIL (CROP) FUNCTION ------------------ // Function for creating a true thumbnail cropping from any jpg, gif, or png image files function ak_img_thumb($target, $newcopy, $w, $h, $ext) { list($w_orig, $h_orig) = getimagesize($target); $src_x = ($w_orig / 2) - ($w / 2); $src_y = ($h_orig / 2) - ($h / 2); $ext = strtolower($ext); $img = ""; if ($ext == "gif"){ $img = imagecreatefromgif($target); } else if($ext =="png"){ $img = imagecreatefrompng($target); } else { $img = imagecreatefromjpeg($target); } $tci = imagecreatetruecolor($w, $h); imagecopyresampled($tci, $img, 0, 0, $src_x, $src_y, $w, $h, $w, $h); if ($ext == "gif"){ imagegif($tci, $newcopy); } else if($ext =="png"){ imagepng($tci, $newcopy); } else { imagejpeg($tci, $newcopy, 84); } } // ------------------ IMAGE CONVERT FUNCTION ------------------- // Function for converting GIFs and PNGs to JPG upon upload function ak_img_convert_to_jpg($target, $newcopy, $ext) { list($w_orig, $h_orig) = getimagesize($target); $ext = strtolower($ext); $img = ""; if ($ext == "gif"){ $img = imagecreatefromgif($target); } else if($ext =="png"){ $img = imagecreatefrompng($target); } $tci = imagecreatetruecolor($w_orig, $h_orig); imagecopyresampled($tci, $img, 0, 0, 0, 0, $w_orig, $h_orig, $w_orig, $h_orig); imagejpeg($tci, $newcopy, 84); } ?> The problem I'm currently experiencing is when I try to upload PNG files, I get a black image and an error message while uploading it Any help related to this problem please
  25. Me again.. I've struggled for the past 2 hours to insert article comments and link them to an existent article on the page. Now, the function that is displaying both comments and articles looks like this: function list_articles() { include('core/db/db_connection.php'); $sql = "SELECT blog.content_id, blog.title, blog.content, blog.posted_by, blog.date, article_comments.comments, article_comments.comment_by FROM blog LEFT OUTER JOIN article_comments ON blog.content_id = article_comments.blog_id WHERE blog.content != '' ORDER BY blog.content_id DESC"; $result = mysqli_query($dbCon, $sql); $previous_blog_id = 0; while ($row = mysqli_fetch_array($result)) { if ($previous_blog_id != $row['content_id']) { echo "<h5 class='posted_by'>Posted by {$row['posted_by']} on {$row['date']}</h5> <h1 class='content_headers'>{$row['title']}</h1> <article>{$row['content']}</article> <hr class='artline'>"; $previous_blog_id = $row['content_id']; } if (!empty($row['comment_by']) && !empty($row['comments'])) { echo "<div class='commented_by'>Posted by: {$row['comment_by']} </div> <div class='comments'>Comments: {$row['comments']}</div> <hr class='artline2'>"; } } } The function I'm running to insert comments into article_comments table function insert_comments($comments, $comment_by, $blog_id) { include('core/db/db_connection.php'); $comment_by = sanitize($comment_by); $comments = sanitize($comments); $sql = "INSERT INTO article_comments (comments, comment_by, blog_id) VALUES ('$comments', '$comment_by', '$blog_id')"; mysqli_query($dbCon, $sql); } This works - it does the insertion, however I have no clue on how I could target the $blog_id variable when the user submits the post... The below is the form I use <?php echo list_articles(); if (!empty($_POST)) { insert_comments($_POST['comments'], $_POST['username'], 11); } ?> <form method='post' action='' class='comments_form'> <input type='text' name='username' placeholder='your name... *' id='name'> <textarea name='comments' id='textarea' placeholder='your comment... *' cols='30' rows='6'></textarea> <input type='submit' name='submit' id='post' value='post'> </form> I bet you noticed that I've manually inserted 11 as a param for the last variable. This links to blog_id 11 (the foreign key) in my article_comments table. It is displaying the comment just fine. Is there any way to target $blog_id without having to insert a number manually? Something like how I am targeting the $comments variable using $_POST['comments'] ? Also, even if I can target that, how do I know which post is the user commenting to? Should I give them the option to choose in a drop-down list ? That seems awkward.. but it's the only solution I can think of.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.