PHP - Help Needed: Select Specific User Data From Mysql In Php
Hello. I'm a newbie so sorry if this isn't the best forum to post my problem.
I am using a MySQL and PHP to create a web app. I have authentication, and I can register users. I also have a form that users provide information and it is successfully inserting data into a table in my database.
I will use fictional fields for my database table called meal_info:
username
dateStartedDiet
numberMealsPerDay
costPerMeal
Problem: Select user-specific data from the MySQL database, using Session username to select only the current user's data, then display it and do some calculations.
Here is thecode at the top, and I am fairly sure it's working:
session_start(); //execute commone code
require("common.php"); //includes code to connect to database, etc.
if(empty($_SESSION['user']))
Similar TutorialsI've a simple Inset List (jQuery Mobile) of several items with a Flip switch, Drop down, check box and Slider elements. I have wrapped this Inset List inside a HTML Form. <code> <div data-role="fieldcontain"> <ul data-role="listview" data-inset="true"> <li data-role="list-divider"> Inhouse capabilities </li> <li> <label for="flip-b">Project Manager</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li> <label for="flip-b">Site Supervisor</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li><label for="flip-b">Architect</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li><label for="flip-b">Builderworks</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li><label for="flip-b">Electrical</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li><label for="flip-b">Mechanical</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li><label for="flip-b">Hydraulics</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li><label for="flip-b">Joinery</label> <select name="slider" id="flip-b" data-role="slider"> <option value="no">No</option> <option value="yes">Yes</option> </select> </li> <li> <label for="select-choice-1" class="select">Main Location:</label> <select name="select-choice-1" id="select-choice-1"> <option value="NSW">NSW</option> <option value="ACT">ACT</option> <option value="VIC">VIC</option> <option value="SA">SA</option> <option value="QLD">QLD</option> <option value="NT">NT</option> <option value="WA">WA</option> <option value="TAS">TAS</option> </select> </li> <!-- Select Menus: Main Location--> <li> <div data-role="fieldcontain"> <fieldset data-role="controlgroup"> <legend>CBA Reference</legend> <input type="checkbox" name="checkbox-1a" id="checkbox-1a" class="custom" /> <label for="checkbox-1a">Commercial</label> <input type="checkbox" name="checkbox-2a" id="checkbox-2a" class="custom" /> <label for="checkbox-2a">Retail</label> </fieldset> </div> </li> </ul> </div> <!-- End of Field Contain div tag --> <a href="#additionalinfo" data-role="button" data-inline="true" data-iconpos="left" data-theme="b">Additional Info</a> <a href="./search2.html" rel="external" data-ajax="false" data-role="button" data-inline="true" data-icon="search" data-iconpos="left" data-theme="e">Search</a> </code> I want to know, how I can include only the elements the user selected in my SQL query. Lets say, User wants to find the Electrical workers in QLD, then he will select Yes for Electrical and QLD as Main Location and the other items he would not touch. Now, how can I include only those two values in the select clause. Say, Select Electrical, Main Location from table where Main location='QLD'. I used POST method to gather users input. I use PHP, MySQL for this project. Any ideas on how to achieve this. Regards Sandeep Hello,
First of all I'd like to say thank you for all the great information on the forums, I've been reading a lot on here lately.
I've started to make a website where users can log in and submit items to a database, which is then displayed on another page.
If Tom and Bill both post 10 items, all 20 items will be displayed on the "listings" page, however on the main log in screen Tom will only see his own 10 items and Bill will see his own 10 items.
This is all working perfectly, however, I now need to add a delete button so that they can delete specific items.
I have loosely followed this tutorial here to get the table to display as I want it (amongst a few other things, such as the user logins) http://www.wickham43...mphptomysql.php
I've added the delete button in the PHP loop for each row, I just can't figure out how to delete the specific row when clicked.
Any help would be really appreciated
Edited by eklem, 22 October 2014 - 08:10 AM. I am not sure if the title is correct; I tried my best.
I'm a PHP/MySQL beginner and I really need some help.
I have a small script that I am using for sending SMS. I recently added a phonebook. The problem with the phonebook right now is that it's available to all users, i.e. they can all update and delete all rows. What I would like to do is make it so that each user can update and delete only their own contacts.
I have a table call contacts. Inside that table there is first name, last name, company and phonenumber.
How can I accomplish this with PHP & MySQL?
CREATE TABLE IF NOT EXISTS `contacts` ( `contact_id` int(10) NOT NULL AUTO_INCREMENT, `firstname` varchar(255) NOT NULL, `lastname` varchar(255) NOT NULL, `company` varchar(255) NOT NULL, `cell_no` text NOT NULL, PRIMARY KEY (`contact_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ; CREATE TABLE IF NOT EXISTS `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `users_name` varchar(30) NOT NULL, `uname` varchar(30) NOT NULL, `u_pass` varchar(60) NOT NULL, `utype` varchar(30) NOT NULL, `timezone` varchar(30) NOT NULL, `uapi_user` varchar(30) NOT NULL, `uapi_pass` varchar(60) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ; <?php if (isset($_POST['submit'])){ //form has been submitted1 $firstname = trim($_POST['firstname']); $lastname = trim($_POST['lastname']); $company = trim($_POST['company']); $cellno = trim($_POST['cell_no']); if($firstname == ''){ echo '<div class="alert alert-danger">First Name is not Valid!</div>'; exit; }elseif($lastname == ''){ echo '<div class="alert alert-danger">Last Name is not Valid!</div>'; exit; }elseif($company == ''){ echo '<div class="alert alert-danger">Company is not Valid!</div>'; exit; }elseif($cellno == ''){ echo '<div class="alert alert-danger">Cellphone Number is not Valid!</div>'; exit; }else{ $query = "Select cell_no from contacts where cell_no = '".$cellno."' "; $result = mysql_query($query); if (!mysql_num_rows($result)) { $sql = "INSERT INTO contacts(firstname, lastname, company, cell_no) values('{$firstname}','{$lastname}', '{$company}', '{$cellno}')"; $result = mysql_query($sql); confirm_query($result); //echo '<div class="alert alert-success">Successfully added.</div>'; //exit; ?> <script type="text/javascript"> window.location = "contact_list.php"; </script> <?php } else{ echo '<div class="alert alert-danger">Username. already exist!.</div>'; echo '<p><a href="new_contact.php" class="btn btn-success"> Back </a></p>'; exit; }} }else{ $firstname = ""; $lastname = ""; $company = ""; $cellno = ""; } ?> Hi, All: I'm trying to figure out what way it's the best way to pull info belonging to a specific user based on whether he's a logged-in "member", and want to make sure he's not able to access any other member's details... would the best way be to try to match the user's "username" stored in a $_SESSION when fetching his info, something like this: Code: [Select] <?php // Assume the login combo is this: $username = $_POST['username']; $password = $_POST['password']; // Assume he has already logged in: $_SESSION['username'] = $username; //EXAMPLE 1: SELECTING user info simply from actual DB username/password match: if ($_SESSION['username']) { $userRecords = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'"); $userInfo = mysql_fetch_array($userRecords); echo $userInfo['id'] . $userInfo['username'] . $userInfo['first-name'] . $userInfo['last-name'] . $userInfo['date-register']; } // EXAMPLE 2: or SELECTING user info based on $_SESSION['username'] value: if ($_SESSION['username']) { $userRecords = mysql_query("SELECT * FROM users WHERE username = . $_SESSION['username'] . AND password = '$password'"); $userInfo = mysql_fetch_array($userRecords); echo $userInfo['id'] . $userInfo['username'] . $userInfo['first-name'] . $userInfo['last-name'] . $userInfo['date-register']; } ?> So, my question is, are this actually working differently? is one better than the other as far as security, preventing other users from hacking either on purpose or accidenally into other user's details? thank! Appreciate any feedback... So I have an array of IDs that I would only like to select from a database table instead of everything in the table. How might I go about doing that? Hi, I have created a session based logon system using php and MYSQL from some tutorials I found online which is working very successfully. I can log on and of and move through different pages with no problems. My query is how do I output or display the information that is specific to the user which is currently logged on and block access to any other users information. I am quite sure there is a simple solution that is escaping me. If you could point me in the right direction it would be greatly appreciated. Thanks in advance I am trying to get specific data from a MySQL table but cannot seem to find a proper command. Code: [Select] $link = mysqli_connect('#####', '########', '########'); $user = $_SESSION['username']; $email = mysqli_query($link,"select email from members where username='$user'"); echo $email; Specifically, I am trying to get the email address stored for the user specified by the session, and display that address. However, I do not get any output with the current code, and am not sure what to try next. I have tried mysqli_fetch_row() but it only returns an error. Hi guys ..
please help me .. I don't know how to do this and I tried but there were no satisfied results..
I want to retrieve a Title (ing_title) from a database called k_db2 , in a table called content_langs
depending on its ID , which called ing_contID
example: if ing_contID=1 , then show the ing_title with this id ing_contID
the above code should be in a php file ..
then I want to include this php file inside the header of my website..
by importing the ing_contID from the database and depending on it the title should be shown..
I really tried but I couldn't find any solution ..
if you could help me in the first part of this problem I'll be glad ..
SELECT * FROM `booking_tbl` WHERE booking_status = 'Check In' AND departure_date_time = NOW()"I use the datetime datatype for the departure_date_time so i can get data from that data because it checking the date and time but i want it to check on the date from the datetime datatype So how can i get the data only with that date without the time in the mysql datetime datatype I have members.php: <?php /********************************************************************** Filename: members.php Version: $Id: members.php 17 2007-04-09 09:40:35Z Jez $ Description: This file displays the members screen once they've logged in. **********************************************************************/ /* Members script: */ include_once("config.php"); // Check user logged in already: checkLoggedIn("yes"); doCSS(); print("Welcome to the members page <b>".$_SESSION["login"]."</b><br>\n"); print("Your password is: <b>".$_SESSION["password"]."</b><br>\n"); print("<a href=\"logout.php"."\">Logout</a>"); ?> and functions.php: <?php /********************************************************************** Filename: functions.php Description: This file contains main stock of functions. This file is automatically 'include()'d by every page that include()'s the file 'config.php'. This has the benefit that every page that includes 'config.php' will have access to all of the functions in this file. **********************************************************************/ /******************************************************\ * Function Name : connectToDB() * * Task : create connection to db * * Arguments : none * * Globals: all defined in config.php * * Returns : none, sets $link * \******************************************************/ function connectToDB() { global $link, $dbhost, $dbuser, $dbpass, $dbname; /* Database connection: The PHP function mysql_pconnect() connects to a MySQL database with the arguments it is given. mysql_pconnect() creates a persistent database connection which can save some time when a number of mysql connections are made to the same db with the same user/password/dbhost triple. Further, when the execution of the PHP script ends, the connection to the database is NOT closed. In some rare cases this can cause problems. Alternatively mysql_connect() can be used and takes the same arguments as mysql_pconnect(). However mysql_connect() does not maintain a persistent connection - every call to mysql_connect() creates a new db connection. On a busy server this can significantly increase the amount of time taken to execute queries on the db. */ ($link = mysql_pconnect("$dbhost", "$dbuser", "$dbpass")) || die("Couldn't connect to MySQL"); // select db: mysql_select_db("$dbname", $link) || die("Couldn't open db: $dbname. Error if any was: ".mysql_error() ); } // end func dbConnect(); /******************************************************\ * Function Name : newUser($login, $pass) * * Task : Create a new user entry in the users table based on args passed * * Arguments : string($login, $pass) * * Returns : int($id), $id of new user * \******************************************************/ function newUser($login, $password) { /* Creating a New User Record in the DB: In this function we create a new user record in the db. We first build a query and save it into the $query variable. The query statement says: 'Insert the value of $login and $password into the 'login' and 'password' columns in the 'users' table' */ global $link; $query="INSERT INTO users (login, password) VALUES('$login', '$password')"; $result=mysql_query($query, $link) or die("Died inserting login info into db. Error returned if any: ".mysql_error()); return true; } // end func newUser($login, $pass) /******************************************************\ * Function Name : displayErrors($messages) * * Task : display a list of errors * * Arguments : array $messages * * Returns : none * \******************************************************/ function displayErrors($messages) { /* Error Handling functions: An error handling function is useful to have in any project. This particular function takes an array of messages, and for each message displays it in a list using HTML <ul><li></li></ul> tags. */ print("<b>There were problems with the previous action. Following is a list of the error messages generated:</b>\n<ul>\n"); foreach($messages as $msg){ print("<li>$msg</li>\n"); } print("</ul>\n"); } // end func displayErrors($messages) /******************************************************\ * Function Name : checkLoggedIn($status) * * Task : check if a user is (isn't) logged in depending on $status * * Arguments : quasi(!) boolean $status - "yes" or "no" * * Returns : * \******************************************************/ function checkLoggedIn($status){ /* Function to check whether a user is logged in or not: This is a function that checks if a user is already logged in or not, depending on the value of $status which is passed in as an argument. If $status is 'yes', we check if the user is already logged in; If $status is 'no', we check if the user is NOT already logged in. */ switch($status){ // if yes, check user is logged in: // ie for actions where, yes, user must be logged in(!) case "yes": if(!isset($_SESSION["loggedIn"])){ header("Location: login.php"); exit; } break; // if no, check NOT logged in: // ie for actions where user can't already be logged in // (ie for joining up or logging in) case "no": /* The '===' operator differs slightly from the '==' equality operator. $a === $b if and only if $a is equal to $b AND $a is the same variable type as $b. for example, if: $a="2"; <-- $a is a string here $b=2; <-- $b is an integer here then this test returns false: if($a===$b) whereas this test returns true: if($a==$b) */ if(isset($_SESSION["loggedIn"]) && $_SESSION["loggedIn"] === true ){ header("Location: members.php"); } break; } // if got here, all ok, return true: return true; } // end func checkLoggedIn($status) /******************************************************\ * Function Name : checkPass($login, $password) * * Task : check login/passwd match that stored in db * * Arguments : string($login, $password); * * Returns : array $row - array of member details on success * false on failure \******************************************************/ function checkPass($login, $password) { /* Password checking function: This is a simple function that takes the $login name and $password that a user submits in a form and checks that a row exists in the database whe the value of the 'login' column is the same as the value in $login and the value of the 'password' column is the same as the value in $password If exactly one row is returned, then that row of data is returned. If no row is found, the function returns 'false'. */ global $link; $query="SELECT login, password FROM users WHERE login='$login' and password='$password'"; $result=mysql_query($query, $link) or die("checkPass fatal error: ".mysql_error()); // Check exactly one row is found: if(mysql_num_rows($result)==1) { $row=mysql_fetch_array($result); return $row; } //Bad Login: return false; } // end func checkPass($login, $password) /******************************************************\ * Function Name : cleanMemberSession($login, $pass) * * Task : populate a session variable * * Arguments : string $login, string $pass taken from users table in db. * * Returns : none * \******************************************************/ function cleanMemberSession($login, $password) { /* Member session initialization function: This function initializes 3 session variables: $login, $password and $loggedIn. $login and $password are used on member pages (where you could allow the user to change their password for example). $loggedIn is a simple boolean variable which indicates whether or not the user is currently logged in. */ $_SESSION["login"]=$login; $_SESSION["password"]=$password; $_SESSION["loggedIn"]=true; } // end func cleanMemberSession($login, $pass) /******************************************************\ * Function Name : flushMemberSession($session) * * Task : unset session variables and destroy session * * Arguments : array $session * * Returns : true * \******************************************************/ function flushMemberSession() { /* Member session destruction function: This function unsets all the session variables initialized above and then destroys the current session. */ // use unset to destroy the session variables unset($_SESSION["login"]); unset($_SESSION["password"]); unset($_SESSION["loggedIn"]); // and use session_destroy to destroy all data associated // with current session: session_destroy(); return true; } // send func flushMemberSession() /******************************************************\ * Function Name : doCSS() * * Task : output the CSS for the screens * * Arguments : * * Returns : * \******************************************************/ function doCSS() { /* CSS Output: This function simply outputs some cascading style sheet data for markup by the user's browser. */ ?> <style type="text/css"> body{font-family: Arial, Helvetica; font-size: 10pt} h1{font-size: 12pt} </style> <?php } // end func doCSS() # function validates HTML form field data passed to it: function field_validator($field_descr, $field_data, $field_type, $min_length="", $max_length="", $field_required=1) { /* Field validator: This is a handy function for validating the data passed to us from a user's <form> fields. Using this function we can check a certain type of data was passed to us (email, digit, number, etc) and that the data was of a certain length. */ # array for storing error messages global $messages; # first, if no data and field is not required, just return now: if(!$field_data && !$field_required){ return; } # initialize a flag variable - used to flag whether data is valid or not $field_ok=false; # this is the regexp for email validation: $email_regexp="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|"; $email_regexp.="(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; # a hash array of "types of data" pointing to "regexps" used to validate the data: $data_types=array( "email"=>$email_regexp, "digit"=>"^[0-9]$", "number"=>"^[0-9]+$", "alpha"=>"^[a-zA-Z]+$", "alpha_space"=>"^[a-zA-Z ]+$", "alphanumeric"=>"^[a-zA-Z0-9]+$", "alphanumeric_space"=>"^[a-zA-Z0-9 ]+$", "string"=>"" ); # check for required fields if ($field_required && empty($field_data)) { $messages[] = "$field_descr is a required field."; return; } # if field type is a string, no need to check regexp: if ($field_type == "string") { $field_ok = true; } else { # Check the field data against the regexp pattern: $field_ok = ereg($data_types[$field_type], $field_data); } # if field data is bad, add message: if (!$field_ok) { $messages[] = "Please enter a valid $field_descr."; return; } # field data min length checking: if ($field_ok && ($min_length > 0)) { if (strlen($field_data) < $min_length) { $messages[] = "$field_descr is invalid, it should be at least $min_length character(s)."; return; } } # field data max length checking: if ($field_ok && ($max_length > 0)) { if (strlen($field_data) > $max_length) { $messages[] = "$field_descr is invalid, it should be less than $max_length characters."; return; } } } ?> The db has an table users with id, login, password, site Question how can i get inf from "site" raw for logged user on members.php ( as a link). Pls help thanks This is a continuation of a previous post. I am trying to get the names of countries that are in a database table. It's not working! All I get is a Submit button, but no data. This is what I understand from the code that Psycho suggested: I am unfamiliar with the function and the use of the FOREACH constuct. looking at the PHP manual there are two syntaxes. It appears that Psyhco has used the second form where the current element's key is assigned to $key variable for each itteration. foreach (array_expression as $key => $value The 2 variables he used are $id and $label I assume that the line: $optionsHTML = ''; is the array built from the expression: $optionsHTML .= "{$label}\n"; Because I was not familiar with the PDO method, but have used mysqli, I had to rewrite the data retrival part which I believe is OK. I guess that the line : $countryOptions = buildSelectOptions($countries); is used in conjunction with the function to build the array. The HTML part that Psycho wrote puts the variable into the Form format for a selection list. Why is the $optionsHTML also inclosed in the option tags? Have I got the HTML part correct or is it the data extraction part that is incorrect? Here is the code: <? include("AddStats_admin_connect.php"); //connect to database doDB(); //Function to build select options based on passed array function buildSelectOptions($options) { $optionsHTML = ''; foreach($options as $id => $label) { $optionsHTML .= "<option value='{$id}'>{$label}</option>\n"; } return $optionsHTML; } //Run query to get the ID and Name from the table //Then populate into an array $clist_sql = "SELECT CID, Country FROM Countries"; $clist_res= mysqli_query($mysqli, $clist_sql) or die(mysqli_error($mysqli)); if (mysqli_num_rows($clist_res) < 1) { //this Country not exist $display_block = "<p><em>You have selected an invalid Country.<br/> Please try again.</em></p>"; } $countries = array(); while($Ctry_info = mysqli_fetch_array($clist_res)) { $countries[$Ctry_info['CID'] = $Ctry_info['Country']]; } $countryOptions = buildSelectOptions($countries); ?> <!DOCTYPE html> <html lang="en"> <head> <title>Stats</title> <link rel="stylesheet" href="stylesheets/style.css" /> <!--[if IE]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <? echo $countryOptions; ?> </br></br></br></br></br></br></br></br> <!Later in the HTML for the page <form action="Ctrystats.php" method="post"> <option name="country" value=<? echo $countryOptions;?>Country</option></br></br> <input type="submit" value="Submit Choice"> </form></p> </body> </html>I think I am nearly there so I would appreciate some help to finish this coding. Note: If you make your questions easy to read, then you have better chances of a quality answer. Use [ code ] ] tags. Not sure why this isnt working. Code: [Select] <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script> <script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <LINK REL=StyleSheet HREF="inc/dyn_style.css" TYPE="text/css" MEDIA=screen /> <?php ?> <?php include('logic.inc'); mysqlConnect(); ?> <script type="text/javascript" src="bbeditor/ed.js"></script> <link rel="stylesheet" type="text/css" href="dyn_style.css" /> <title> Social </title> <script type="text/javascript"> function changeTitle(title) { document.title = title; } </script> </head> <body> <?php $inc = 'new_story.php'; $view = 'Newest '; $by = 'added'; $where = " "; $where2 = " "; $order = "ASC"; $gen = "All"; $rat = 'All'; $blerg = ""; $sort = 'newest'; //---------------------------------------------------------------------- if(isset($_GET['sub'])) { $sort = $_GET['sort']; switch($sort) { case "Most Popular"; $by = 'views'; $view = 'Most Popular '; $order = 'DESC'; break; case "Most Reviewed"; $view= 'Most Reviewed '; $by = 'reviews'; $order = 'DESC'; break; case "Newest"; $by = 'added'; $view = 'Newest'; $order = 'ASC'; break; } $genre = mysql_real_escape_string($_GET['cat']); $rating = mysql_real_escape_string($_GET['rat']); if($gen == 'All') { $where = " "; $blerg = ""; } else { $where = "WHERE cat='$gen'"; } if ($rat == "All") { $where2 = ' '; $blerg = 'AND'; } else { $where2 = $blerg ." rating = '$rat' "; } } //---------------------------------------------------------------------- ?> <?php serch(); ?> <form action="story.php" method="get"> <label id='inline'> Order By: </label> <select name='sort'> <option selected='yes' label='Currently Selected' > <?php echo $view; ?> </option> <option> Newest </option> <option> Most Popular</option> <option> Most Reviewed </option> </select> <input type='hidden' value='spec_view' name='p' /> <label id='inline'> Genre/Catagory: </label> <select name='gen'> <option selected='yes' label = 'Selected Genre - <?php echo $gen; ?>'> <?php echo $gen; ?> </option> <option> All </option> <option> Fantasy </option> <option> Adventure </option> <option> Science Fiction</option> <option> Drama</option> <option> Fable </option> <option> Horror</option> <option> Humor</option> <option> Realistic Fiction </option> <option> Tall Tale</option> <option> Mystery </option> <option> Mythology </option> <option> Poetry </option> <option> Shorty Story </option> <option> Romance </option> </select> <label id='inline'> Rating: </label> <select name='rat'> <option selected='yes' label = "Selected Genre - <?php echo $rat; ?>"> <?php echo $gen; ?> </option> <option> All </option> <option> C </option> <option> C13 </option> <option> YA </option> <option> A </option> </select> <input type='submit' value='Go!' name = 'go' /> </form> <?php $query = " SELECT * FROM story_info ORDER BY $by $order $where $where2 "; echo $query; $select = mysql_query($query) or die(mysql_error()); while($rows = mysql_fetch_assoc($select)) { $viewsdb = $rows['views']; $titledb = $rows['title']; $userdb = $rows['user']; $catdb = $rows['cat']; $ratdb = $rows['rating']; $id_db = $rows['story_id']; $sumdb = shorten($rows['sum']); echo "<h3><a href='?p=page&id=$id_db'> $titledb </a> </h3>"; echo "<div id='fun_info'>"; echo "$sumdb <br />"; echo "By <a href='?p=profile&user=$userdb'> $userdb </a> <br /> "; echo "$viewsdb Views | Rated: $ratdb | Catagory: <a href='?p=cat_view&gen=$catdb'> $catdb </a> </div>"; } ?> </div> </body> </html> I had this working, but when I try and get fancy and use AJAX the data doesn't display. I think this is a PHP problem though. My code for the select form including AJAX code Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-GB"> <head> <title>AJAX Example</title> <link rel="stylesheet" type="text/css" href="Form.css" media="screen" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("tr:odd").addClass("odd"); }); </script> <script type="text/javascript"> function showPlayers(str) { var xmlhttp; if (str=="") { document.getElementById("DataDisplay").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); else {// code for IE6, IE5 } xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("DataDisplay").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","Query.php?category_id="+str,true); xmlhttp.send(); } </script> </head> <body> <h1">AJAX Example</h1> <?php #connect to MySQL $conn = @mysql_connect( "localhost","username","pw") or die( "You did not successfully connect to the DB!" ); #select the specified database $rs = @mysql_SELECT_DB ("MyDB", $conn ) or die ( "Error connecting to the database test!"); ?> <form name="sports" id="sports"> <legend>Select a Sport</legend> <select name="category_id" onChange="showPlayers(this.value)"> <option value="">Select a Sport:</option> <?php $sql = "SELECT category_id, sport FROM sports ". "ORDER BY sport"; $rs = mysql_query($sql); while($row = mysql_fetch_array($rs)) { echo "<option value=\"".$row['category_id']."\">".$row['sport']."</option>\n "; } ?> </select> </form> <br /> <div id="DataDisplay"></div> </body> </html> Query.php <?php #get the id $id=$_GET["category_id"]; #connect to MySQL $conn = @mysql_connect( "localhost","username","pw") or die( "Error connecting to MySQL" ); #select the specified database $rs = @mysql_SELECT_DB ("MyDB", $conn ) or die ( "Could not select that particular Database"); #$id="category_id"; #create the query $sql ="SELECT * FROM sports INNER JOIN players ON sports.category_id = players.category_id WHERE players.category_id = '".$id."'"; echo $sql; #execute the query $rs = mysql_query($sql,$conn); #start the table code echo "<table><tr><th>Category ID</th><th>Sport</th><th>First Name</th><th>Last Name</th></tr>"; #write the data while( $row = mysql_fetch_array( $rs) ) { echo ("<tr><td>"); echo ($row["category_id"] ); echo ("</td>"); echo ("<td>"); echo ($row["sport"]); echo ("</td>"); echo ("<td>"); echo ($row["first_name"]); echo ("</td>"); echo ("<td>"); echo ($row["last_name"]); echo ("</td></tr>"); } echo "</tr></table>"; mysql_close($conn); ?> I think the problem is either with this part in the AJAX Code: [Select] xmlhttp.open("GET","Query.php?category_id="+str,true); or most likely in my Query.php code when I wasn't using AJAX and using POST it worked fine, but adding the AJAX stuff and GET it doesn't work. When I echo out the SQL the result is Code: [Select] SELECT * FROM sports INNER JOIN players ON sports.category_id = players.category_id WHERE players.category_id = '' so the category_id is not being selected properly and that is the primary key/foreign key in the MySQL table which connects the JOIN.
Hello. I activate the Payment Gateway Platform (by Redsys in Spain), and it works fine asking you for card number and it goes through correctly and says PAYMENT OK, but the notification.PHP FILE does not work. Could my server (SSL) configuration be the problem? or is it the CODE? Any help about this, please, would be highly appreciated. Thank you. Part of the Nofication.php code is: __________________________________________________________________________________
<?php $handle = fopen("_redsys.log", "a");
require_once("include/dbcommon.php"); $miObj = new RedsysAPI;
$version = postvalue("Ds_SignatureVersion");
// $version = "HMAC_SHA256_V1";
$claveModuloAdmin = 'sq7HjrUOBfKmC576ILgskD5srU870gJ7';
if ($signatureCalculada === $signatureRecibida && $res["Ds_AuthorisationCode"]!="++++++" && !isset($res["Ds_ErrorCode"]) {
$sql = "SELECT Espacio FROM Espacios WHERE Id_Espacio=" . $values["Id_Espacio"];
// echo '<img src="data:image/jpeg;base64,'.$imageData.'">';
_______________________________________________________________________________________________ Hi Guys, I am fairly new to mySQL/PHP and I have an issue. I have a login/registration system for a website and it works. However in the registration the user enters info such as their phone and email. How can I access these two fields of info from the user who is currently logged in. For example someone makes an account with: Username: Person Password: hello Email: person@gmail.com Phone: 111-111-1111 Name: Hello Person When they log into the site using their username and password, how can I detect their email/phone/name? Thanks in advance! I have this code that will get the absent dates for all employees, how can i make it for one specific employee using oracle id? code: $res = $conn->query("SELECT s.oracleid , s.staffname , date_format(date, '%W %d/%m/%Y') as absent FROM staff s CROSS JOIN date d LEFT JOIN attendance_records a ON s.oracleid = a.oracleid AND d.date = DATE(a.clockingindate) WHERE a.oracleid IS NULL ORDER BY s.oracleid, d.date "); the records i am concerned about is for the attendance records table, I have oracle id in that table. Hello, i am coding a backend portal, this portal will have staff members lets call them 'M1' and each staff member will have a client 'C1' What is the best way to put this into a database? do i have a table for Staff? then a seperate table for Members? or one table consisting of staff, with the members details written into the staff's row? Hi this is what I have set up - SQL tables - Members - memberid - primary key Username Password Orders - Orderid - primary key memberid - foreign key orderno In my sql table there are two members and two orders. 1 order is assigned to 1 member and the other order to the other member. After each member logs in I need to 'echo' that order on the page. I've not been able to write any succesful php code that 'gets' the specific order that is related to the member that has signed in. I would appreciate help on this! Thanks Hi guys, I am getting data from a json source: ``` $jsondata = file_get_contents($url);$response = json_decode($jsondata, true) echo "<pre>"; print_r(array_keys($response));; echo "</pre>"; ``` and this returns: ``` Array ( [0] => jsonapi [1] => data [2] => links ) ``` I want to extract data from specific key in the data array (eg 'title'): ``` [data] => Array ( [0] => Array ( [type] => recipes [id] => d6cd7643-6e44-4d26-9ed9-9da7196cef12 [attributes] => Array ( [internalId] => 7 [isPublished] => 1 [title] => Deep mediterranean quiche [createdAt] => 2019-05-07T13:34:27+0200 [updatedAt] => 2019-05-07T13:34:27+0200 [isPromoted] => 1 [path] => /recipes/deep-mediterranean-quiche [cookingTime] => 30 [difficulty] => medium [ingredients] => Array ( [0] => For the pastry: [1] => 280g plain flour [2] => 140g butter [3] => Cold water [4] => For the filling: [5] => 1 onion [6] => 2 garlic cloves [7] => Half a courgette [8] => 450ml soya milk [9] => 500g grated parmesan [10] => 2 eggs [11] => 200g sun dried tomatoes [12] => 100g feta ) [numberOfservings] => 8 [preparationTime] => 40 [instructions] => ``` How do I loop through the data array and select just the 'title' and 'difficulty' for example? Edited May 12, 2019 by ludo1960Hi, I've currently started to modify a chat script of mine to output a moderation panel but the moderation page seems empty(blank) every time I load it. What im trying to do is to take the ID part in my URL via the $_GET and look it up in my database table in the column named id, then select that specific row to be able to retrieve the StringyChat_ip and place it into another table to ban the IP and the second thing im trying to do is to be able to delete the specific row from my table.
My Http link look something like
http://imagecrab.fre.../ban.php?id=159
and my ban.php page where I want to lookup the 159 part and do the banning etc looks like
<? include("admin_code_header.php"); if ($_POST["DeletePost"]) { $id = $_POST['id']; $query = "DELETE FROM ".$dbTable." WHERE id='".$id."'"; mysql_query($query); echo "ID removed from system: ".$id; } if ($_POST["BanIP"]) { $IP_To_Add = $_POST["ip"]; $sql = "INSERT INTO ".$IPBanTable." (ip) VALUES (\"$IP_To_Add\")"; $result = mysql_query($sql); } $result = mysql_query("SELECT * FROM ".$dbTable." WHERE id='".$id."'",$db); while ($myrow = mysql_fetch_array($result)) { $msg = $myrow["StringyChat_message"]; $idm = $myrow["id"]; ?> <html> <form name="form<? echo $myrow["id"];?>" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <input name="DeletePost" type="submit" id="DeletePost" value="Delete"> <input name="BanIP" type="submit" id="BanIP" value="Ban <? echo $myrow["StringyChat_ip"];?>"> </form> </html> <? } ?> |