PHP - While Fetching Mysql
Hi,
I was wondering if any one can help me out with this little issue. I select some data, and put it on a while loop, so something like while($row = mysql_fetch_array($result)){ body } but at the very last element in the array I'd like to something a little different than else. So, i have 4 elements. For the first 3 I'd like to print element1, element2, element 3, element4 Notice the missing comma at element4 Similar TutorialsCan you add a WHERE clause in $row? For example: $row['city_display'] WHERE city_display = 1 $row['city_display'] WHERE city_display = 2 etc... How can this be done? I've just learned the basics of MySQL last night and made a simple app (where a user enters a song name, song title, and rating (out of 5) and it displays the list of songs with the highest rated songs first). So I decided I wanted to make something similar yet slightly more complicated and I'm not sure if I'm on the right track. Basically it's a "flash card" game whe - The user gets to input their own questions and answers into a simple form, which would then go into an MySQL table with 2 columns, questions and answers - A new page where the user see's random question, must input an answer, if the answer matches goes to next question otherwise gives error Now I'm confused as to how to go about making this. I was thinking of making some session variables and then do something along the lines of Code: [Select] $display_query = "SELECT * FROM questions"; $display = mysqli_query($connection, $display_query); while ($row = mysqli_fetch_array($display)) { $_SESSION['question'] = $row[0]; }[/syntax] //and then make some PHP that might do something like this: if ($_SESSION['answer'] != $row[1]) { echo "error, try again" } else { // I would write something here to grab the next question } So am I just completely off the wall with this, how would I make such an app? How would I make it, for example, fetch new questions? Hi , i am working on a PHP code that would fetch me the" title and the description" from another web page something similar to www.Digg.com .After searching a couple of Open source codes developed by some generous coder I found this piece of code: I have tested this code and it works fine, but the confusion here is it only works from external internet and Iam not able to extract the contents when i use the same piece of code from my office intranet(Our intranet has full access to the internet ) and the best part is when i use the same url for fetching content from Digg.com from my office intranet it works fine. The error I get is file_get_contents time out after 60 seconds OR I get a blank page result without any content But the same piece of code when used outside of my intranet works perfectly fine. Please let me know if you find anything incorrect! Thanks Code: [Select] <?php if(isset($_POST['submitlink'])) { function getMetaTitle($content){ $pattern = "|<[\s]*title[\s]*>([^<]+)<[\s]*/[\s]*title[\s]*>|Ui"; if(preg_match($pattern, $content, $match)) return $match[1]; else return false; } $url = $_POST['submitlink']; $data = array(); // get url title $content = @file_get_contents($url); $data['title'] = getMetaTitle($content); // get url description from meta tag $tags = @get_meta_tags($url); $data['description'] = $tags['description']; $dom = new domDocument; @$dom->loadHTML($content); $dom->preserveWhiteSpace = false; $images = $dom->getElementsByTagName('img'); foreach($images as $img) { $imgurl = $img->getAttribute('src'); $alt = $img->getAttribute('alt'); //$size = getimagesize($imgurl); //echo "Title: $alt<br>"; //echo $imgurl; //echo '<img src="'.$imgurl.'" title="'.$alt.'" width="50px"/>'; } $formdata .= '<table><tr><td>Title:</td><td><a href='; $formdata .= 'gethome.php?url='; $formdata .= $url; $formdata .= '>'; $formdata .= json_encode($data['title']); $formdata .= '</a></td></tr>'; $formdata .= '<tr><td>Description:</td><td> '; $formdata .= json_encode($data['description']); $formdata .= '</td></tr></table>'; } hello guys i heard there is a way that you can make something like a database on a text editor and when ever u want to change the info you just open a text editor and change the information How is this called? where can i find a tutorial? any tips? thanks you very much Hello, iam almost done with my project .. except there is one more thing left which somehow i cant manage to figure it out....... i manged to make a proxy array which rotates proxies randomly on every try..... but i want for my users to be able to add them manually via the textarea... so they put their proxies and as much as they want...... so then i guess explode should be used to fetch the proxies that were added by the user from the textarea and put them in an array like u see down and then with the curl array_rand it randomises them on evry try The real problem is i dnt know how to indetidy the explode cause iam not adding them manually they will be added via textare by users....... so when they add the ips they need to be fetched from the textare. THNX IN ADVACE $proxies = array( '000.000.000.00:000', <----------------- should i keep this ? cause ips will be added from textarea by users ? '000.000.000.00:000', '000.000.000.00:000', '000.000.000.00:000', ); curl_setopt($ch, CURLOPT_PROXY,$proxies[array_rand($proxies)]); <----- AFTER and array is made using exploit this will call it :) <textarea cols='22' class='area' rows='14' name='proxies'>PROXIES</textarea><br><input type='submit' value='Test'><br></p><p align='center' dir='ltr'><b> Edited by madmike3, 20 August 2014 - 05:29 AM. Hi,
I am working on coupon script which generate coupon.
The coupon script have two types, one is redemption and second one is printable in the same process it send sms to customer.
But issue is when it send SMS, sometime SMS works nice and lots of time SMS content got missing.
I could not understand why it happening. Is it scripting issue or another?
The script code as below:
----------------------------------------------------------------------------------------------------------
//Send coupon code to customer by SMS
$smsparameters = "select * from cs_options where option_id in ('23','24','25','26')";
if(!($smsparametersresult = mysql_query($smsparameters))) { echo $smsparameters.mysql_error(); exit; }
while($smsparametersrow = mysql_fetch_array($smsparametersresult)) {
$smsparametersarray[] = $smsparametersrow['option_value'];
}
define('SMS_SERVICE_URL', $smsparametersarray[0]);
define('KEY', $smsparametersarray[1]);
define('USERNAME', $smsparametersarray[2]);
define('PASSWORD', $smsparametersarray[3]);
$automationquery = "select * from cs_automation where automation_id='6'";
if(!($automationresult = mysql_query($automationquery))) { echo $automationquery.mysql_error(); exit; }
$automationrow = mysql_fetch_array($automationresult);
$automationrow['automation_value'];
if($automationrow['automation_value']=='1') {
$sms_order_id = $_SESSION['new_order_id'];
$current_date = date('Y-m-d');
$smsquery = "select * from cs_order as ord left join cs_customer as cust on ord.order_user_id = cust.customer_id where ord.order_id = '$sms_order_id'";
if(!($smsresult = mysql_query($smsquery))) { echo $smsquery.mysql_error(); exit; }
$sms_items = mysql_fetch_assoc($smsresult);
$order_coupon_id4 = explode(", ", $customer_email_items['order_coupon_id']);
foreach($order_coupon_id4 as $coup_id) {
$coupon_id = $coup_id['order_coupon_id'];
$query = "select * from cs_coupons as coup inner join cs_company as comp on coup.coupons_store = comp.retailer_id inner join cs_payments_currency as curr on coup.coupons_currency_id = curr.currency_id inner join cs_countries as cont on comp.country = cont.country_id inner join cs_states as stat on comp.state = stat.state_id inner join cs_cities as citi on comp.city = citi.city_id inner join cs_area as aria on comp.local_area = aria.area_id where coup.coupons_id = '$coupon_id'";
if(!($result = mysql_query($query))) { echo $query.mysql_error(); exit; }
$coupon = mysql_fetch_array($result);
$coup_name = $coupon['coupons_name'];
$coup_code = $coupon['coupons_code'];
$custdiscount = $coupon['coupons_product_discount'];
$coup_valid_date = date("d-m-Y", strtotime($coupon['coupons_exp_date']));
$couponcodeforsms = $sms_items['order_coupon_code'];
$couponcodeforsms1 = explode(", ", $sms_items['order_coupon_code']);
$smscount = count($couponcodeforsms1);
$mobilenoforsms = $sms_items['customer_mobile'];
$custnameforsms = ucwords($sms_items['customer_fname']);
$company_name = $coupon['company_name'];
$company_address = $coupon['city_name'];
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, "".SMS_SERVICE_URL."?user=".USERNAME."&password=".PASSWORD."&phone=".urlencode($mobilenoforsms)."&text=".urlencode('Hi '.$custnameforsms.', Coupon from CrackMyDeal : '.$coup_code.', '.$custdiscount.'% off on '.$coup_name.' at '.$company_name.', '.$company_address.', Valid till '.$coup_valid_date.'. T&C Apply.')."&type=t&senderid=".KEY."");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
}
}
----------------------------------------------------------------------------------------------------------------
The SMS which works nice:
Hi Paresh, Coupon from CrackMyDeal : CRACKD2014, 20% off on WebHosting (Business) at Unique InfoTech, Kamothe, Valid till 31-12-2014. T&C Apply.
--------------------------------------------------------------------------------------------------------------
And missing content SMS :
Hi Paresh, Coupon from CrackMyDeal : , % off on at , , Valid till 01-01-1970. T&C Apply.
-------------------------------------------------------------------------------------------------------------- Hello I have the following code Code: [Select] <?php // STORE DATABASE VARIABLES $hostname_cnConnection = "localhost"; $database_cnConnection = "tekou"; $username_cnConnection = "root"; $password_cnConnection = "1234"; $cnConnection = mysql_pconnect($hostname_cnConnection, $username_cnConnection, $password_cnConnection); mysql_set_charset('utf8',$cnConnection); // CONNECT TO DATABASE mysql_select_db($database_cnConnection, $cnConnection); $data = mysql_query("SELECT * from jos_users") or die(mysql_error()); // Print "<table border cellpadding=3>"; while($info = mysql_fetch_array( $data )) { // echo $info['id']; $prod_id=$info['id'] ; // echo "Product ID " .$prod_id; //Show Product Id mysql_query("UPDATE jos_vm_user_info SET first_name = '".$info['name']." WHERE user_id = ".$info['id']) or die(mysql_error()); } echo $info['id']; ?> I want to read every $name and update in jos_vm_user_info the first_name but I think I have error in code because nothing happens. I quess that .$info['id'] doesnt return a single number but all numbers but I dont know how to fix it. Please someone to help me. Hello, I'm using pbb forum http://xemix.pl/ When I tried to get topics using rss feeds module, I got this error. Code: [Select] Fatal error: Uncaught exception 'Exception' with message 'Erroe occured while loading url by cURL. Couldn't resolve host 'pbboard.com'' in /home/a5402323/public_html/includes/FeedParser.php:226 Stack trace: #0 /home/a5402323/public_html/includes/FeedParser.php(157): FeedParser->getUrlContent() #1 /home/a5402323/public_html/modules/admin/feeder.module.php(218): FeedParser->parse('http://absba.or...') #2 /home/a5402323/public_html/modules/admin/feeder.module.php(49): PowerBBFeederMOD->_AddFeedStart() #3 /home/a5402323/public_html/admin.php(89): PowerBBFeederMOD->run() #4 {main} thrown in /home/a5402323/public_html/includes/FeedParser.php on line 226 the host said thet Hello,cURL is installed by default here Many Thanks,Helpdesk Staff any help !!!! I'm trying to do a following feed. This feed includes posts and comments that the user is following.
The first 3 following types are in the content table and the last following type is in the comments table.
This query fetches the first 3 following types successfully.
$construct = $connectdb->prepare("SELECT parent.* FROM `content` as parent JOIN followers ftable on ( (ftable.parent_id=parent.sid AND ftable.userposts='1') OR (ftable.`parent_id`=parent.pageid AND ftable.topic='1') OR (ftable.parent_id=parent.pageid AND ftable.page='1') ) AND ftable.userid=:userid WHERE parent.deleted='0' GROUP BY parent.id ORDER BY parent.posted DESC");This query fetches the following comments type successfully $construct = $connectdb->prepare("SELECT parent.* FROM `comments` as parent JOIN followers ftable on ftable.parent_id=parent.postid AND ftable.comments='1' AND ftable.userid=:userid WHERE parent.deleted='0' ORDER BY parent.posted DESC");How do i combine the two queries? In this feed i want the results to be ORDER by posted DESC. my current code for getting a page is <?php $page = $_GET['page']; //Gets the (page=) from the URL if($page){ $site = file_exists($page.'.html') ? $page.'.html' : 'home.html';} else{ $site = 'home.html'; // Else include the default home.php file. } include($site); ?> the problem with it is it only checks for html pages. I would like to have it check for html then php pages and it pull up whichever is valid. i tried to do it myself but im a php n00b. pls help <?php $page = $_GET['page']; //Gets the (page=) from the URL if($page){ $site = file_exists($page.'.html') ? $page.'.html' : 'home.html';} elseif $site = file_exists($page.'.php') ? $page.'.php' : 'home.html'; else{$site = 'home.html'; // Else include the default home.php file. } include($site); ?> ^^ is what i did. any help will be appreciated. Thanks ok i display description from database with no isue but the thing is if there are links in description even the links like http://somesite.com shows as normal text on browser. how can i make them clickable? Hi guys, I am using a search form that's supposed to pull data out of database and display them. I managed to to do that using the following: while($rows = mysql_fetch_assoc($result)) { echo "-Title: " . $rows['title'] . "<br/>" . "-Author: " . $rows['author'] . "<br />"; Displays something like this: -Title: Young One -Author: Edwards Bonnie. ---------------------------------- I have links related to each book in a folder and I want to make the title clickable and each title should take me to the corresponding book page. I know that I have to do something like <a href=\"...........\">$rows['title']</a>", but as far as I know all titles will take me to one page using that! please help and thank you. Hi, I am trying to fetch a file with function file_get_contents() from a website, but am getting following error. [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in /data/22/1/27/17/1842180/user/1999295/htdocs/web/modules/index.php on line 14. using following code, Code: [Select] $content = file_get_contents($source); $handle = fopen($destination, 'wb'); fwrite($handle, $content); fclose($handle); does it have something to with http header, which might be required to set as HTTP/1.1 in php Regards, Abhishek I have a simple database set up for story awards given out by different groups. Here are some of the fields I'm using: Author Title Year Summary Some of the rows are nearly identical with the same Author and Title, but sometimes a different year or or others have a Summary for the story where otherwise it would be empty for a different row. The problem I'm having is I want to fetch the summary of the story from all rows where the Author and Title are identical. Currently the code is fetching a random row with the same Author and Title, but won't show the Summary if that specific row doesn't have the summary filled in (and where other rows of nearly identical information would have the summary). Here's an example of nearly identical rows: 'Boring Title', 'Boring Author', '', '2012' 'Boring Title', 'Boring Author', 'Boring Summary', '2012' How would I go about fetching all rows with the identical Author and Title and then showing the Summary even if only one of those rows has information in the Summary field? Much obliged for any help. Here's the code I'm working with: Code: [Select] <?php mysql_connect(localhost,db_user,pw); @mysql_select_db(db_database) or die( "Unable to select database"); $quer="SELECT * FROM archives ORDER BY RAND() DESC LIMIT 1"; $re = mysql_query($quer); while ($ro = mysql_fetch_array($re)) { extract($ro); $please = ''; if (strlen($ro[summary]) == 0) { $please = "The summary is empty. Please help the Archives by <a href=\"edit.php?cmd=edit&author=$author&title=$title\">filling out the summary</a>."; } $select_author = mysql_query("SELECT DISTINCT author FROM archives WHERE `title` = '" . mysql_real_escape_string($title) . "' ") or die (mysql_error()); $aut = ""; while ($row2 = mysql_fetch_array($select_author)) { $aut .= "<a href=\"author.php?author={$row2[author]}\">$row2[author]</a> & "; } $aut = substr($aut,0,-3); echo '<div style="margin: 5px;"> '.$summary.''.$please.' <p style="float: right; width: 100%; margin-top: 10px; text-align: right;"><i> ~ <a href="info.php?author='.$author.'&title='.$title.'">'.$title.'</a> by <a href="author.php?author='.$author.'">'.$aut.'</a></i> </div>'; } ?> hi
i am trying to fetch all my data from table
here is the code
function premiumview($cn,$table) { $table=mysqli_real_escape_string($cn,$table); $result=$cn->query("select * from $table"); if($result->num_rows >0) { while($f=$result->fetch_all(MYSQL_ASSOC)) { $result[]=$f; } return $result; } else { return $result=$cn->error; } }and the error is Fatal error: Cannot use object of type mysqli_result as array ( in while loop line ) What i am doing wrong? Hi, I am trying to migrate my project from mysql to mysqli but with little knowledge of the later. Among the noticeable errors is that the code is no longer fetching data from the database, and I am also getting UNDEFINED VARIABLE errors on the in the mysqli statement that should be binding results to variables. Here is the code if you can help: //set connection variables $host = "localhost"; $username = "root"; $password = "password"; $db_name = "mydb"; //database name //connect to mysql server $mysqli = new mysqli($host, $username, $password, $db_name); //check if any connection error was encountered if(mysqli_connect_errno()) { echo "Error: Could not connect to database."; exit; } //Just counting ...required for pagination... $query = "SELECT COUNT(*) FROM t_persons"; $result = mysqli_query($mysqli,$query) or die(mysqli_connect_errno()); $num_rows = mysqli_fetch_row($result); $pages = new Paginator; $pages->items_total = $num_rows[0]; $pages->mid_range = 9; // Number of pages to display. Must be odd and > 3 $pages->paginate(); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } if ($stmt = $mysqli->prepare("SELECT p.PersonID, p.ImagePath, p.FamilyName, p.FirstName, p.OtherNames, p.Gender, p.CountryID, p.StatusID, i.IncidentDate, i.IncidentCountryID, i.AgencyID, i.KeywordID FROM t_incidents i INNER JOIN t_incident_persons ip ON ip.IncidentID = i.IncidentID INNER JOIN t_persons p ON ip.PersonID = p.PersonID WHERE p.PersonID>0" . $likes . " ORDER BY p.PersonID DESC $pages->limit")) { /* Execute the prepared Statement */ $stmt->execute(); /* Bind results to variables */ $stmt->bind_result($PersonID,$ImagePath,$FamilyName,$FirstName,$OtherNames,$Gender,$CountryID,$StatusID,$IncidentDate,$IncidentCountryID,$AgencyID,$KeywordID); /* fetch values */ while ($rows = $stmt->fetch()) { // display records in a table // $PersonID=$row[0]; ?> <div class="thumbnail"> <a href=details.php?PersonID=<?php echo $PersonID ?> target=gallery><img src="./Persons_Images/<?php echo $row[1]; ?>" width="100" height="130" alt="" /></a><br> <a href="details.php?PersonID=<?php echo $PersonID; ?>"> <?php echo $row[2]; ?> <?php echo $row[3]; ?></a> </div> <?php }?> <?php } /* Close the statement */ $stmt->close(); /* close our connection */ $mysqli->close(); ?>I will appreciate. Joseph I have made an autocomplete form... originally the values were static: $aUsers = array( "Adams, Egbert", "Altman, Alisha", "Archibald, Janna", ); Now I want the values from a database table DEVICES row name DeviceName: $sql = "SELECT DeviceName FROM DEVICES"; $res = mysql_query($sql); $aUsers = array(); while ($row = mysql_fetch_assoc($res)) { $aUsers[] = $row; } It will not display the values in my autocomplete form when text is entered.... but with static data it will. Im confused! Thank you Hi, My name is stefan and I've been trying to develop a php/mysql based CRM for private use. I've stumbled upon a problem a few days ago and I just can't figure it out, so if you could help me, I'd really appreciate it. The problem is the following: I have 1 database which contains 5 tables. Each table has info in it but the primary key always is 'ID' 4 Tables are named; Zendingen | Klanten | Manden | Bestemmeling The last table, named 'Combination' has the unique ID of each of those 4 in it. The example will be given below. What I want to do now is create a page that shows all stored rows in 'Combination'-table, but gets the proper client_name or product_info out of the corresponding table. I have searched for it myself but I have no clue where to begin and how to define my searches so they all stranded. This is the piece of code. Code: (php) [Select] $Shipm1 = mysql_query("SELECT * FROM Shipments where Zending_ID = 9") or die(mysql_error()); while($row = mysql_fetch_assoc($Shipm1)) { echo "<br />"; echo $row["ID"]; echo "<br />"; echo $row["Zending_ID"]; echo "<br />"; echo $row["Klant_ID"]; echo "<br />"; echo $row["Mand_ID"]; echo "<br />"; echo $row["Bestemmeling_ID"]; echo "<br />"; }This code returns: Quote 3 ---- the ID of the 'combination' table and thus primary key 9 ---- Zending_ID 47 --- Klant_ID 17 --- Mand_ID 2 ---- Bestemmeling_ID 4 This is another row from the combinations table, 9 notice that it only returns the Zending_ID = 9. 49 21 4 Now this gives me the info I want, but it doesn't displays them how I need it to. I want it to search up each ID in the proper table and return me the product name, client name etc... Anyone who can help or point me in the right direction? Kind regards Stefan Hi,
I am wanting to bring information from a number of different tables. For an example I have used two tables.
The tables provide results from motorsport. I am wanting a page to display both sets of data WHERE skill is 'novice' for the novice championship. the novice championship includes events from cautotest and ctrial hence why i need both tables.
I have a table called cautotest and ctrial
They both contain the same structure apart from ctrial has more "rounds".
This is the coding for the page i have;
<?php $cnovice_results = mysql_query("SELECT * FROM cautotest, ctrial WHERE skill ='N'"); if(mysql_num_rows($novice_results) == 0) { echo "<p>No Results Available."; } else { echo "<table width=\"800\" border=\"0\" cellpadding=\"2\" cellspacing=\"2\" class=\"greywritinglight\" align=\"center\"> <tr align=\"center\"> <td>Competitor</td> <td>Vehicle</td> <td>Class</td> <td>autotest1</td> <td>autotest2</td> <td>trial1</td> <td>autotest3</td> <td>trial2</td> <td>Total</td> </tr>"; $x=1; while($results_row = mysql_fetch_array($cnovice_results)) { if($x%2): $rowbgcolor = "#FFFFFF"; else: $rowbgcolor = "#EEEEEE"; endif; echo "<tr align=\"center\" bgcolor=\"" .$rowbgcolor. "\">"; echo "<td>" . $results_row['competitor'] . "</td>"; echo "<td>" . $results_row['vehicle'] . "</td>"; echo "<td>" . $results_row['class'] . "</td>"; echo "<td>" . $results_row['autotest1'] . "</td>"; echo "<td>" . $results_row['autotest2'] . "</td>"; echo "<td>" . $results_row['trial1'] . "</td>"; echo "<td>" . $results_row['autotest3'] . "</td>"; echo "<td>" . $results_row['trial2'] . "</td>"; echo "<td>" . $results_row['total'] . "</td>"; echo "</tr>"; $x++; } echo "</table>"; } ?>Any help is appriciated Purpose: To get time zone of a remote file in my time zone. I have to download a file daily (mp3, don't worry its legal!) from BBC. Problem is that sometimes BBC doesn't update the file and i have to download entire file to check if it has been updated or not. Hence i decided to code a page that gives me date and time of that remote file. I have successfully compiled the code (that i got from internet). But the time returns in EST. I want the time in IST (indian std time Asia/Calcutta). CURLINFO_FILETIME has bee used. Below is code. Pls suggest me how to convert EST to IST - Warning: I am a newbie. But i can follow instructions Code: [Select] <?php $curl = curl_init('http://wsdownload.bbc.co.uk/hindi/tx/32mp3/din_bhar.mp3'); //don't fetch the actual page, you only want headers curl_setopt($curl, CURLOPT_NOBODY, true); //stop it from outputting stuff to stdout curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // attempt to retrieve the modification date curl_setopt($curl, CURLOPT_FILETIME, true); $result = curl_exec($curl); if ($result === false) { die (curl_error($curl)); } $timestamp = curl_getinfo($curl, CURLINFO_FILETIME); if ($timestamp != -1) { //otherwise unknown echo "BBC Hindi was last modified" . date("d-m-Y h:i:s A T", $timestamp); //etc } ?> I have used it with custom getRemoteFileSize function he - Code: [Select] http://island.web44.net/bbc.php |