PHP - How To Reuse Mysql Result Array In Php
Similar TutorialsHi, I have come up with the following code, I need it to get the details of several scattered products and echo the results, the trick is I don't want it to echo the results one after the other... I want to have the products scattered between unique text on the page but don't want to run the query several times for performance reasons. E.g.- PAGE to look like this: $Product_1 unique text/images $Product_2 $Product_3 unique text/images $Product_4 Current Code: Code: [Select] <? $result = mysql_query("SELECT * FROM products where Product_ID IN (475, 465, 234, 567, 845)"); while($row = mysql_fetch_array($result)) { $x = "1"; while ($x<=3) { echo $x; $Product = "Product_"; $Product = $Product.$x; echo $Product; $Product = $row['Product_ID']; echo $Product; $x++; echo $x; } } At the moment it returns the following results: Quote 1 Product_1 465 2 2 Product_2 465 3 3 Product_3 465 4 1 Product_1 475 2 2 Product_2 475 3 3 Product_3 475 4 A few problems... In Blue... it duplicates for product 465 In Red... It repeats again for 475 Also.... it starts with 465, but I want it to go in order as how it appears - $result = mysql_query("SELECT * FROM products where Product_ID IN (475, 465, 234, 567, 845)"); so should start with 475 I want to get the following result: Quote 1 Product_1 475 2 2 Product_2 465 3 3 Product_3 234 4 4 Product_4 567 4 (and so on.....) If anyone could provide me assistance with my troubled 'while loop' statement that would be much appreciated! I'm self-studying PHP and put to myself to a task. But I can't figure this out. It's about putting a database result into array. There is this database called books with columns: isbn, author,title, price. The DB has records. I want to output certain records of certain columns:for example echo $books['title"];. I also to use functions. I used the following code to titles listing for example: function db_connect() { $result = new mysqli('localhost', 'root', 'password', 'books'); if (!$result) { return false; } $result->autocommit(TRUE); return $result; } function get_book_details($isbn) { // query database for all details for a particular book if ((!$isbn) || ($isbn=='')) { return false; } $conn = db_connect(); $query = "select * from books where isbn='".$isbn."'"; $result = @$conn->query($query); if (!$result) { return false; } $result = @$result->fetch_assoc(); return $result; } $book = get_book_details($isbn); foreach($book as $isbn => $qty){ echo $book['title']; } I have this error: Warning: Invalid argument supplied for foreach() in ..\foreach.php on line 41 I'm guessing that $book is not array that's why I get this error message. But the big problem is as you can see in the function function get_book_details($isbn) inside the function it already gets the result into array $result = @$result->fetch_assoc(); I have a list of ID's returned from a table (even number). I always used a loop to get the next result, but I want to put these straight into a new table INSERT INTO table VALUES ($ID1, $ID2); This is recursive till there are no more ID's. How do I get the result then the next result without loops. ID1 and ID2 cannot be null. What is the best way? How can I check if a returned mysql value is equal to '' i.e. nothing? I keep getting an error where the page won't load because the returned value is '' so i need to check for it This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=353485.0 Hi all, I'm new to PHP have written some code to extract data from mysql. here it is <!DOCTYPE html> <html lang="en"> result 1.png 18.34KB 0 downloads result 2.png 24.62KB 0 downloads Table.png 4.61KB 0 downloads <head> <meta charset="utf-8" /> <title></title> </head> <body> <?php echo "Testing Database....<br>"; $con = mysqli_connect('localhost', 'db_id', 'my_pw', 'mysql_db'); $result = $con->query("SELECT user_id FROM users"); echo "Number of users : ".$result->num_rows."<br><br>"; $row = mysqli_fetch_row($result); echo $row[0]."<br>"; echo $row[1]."<br>"; echo $row[2]."<br>"; ?> </body> </html> in result number of rows its giving right, but when i fetch the result in row, its giving only first row. rest all are empty. then further i have tested few more things like, i change the query as below 'SELECT * FROM users' now this is giving another strange result. It selected first row of the table and making array for all available columns. i have attached herewith image of my table, and result of both of my queries. Could someone guide me on this issue... Hello guys I have here my array result Array ( => Array ( => 1 [1] => [2] => 123456789 [3] => [4] => 2012-02-02 [5] => 09:12:21 [6] => Test Array ) ) I would like to view this result into a string so that it will remove the unnecessary array elements like brackets etc. Can some tell me how to handle this properly? The result would be : 1 123456789 2012-02-02 09:12:21 thanks $sql = "SELECT option_id, id FROM bets WHERE win_status = '1' AND updated_at BETWEEN '$today 13:00:00.000000' AND '$tmrw 08:00:00.000000'"; $result = mysqli_query($connt, $sql); foreach($result as $value) { $value[] = arary_multisort(); $oid = $value['option_id']; $gid = $value['id']; var_dump($value); //$gim = var_export($value); } foreach($result as $key => $value) { $info = array($value); } mysqli_close($connt); $fl = array($oid, $gid); print_r($fl);
array ( Either I can return 1 row and have the data sorted nicely or I can return an array but I can only seem to access the last array. Been stuck on this bit for atleast 2 hrs sadly. How can I rename the array? Some days I might have 100 results. Today we have two winners xP I really need to ctrl+z sublime cuz I tried what feels like everything. Ancy to move to the next part of this code MATH if you can kindly assist. Yall have been extremely helpful in my last two posts 2/2 going on 3. Is there a place I can properly contribute lite silver :3 Hi everyone, I really need some help with a project I'm working on. I have a table in MySQL that I am querying to pull out some data. This is the results I am getting from my query: ----------------------------------------------- | fld_id | fld_vl | ----------------------------------------------- | CLNT_NM | Motel1 | | CLNT_MGR | Frank | | CLNT_TMZ | EST | ----------------------------------------------- What I would like to do is get a variable for each fld_id and populate it with the field value. So, in essence it would look like this. $CLNT_NM = 'Motel1'; $CLNT_MGR = 'Frank'; $CLNT_TMZ = 'EST'; How can I do this? I have tried to figure this out but I can't seem to do it. Any help you guys can provide would be greatly appreciated. THANKS in advance!!! Hello, i created this script for a client and have ran into an annoying error with the results displaying on a new line for each result instead of side by side, any help is welcome Cheers Code: [Select] <?php $subcat = mysql_real_escape_string(strip_tags(htmlspecialchars(protect($_GET['subcat'])))); $cat = mysql_real_escape_string(strip_tags(htmlspecialchars(protect($_GET['cat'])))); $sql = @mysql_query("SELECT * FROM cakes WHERE category =\"$cat\" AND sub_cat=\"$subcat\" ORDER BY id DESC"); while ($row = mysql_fetch_array($sql)) { $reference = $row['reference']; $image = $row['image']; echo ("<p><img src='./images/cakes/$image' height='289px' width='177px' alt='IMAGE OF CAKE'></img><br />"); echo ("<b>Reference:</b>$reference"."</p>"); } if (!$reference) { echo 'There are no cakes in this category yet.'; } ?> I know the errors only going to be something small i'm missing, but i've been coding all day hello I'm using this code: Code: [Select] $query="SELECT * FROM `second_content` WHERE CHANGED =0 limit 0,1";to query first row data when I want see it and echo it I recived : Code: [Select] Resource id #2can anyone help me ? thank you Hi, I don't know anything about php and Mysql but I found a tutorial for a shopping cart and everything is working. The only thing is they don't have the email part in the totorial so I'm kind of stuck with my file. Anyone know how to email the resul to me via email with this code? <? include("includes/db.php"); include("includes/functions.php"); if($_REQUEST['command']=='update'){ $name=$_REQUEST['name']; $email=$_REQUEST['email']; $address=$_REQUEST['address']; $phone=$_REQUEST['phone']; $result=mysql_query("insert into customers values('','$name','$email','$address','$phone')"); $customerid=mysql_insert_id(); $date=date('Y-m-d'); $result=mysql_query("insert into orders values('','$date','$customerid')"); $orderid=mysql_insert_id(); $max=count($_SESSION['cart']); for($i=0;$i<$max;$i++){ $pid=$_SESSION['cart'][$i]['productid']; $q=$_SESSION['cart'][$i]['qty']; $price=get_price($pid); mysql_query("insert into order_detail values ($orderid,$pid,$q,$price)"); } die('Thank You! your order has been placed!'); } ?> <!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Billing Info</title> <script language="javascript"> function validate(){ var f=document.form1; if(f.name.value==''){ alert('Your name is required'); f.name.focus(); return false; } f.command.value='update'; f.submit(); } </script> </head> <body> <form name="form1" onsubmit="return validate()"> <input type="hidden" name="command" /> <div align="center"> <h1 align="center">Billing information</h1> <table border="0" cellpadding="2px"> <tr><td>Total:</td><td><?=get_order_total()?></td></tr> <tr><td>Name :</td><td><input type="text" name="name" /></td></tr> <tr><td>Address :</td><td><input type="text" name="address" /></td></tr> <tr><td>Email :</td><td><input type="text" name="email" /></td></tr> <tr><td>Phone :</td><td><input type="text" name="phone" /></td></tr> <tr><td> </td><td><input type="submit" value="Place Order" /></td></tr> </table> </div> </form> </body> </html> Im not sure where to post this but since it includes php il post it here instead of in the mysql forum. ok so, i have a table and i get the values using while($row = mysql_fetch_array($result)){ and then echo them in rows. that works fine but i need to add a class to the last row of my table. I would need somehow to fetch the last row of the array and make it echo something different. Any help is appreciated Thank you Hi, I have attached sql script for table structure and sample data. When I run following sql query ,I get result set. Code: [Select] select * from tablename order by col10 desc I want to create array using result set. Following is the require structure of array. Code: [Select] <?php $resultSet[]=array ( ('0') =>array ( ('col10value1') => array ( ('0') => array ( ('col1') => 'col1', ('col2') => 'col2', ('col3') => 'col3', ('col4') => 'col4', ('col5') => 'col5', ('col6') => 'col6', ('col7') => 'col7', ('col8') => 'col8', ), ('1') => array ( ('col1') => 'col1', ('col2') => 'col2', ('col3') => 'col3', ('col4') => 'col4', ('col5') => 'col5', ('col6') => 'col6', ('col7') => 'col7', ('col8') => 'col8', ), ), ), ('1') => array ( ('col10value2') => array ( ('0') => array ( ('col1') => 'col1', ('col2') => 'col2', ('col3') => 'col3', ('col4') => 'col4', ('col5') => 'col5', ('col6') => 'col6', ('col7') => 'col7', ('col8') => 'col8', ), ), ), ); ?> im getting an error: Warning: mysql_fetch_array() [function.mysql-fetch-array]: The result type should be either MYSQL_NUM, MYSQL_ASSOC or MYSQL_BOTH. in C:\www\library\mysql.class.php on line 353 $result_type = "MYSQL_ASSOC"; $row = mysql_fetch_array($result, $result_type) but if i use (below) it works fine...is the constant() function the right way to what im doing? $result_type = "MYSQL_ASSOC"; $row = mysql_fetch_array($result, constant($result_type)) thank you hey guys, i need some help with my php/mysql iplogger. My code: <?php //finds out ip $ip = $_SERVER['REMOTE_ADDR']; //conects to the mysql server $connection = mysql_connect('localhost', 'root', ''); //sellects the database mysql_select_db('iplog', $connection); //looks for duplacute ips $dup = mysql_query("SELECT COUNT(number) FROM logged_ips WHERE ip_address = '$ip'",$connection); $count = mysql_result($dup, 0); //checks to see if there is a duplecate name if ($count == 0){ //inserts the ip in to the database $string = 'INSERT INTO `logged_ips` (`aid`, `ip_address`, `ip_visits`) VALUES (\'' . null . '\', \'' . $ip . '\', \'0\')'; mysql_query($string, $connection); }else{ //adds a visit to the database $string2 = "UPDATE `logged_ips` SET `ip_visits` = '++1' WHERE `ip_address` = $ip LIMIT 0,1"; mysql_query($string2, $connection); } //outputs the ip echo $ip; ?> error: Warning: mysql_result() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\randoms\logger\test.php on line 11 127.0.0.1 It also doesnt put anything in to the mysql database. Please help. Thanks jragon Hi, I am new to php but not to programming. I created a script on a windows platform which connects to the mysql database and returns the results of a table. A very basic script which I wrote to simply test my connection worked. The script works fine on my windows machine but not on my new mac. On the mac it simply does not display any records at all. I know that the database connection has been established because there is no error but I can not see why the result set is not being displayed on screen, as I said it worked fine on my windows machine. The Mac has mysql (with data) and apache running for php. Please could someone help as I have no idea what to do now? Script below: Code: [Select] $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'root'; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); $dbname = 'test'; mysql_select_db($dbname); mysql_select_db("test", $conn); $result = mysql_query("SELECT * FROM new_table"); while($row = mysql_fetch_array($result)) { echo $row['test1'] . " " . $row['test2'] . " " . $row['test3']; echo "<br />"; } mysql_close($con); I am seeking to learn more about the noted subject, how to use PHP to allow a user to enter search terms and search a database. I have experimented with this with little results save for errors. Please see code listed below: search.php <? //// filename = search.php <form method="post" action="result.php3"> <select name="metode" size="1"> <option value="row_name1">metode1</option> <option value="row_name2">metode2</option> </select> <input type="text" name="search" size="25"> <input type="submit" value="Begin Searching!!"> </form> ?> results.php //// filename = result.php3 <? $hostname = "mysql7.000webhost.com"; // Usually localhost. $username = "a4542527_root"; // If you have no username, leave this space empty. $password = "*******"; // The same applies here. $usertable = "people"; // This is the table you made. $dbName = "a4542527_test1"; // This is the main database you connect to. MYSQL_CONNECT($hostname, $username, $password) OR DIE("Unable to connect to database"); @mysql_select_db( "$dbName") or die( "Unable to select database"); ?> <? //error message (not found message) $XX = "No Record Found"; $query = mysql_query("SELECT * FROM $usertable WHERE $metode LIKE '%$search%' LIMIT 0, 30 "); while ($row = mysql_fetch_array($query)) { $variable1=$row["row_name1"]; $variable2=$row["row_name2"]; $variable3=$row["row_name3"]; print ("this is for $variable1, and this print the variable2 end so on..."); } //below this is the function for no record!! if (!$variable1) { print ("$XX"); } //end ?> Upon viewing search.php I receive the error message: Parse error: syntax error, unexpected '<' in /home/a4542527/public_html/search.php on line 3 I believe I may be missing something and am a bit lost. Thank-you in in advance for any help or suggestions. ~Matty |