PHP - How To Access Database Fields As An Array Variables ?
Hi friends,
a quick print_r() shows the following array while connecting to my database. How to get them as individual items and display on the website ? Array ( [0] => Array ( [id] => 52 [document_name] => xyz [document_ext] => gif [download_file_name] => ktm_impact.gif [upload_dt] => 2010-08-11 ) ) Similar TutorialsHiya I was wondering how one would get make dynamic url variable value pairs from a databases fields. I have a database that I want to use to store variable value pairs that will be used on my pages for dynamic content. It will check one thing for certain besides if the variable value pair match. The table looks like this rpg loc_type loc_type template I want it to check if the rpg is in an array and then check if the url variable and value pair match on from the database. I dont know much about auto code that would generate this on its own and I'm not sure if you can say $_GET[$location]; I dont want to hard code it so it only works with what i code I want the urls variable value pair to be based on the database info which determines which template to show based on those values. Hello, A named field in an html form e.g. <input type="text" name="time"> is accessed as $_GET['time'] or $_POST['time'] by the processing script. What about an unnamed field like the one below: <input type="text" value="" id="1" /> How do I harvest this field's input as a variable from my php processing script? Thanks in advance I have a user class that is very dependent on the database class, which is why the user class extends the database. I tried creating a protected method in the parent class called getDBCObject, which returned the database object/variable/handle that I want the user to have access to. I tried the method below, but it doesn't work: <?php /* * @DATABASE * ~~~~~~~~~~~~ * @FILE DESCRIPTION: Handles all database related processes * @LAST MODIFIED: April 4, 2012 */ class database { protected $dbc; function __construct($db_host, $db_name, $db_user, $db_password) { try { $this->dbc = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password); } catch(PDOException $e) { echo '<b>An error occured while trying to create a database connection: </b>'. $e->getMessage(); } } /* * @METHOD getDBCObject * @DESC Gives the $dbc object/variable to its child classes */ protected function getDBCObject() { return $this->dbc; } } ?> My user class: <?php /* * @DATABASE * ~~~~~~~~~~~~ * @FILE DESCRIPTION: User related proccess * @LAST MODIFIED: April 5, 2012 */ class user extends database { protected $dbc; public function __construct() { if(parent::getDBCObject() == null) { echo '<br/>A database class/connection is required before creating the user class.'; } } public function isLoggedIn() { if($_COOKIE['user']) { //soon to come } else { return false; } } } ?> Any feedback on how I can let the user class use the $dbc variable in the database class? Ok here is what i got so far and now I am stuck. The user enters a number of how many squares (rectangles is note accurate) they wish to calculate. If its between 1 and 100 it continues, if its any other number it tells you to put in a number between 1 and 100. That was easy for me to do. If the number is between 1 and 100 it creates and input for length, width and height of each rectangle. creating the variables as it goes, i.e. "length$i" when $i is the while counter and increases to the ammount of rectangles you wished to view. Again, not that hard for me. So I am at the point where is I put in 50 I get length1 - through length30, width1 - width50, and height1 - height50. THis works great. However I now what to store those variables and calculate the area of each one via a while look which again creates an area$i variable which can be added (it would create area1 - area50 which I then wish to add together) Here is what I have so far. <?php session_start(); if (isset($_REQUEST['numpack'])) { if ($_REQUEST['numpack'] <= 0 || $_REQUEST['numpack'] > 100 ) { $error = "Please enter a number between 1 and 100"; echo $error; ?> <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <table width="0" border="0" cellspacing="5" cellpadding="5"> <tr> <td colspan="2">How many Squares</td> </tr> <tr> <td> <input name="numpack" type="text" size="4" maxlength="3"></td> <td><input type="submit" name="button" id="button" value="Submit"></td> </tr> </table> </form> <?php } else { ?> <form name="form2" method="post" action="<?php $_SERVER['PHP_SELF']; ?>"> <?php $i=1; while($i<=ceil($_REQUEST['numpack'])) { ?> <table width="325" border="0" cellspacing="5" cellpadding="5" style="float: left;" class="aluminium"> <tr> <td align="center" rowspan="2"><span class="transparent" style="color: #FFF; font-weight: bold;"><?=$i; ?>.</span></td> <td align="center">L</td> <td align="center">x</td> <td align="center">W</td> <td align="center">x</td> <td align="center">H</td> </tr> <tr> <td align="center"><input name="length<?=$i; ?>" type="text" size="4" maxlength="3"></td> <td align="center">x</td> <td align="center"><input name="width<?=$i; ?>" type="text" size="4" maxlength="3"></td> <td align="center">x</td> <td align="center"><input name="height<?=$i; ?>" type="text" size="4" maxlength="3"></td> </tr> </table> <?php $i++; } ?> </form> <?php } } If (!isset($_REQUEST['numpack'])) { ?> <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <table width="0" border="0" cellspacing="5" cellpadding="5"> <tr> <td colspan="2">How many Squares</td> </tr> <tr> <td> <input name="numpack" type="text" size="4" maxlength="3"></td> <td><input type="submit" name="button" id="button" value="Submit"></td> </tr> </table> </form> <?php } ?> Now I was reading up on session data and think this might be the best way to go, but again how do I do this? and two I want to make sure that if there are 2 people accessing it at the same time, it does not change the variables on them... (i.e. user one puts in 50 values, and user two puts in 50 different values I do not want cross contamination) Any ideas on how to proceed? Hi all. I'm working on a PHP application that will serve several clients. After a discussion on another thread about compliance, I've decided that using tables with a client specific prefix would be the safest way to go. However, I'm having a lot of trouble wrapping my head around what the database connection script would look like. I have a generic one that connects with host, user, pwd, and db as arguments but I'm not sure how to modify it to incorporate the table prefix requirement. Thoughts on how I can incorporate the aforementioned requirement and enhance the script in general? function connect_mysql($host,$user,$pass,$database){ $conn=mysql_connect($host,$user,$pass)or die('Cannot create link'); mysql_select_db($database)or die('Cannot select database'); }; Hi all, I am working on PHP to create a email client using imap. I have got a problem with using imap because it will get very slow so I want to find a way to make it to go faster. I have been researching that I have seen alot of people are using mysql database to store their emails and get access to their emails pretty quick than using imap. And I have also seen that roundcube are using mysql database to store contacts, emails...etc. I am not really sure what to do but I need your advice and I need your opinion. I have got questions for you. Do you think if I am better off to use imap or use mysql database to get access to my emails pretty quicker? If you think I am better off to use mysql database, then I want to know how I could store my emails in mysql and do I need to delete the emails in imap after I store the emails in mysql? Please let me know your opinion so I will decide what to do next. Thank you. Edited September 15, 2019 by mark107The title makes it sound more complicated than it is. I have a recurring function that searches for a specific value in a multi-dimensional array. When it finds it, it returns an array of the index. For example, if it found the value at $array[1][4][2][0], it would return an array like this: [0]=>1 [1]=>4 [2]=>2 [3]=>0 Here's the function. Code: [Select] <?php // Other Code /** * Find's the parent of an item * Unfortunately, it takes a bit more work than just using the loudspeaker at a grocery store * @param int $parent The parent to be searched for * @param array $array * @param array $cur_index */ private function findParent($parent, $array, $cur_index) { for($i = 0; $i < count($array); $i++) { // Search the array if($array[$i]['id'] == $parent) { // If the parent is found $cur_index[count($cur_index)] = $i; return array(true, $cur_index); } if(count($array[$i][1]) > 1) { // Call findParent again to search the child $cur_index[count($cur_index)] = $i; $found_in_child = $this->findParent($parent, $array[$i], $cur_index); if($found_in_child[0]) { return $found_in_child; } } } return array(false); // Return no matches } I need to be able to call that index using the keys from the key array (as we will call it). How can I do that? Thank you in advance for your help. Im doing a search system and Im having some problems.
I need to search in two tables (news and pages), I already had sucess doing my search system for just one table, but for two tables its not easy to do.
I already use a select statment with two tables using UNION because I want to show number of search results, that is number of returned rows of my first sql statment.
But now I need to do a select statment that allows me to acess all fields of my news table and all fields of my pages table.
I need to acess in my news table this fields: id, title, content, link, date, nViews
I need to acess in my pages table this fields: id, title, content, link
Im trying to do this also with UNION, but in this case Im not having any row returning.
Do you see what I have wrong in my code?
<?php //first I get my $search keyword $search = $url[1]; $pdo = connecting(); //then I want to show number of returned rows for keyword searched $readALL = $pdo->prepare("SELECT title,content FROM news WHERE title LIKE ? OR content LIKE ? UNION SELECT title,content FROM pages WHERE title LIKE ? OR content like ?"); $readALL->bindValue(1,"%$search%", PDO::PARAM_STR); $readALL->bindValue(2,"%$search%", PDO::PARAM_STR); $readALL->bindValue(3,"%$search%", PDO::PARAM_STR); $readALL->bindValue(4,"%$search%", PDO::PARAM_STR); $readALL->execute(); //I show number of returned rows echo '<p>Your search keyword returned <strong>'.$readALL->rowCount().'</strong> results!</p>'; //If dont return any rows I show a error message if($readALL->rowCount() <=0){ echo 'Sorry but we didnt found any result for your keyword search.'; } else{ //If return rows I want to show, if it is a page result I want to show title and link that I have in my page table //if it is a news result I want to show title and link that I have in my news table and also date of news echo '<ul class="searchlist">'; $readALL2 = $pdo->prepare("SELECT * FROM news WHERE status = ? AND title LIKE ? OR content LIKE ? LIMIT 0,4 UNION SELECT * FROM pages where title LIKE ? OR content LIKE ? LIMIT 0,4"); $readALL2->bindValue(1, '1'); $readALL2->bindValue(2, "%$search%", PDO::PARAM_STR); $readALL2->bindValue(3, "%$search%", PDO::PARAM_STR); $readALL2->bindValue(4, "%$search%", PDO::PARAM_STR); $readALL2->execute(); while ($result = $readALL2->fetch(PDO::FETCH_ASSOC)){ echo '<li>'; echo '<img src="'.BASE.'/uploads/news/'.$result['thumb'].'"/>'; echo '<a href="'.BASE.'/news/'.$result['id_news'].'">'.$result['title'].'</a>'; //if it is a news result I also want to show date on my list //echo '<span id="date">'.$result['date'].'</span>'; echo '</li>'; } echo ' </ul>'; //but how can I do my select statement to have access to my news table fields and my page table fields?? } ?> Hi Is it necessary to hash stored access and refresh tokens that are stored in a database. Both these tokens have limited lifespan (access token - 20 minutes but refresh token is 14 days). The reason I ask is I have hashed the tokens using the password_hash function but a user can have multiple active sessions if they want (so there is a sessions table with user id (not username), access token, token expiry date/time, refresh token and refresh token expiry date/time. So in order to refresh the access token I have to do a look up to see which session it relates to, what I have found is that I must retrieve all rows where the refresh token hasn't expired and then run password_verify against the tokens stored with the tokens provided to check each session to see if they match. What I have found is that it takes a while to run the password_verify function (by design I think) for each row (could be many if the users has been silly and logged in lots of time) which would cause an unacceptable delay when calling an API with an access token that needs refreshing (my tests resulted in times upwards of 30 seconds for a user who has around 10 active sessions). If both tokens were not hashed the same action to refresh a token for a user who has 10 active sessions takes less than a second which is much more acceptable. Edited December 15, 2018 by mds1256We have setup a member login page in CS5 using a myphpadmin database. We want to give members access to particular areas of our site depending on what username and password they enter. ie member 1 only requires access to specific documents/webpages - member 2 requires access to other documents/webpages. Not sure how to do this. Hi everyone! I'm getting the error "Access denied for user ''@'localhost' to database 'crystalair'" (crystalair is the name of my database) whenever I submit my form which inserts a new row to the database table "order". The same happens when I try to retrieve data from the table using select query. However, I can successfully perform operations (select, insert) in my other pages which involves another database table "user". If this is a connection error, how can I successfully perform operations with another table? Also, my connection query does not return an error. I have also checked to make sure my user has been granted "All Privileges" in the phpmyadmin. I've run out of ideas. Can you please help? Thanks a lot. When I send values to the foreach they are not recorded in the array. $x = $getProductID; $_SESSION['pColors'] = array(); if(isset($_POST['pColors'])) { foreach($_POST['pColors'] as $colorKey => $RColors) { $_SESSION['pColors'][$colorKey] = $RColors; } } var_dump($_SESSION['pColors']); Send date with AJAX: $('.addToCart').click(function(){ $.ajax({ url:""+realLink+"cart.php", method:"POST", data:{action:action,pColors:pColors}, success:function(data){ //alert(data); } }); }); Array ( [game] => Array ( [id] => 2011012593950636050 [name] => Array ( [us] => Castlevania II: Belmont's Revenge [uk] => Castlevania II: Belmont's Revenge ) echo print_r($this->game[0]['name']) but undefined offset error. I don't want to loop through the first array either. Thanks I am quite new to PHP and MySQL. I am trying to figure out what datatypes to use for different fields in a Database. For ID (Identification) I use INT, for name I use VARCHAR and for people to write text messages, I use LONGTEXT. For date and time I use DATETIME.
What I am unsure about, however, is what type to use for an email adress and for an IP address? I have been watching videos at Youtube about the Datatype for IP addresses, but they don't seem always to agree. I hope someone can put me in the right direction on those two.
Regards,
Erik
Hi can anybody help I need to export and download tables from a database into a excel sheet. I have this code and it works what I need is to export specific fields and not just the whole table can anyone help modifying the code to export certain fields within the table please? Here is the code... Code: [Select] <?php $host = 'localhost'; $user = 'user'; $pass = 'password'; $db = 'qdbname'; $table = 'tablename'; $file = 'export'; $link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error()); mysql_select_db($db) or die("Can not connect."); $result = mysql_query("SHOW COLUMNS FROM ".$table.""); $i = 0; if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $csv_output .= $row['Field']."; "; $i++; } } $csv_output .= "\n"; $values = mysql_query("SELECT * FROM ".$table.""); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j]."; "; } $csv_output .= "\n"; } $filename = $file."_".date("Y-m-d_H-i",time()); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("Y-m-d") . ".csv"); header( "Content-disposition: filename=".$filename.".csv"); print $csv_output; exit; ?> How would you access the number 10 in the $arr array? I am trying to pull images from my Flickr account with some success except that of accessing the description to be used as a caption for the image. What I have so far is:- Code: [Select] <?php //>>> Define some variables $maximgs = 5; $images = array(); $params = array( 'api_key' => '***********************', 'method' => 'flickr.photos.search', 'user_id' => '****************', 'sort' => 'date-posted-desc', 'format' => 'php_serial', 'extras' => 'description', ); $encoded_params = array(); foreach ($params as $key => $value){ $encoded_params[] = urlencode($key) . '=' . urlencode($value); } //>>> Make request and decode the response $url = 'http://api.flickr.com/services/rest/?' . implode('&', $encoded_params); $response = file_get_contents($url); $response_object = unserialize($response); //var_dump($response_object['photos']['photo']); //>>> Why is this returning 100 results? if($response_object['stat'] !== 'ok'){ echo "Something went wrong!"; } //>>> Select the required number of images ($maximgs) for($loop = 0; $loop <= $maximgs; $loop++){ $images = $response_object['photos']['photo'][$loop]; var_dump($images); //>>> Url of the individual image location for the img src. $imgurl = 'http://farm'.$images['farm'].'.'.'static'.'.'.'flickr.com/'. $images['server'].'/'.$images['id'].'_'.$images['secret'].'_n.jpg'; //>>> Url of the individual image for the link. $flkrurl = 'http://www.flickr.com/photos/'.$images['owner'].'/'.$images['id'].'/'; /*The complete Url (<a href="link($flkrurl)"> <img alt="$images['title']" src="image location"($imgurl) width="required width of image" /> </a>) */ $compurl = '<a href="'.$flkrurl.'" target="_blank">'.'<img alt="'. $images['title'].'" src="'.$imgurl.'" width="320px" /></a>'; //>>> Display Images echo $compurl . '<br />' . $images['description']['content']; //<<<<<< Line 66 } ?> Which annoyingly throws this error:- Notice: Undefined index: content in C:\wamp\www\php\flickr_test1.php on line 66 The result of a var_dump():- array 'id' => string '6914498038' (length=10) 'owner' => string '************' (length=12) 'secret' => string '601a885f31' (length=10) 'server' => string '7137' (length=4) 'farm' => float 8 'title' => string 'newhaven_15' (length=11) 'ispublic' => int 1 'isfriend' => int 0 'isfamily' => int 0 'description' => array '_content' => string 'Great reflections found in Newhaven Harbour.' (length=44) with the info that I want to extract underlined. What I can't figure out is how to find out the name of the array below "description =>". I have been scratching my head for several hours now and am no nearer to working it out. Maybe a genius here will have the solution. what am I doing wrong? I have an assoc array, but I can't seem to access it. Code: [Select] $var = Array ( 'domain' => asdfasdf.com 'port' => 2082 'adminuser' => admin 'INST_password' => adsfasdf 'adminnickname' => admin 'adminemail' => admin@asdfasdf.com 'sitename' => Play Bingo Online Austrailia 'description' => How to play bingo online in Australia 'site_root_path' => /home/chris/public_html/ 'theme' => default 'anchor_one' => How to play bingo online in Australia 'anchor_two' => play bingo 'anchor_three' => bingo online ) if( empty($var['domain']) ) exit; the code exits everytime. What am I missing? Hi all, I'm brand new to php / mysql and I'm trying to modify this script which currently runs a search on two fields "product_number" and "product_name". I also want the search to consider a third field "product_type". When I remove either product_name or product number from the following part of the code, it removes that field from being considered in the search: Code: [Select] $search_map = array($orderby, 'product_number','product_name',); So shouldn't I be able to just add the third field's name to this array and have it be considered too? I'm a complete beginner so I'm hoping this is a simple fix and I just dont get it. Here's the rest of what I think is the relevant code: Code: [Select] function load_all_products() { global $AppUI; global $sorted_item_list; global $additional_pfilter; load_type_list(); $orderby = 'product_id'; $search_map = array($orderby, 'product_number','product_name',); $where = $AppUI->getState( 'QuoteIdxWhere' ) ? $AppUI->getState( 'QuoteIdxWhere' ) : '*'; $not =" "; $op = " OR"; $check = substr(trim($where),0,4); if(stristr($check,"NOT")){ $op ="AND"; $not = " NOT "; $where = substr(trim($where),4); $where = trim($where); } // assemble the sql statement $q = new DBQuery; $q->addTable('products'); $q->addJoin('companies', 'com', 'products.product_company_id = com.company_id'); $q->addJoin('users', 'u', 'products.product_owner = u.user_id'); $q->addQuery('products.*, com.company_name, u.user_username'); $where_filter = " "; foreach($search_map as $search_name) $where_filter .=" $op $search_name $not REGEXP '$where'"; $where_filter = substr($where_filter, 5); // echo $where_filter; if($where != "*") $q->addWhere("($where_filter)"); $q->addOrder('product_id'); $sql = $q->prepare(); $q->clear(); $sql_list = db_exec( $sql ); if ($sql_list) $rn = db_num_rows( $sql_list ); else { echo db_error(); $rn = 0; } $product_list = array(); foreach ($sql_list as $item) { $product_list[ $item[ 'product_id' ] ] = $item; } // sort the list global $sort_state; if ( !isset( $sort_state ) ) $sort_state = getProductSortState(); if ( isset( $sort_state[ 'sort_item1' ] ) ) { if ( isset( $sort_state[ 'sort_item2' ] ) ) { $sorted_item_list = array_csort2( $product_list, $sort_state['sort_item1'], intval( $sort_state['sort_order1'] ) , $sort_state[ 'sort_item2' ], intval( $sort_state['sort_order2'] ) ); } else { $sorted_item_list = array_csort2( $product_list, $sort_state['sort_item1'], intval($sort_state['sort_order1']) ); } } else $sorted_item_list = array_csort2( $product_list, 'product_id' ); } Thanks! |