I have use joins to retrieve the data from various tables and I am successful in it but when I want to retrieve it the query only show me the result of last row even though I have use while loop on it but its not working properly give me the one result only which belongs to last row .
Here is my php scrip.
include("connections/conn.php");
$sql = mysql_query("SELECT * FROM `tbl_cart` as c join " .
"`tbl_product` as p join " .
"`tbl_catagory` as ca join " .
"`tbl_compony` as co join " .
"`tbl_images` as i " .
"on c.pid=p.pro_id " .
"and p.compony=co.com_id " .
"and p.catagory=ca.cat_id " .
"and p.pro_id=i.p_id");
$row = mysql_fetch_array($sql);
while($row1 = mysql_fetch_array($sql)) {
$product_ids[]=$row1['pro_id'];
foreach($product_ids as $pro) {
echo $pro;
}
}
but the array contains this data. which have more result of from similar columns.
111Array ( [0] => 33 [cart_id] => 33 [1] => 110 [pid] => 110 [2] => 20 [quantity] => 20 [3] => 65,000 [price] => 65,000 [4] => 9 [userid] => 9 [5] => 2014-08-14 [dated] => 2013-08-24 [6] => 110 [pro_id] => 110 [7] => Aspire S3-391 [title] => Aspire S3-391 [8] => 10.68 lbs [weight] => 10.68 lbs [9] => 15.90 inch [width] => 15.90 inch [10] => 2.31 cm [height] => 2.31 cm [11] => Black [color] => Black [12] => 65,000 [13] => $1499 [USD] => $1499 [14] => [waranty] => [15] => Make work a touch easier.Get in touch with your productive side. Tap and scroll your way through the workday with an intuitive touch screen (select models) that helps you work so much smarter. Count on durability inside and out from built in security to the spill resistant keyboard and a thin light design thats packed with style. [description] => Make work a touch easier.Get in touch with your productive side. Tap and scroll your way through the workday with an intuitive touch screen (select models) that helps you work so much smarter. Count on durability inside and out from built in security to the spill resistant keyboard and a thin light design thats packed with style. [16] => 1 [catagory] => 1 [17] => 4 [compony] => 4 [18] => Intel® Core™ i5 [l_ptype] => Intel® Core™ i5 [19] => 2.8 GHZ [l_pspeed] => 2.8 GHZ [20] => 700 GB [l_harddisk] => 700 GB [21] => 4GB DDR3 [l_RAM] => 4GB DDR3 [22] => Windows 8 [l_op] => Windows 8 [23] => [l_battery] => [24] => [lcd_brightness] => [25] => [lcd_contrast] => [26] => [lcd_imagesize] => [27] => [lcd_pixelsize] => [28] => [lcd_resolution] => [29] => [lcd_backlight] => [30] => [lcd_depth] => [31] => [p_pspeed] => [32] => [p_resolution] => [33] => [p_pconsumption] => [34] => [p_memorycapacity] => [35] => [p_storagecapacity] => [36] => [p_interface] => [37] => [p_processorspeed] => [38] => [pro_p_consumption] => [39] => [pro_brightness] => [40] => [pro_resolution] => [41] => [pro_imagesize] => [42] => [pro_ptype] => [43] => [pro_imagesignal] => [44] => [pro_contrast] => [45] => [sca_capacity] => [46] => [sca_speed] => [47] => [sca_colordepth] => [48] => [sca_usb] => [49] => [sca_documentsize] => [50] => [sca_resolution] => [51] => 2013-08-24 [52] => 1 [cat_id] => 1 [53] => Laptop [cat_title] => Laptop [54] => 4 [com_id] => 4 [55] => Acer [com_title] => Acer [56] => 120 [img_id] => 120 [57] => Aspire S3-391_main.jpg [main_image] => Aspire S3-391_main.jpg [58] => Aspire S3-391_left.jpg [left_image] => Aspire S3-391_left.jpg [59] => Aspire S3-391_right.jpg [right_image] => Aspire S3-391_right.jpg [60] => Aspire S3-391_top.jpg [top_image] => Aspire S3-391_top.jpg [61] => Aspire S3-391_other.jpg [other_image] => Aspire S3-391_other.jpg [62] => 110 [p_id] => 110 )
And when I run this query in sql it returns me two rows so how can I retrieve the data accordingly in my php script I am really confuse in it please help me out .
Now for further understanding i am adding this picture. And you people can see that this query is returning me two rows so how will fetch the two rows separately in my php script and show them on my page.
The problem is you are fetching the results from the same variable which bring you to a logical error see what's happening here you fetch once the result and store it in $row so first row from the result set get fetched and again your fetching the record and storing in another variable but from the same variable $sql and applying the while loop in result you are getting only one row because the first row get skipped.
Solution: Do not fetch the Results from the same variable make another variable and store the same query in it if you really needed e.g
$sql = mysql_query("SELECT * FROM `tbl_cart` as c join " .
"`tbl_product` as p join " .
"`tbl_catagory` as ca join " .
"`tbl_compony` as co join " .
"`tbl_images` as i " .
"on c.pid=p.pro_id " .
"and p.compony=co.com_id " .
"and p.catagory=ca.cat_id " .
"and p.pro_id=i.p_id");
$sql1 = mysql_query("SELECT * FROM `tbl_cart` as c join " .
"`tbl_product` as p join " .
"`tbl_catagory` as ca join " .
"`tbl_compony` as co join " .
"`tbl_images` as i " .
"on c.pid=p.pro_id " .
"and p.compony=co.com_id " .
"and p.catagory=ca.cat_id " .
"and p.pro_id=i.p_id");
$row = mysql_fetch_array($sql);
while($row1= mysql_fetch_array($sql1))
{
echo $row1['pro_id'];
}
I hope this will work.
You have this statement:
$row = mysql_fetch_array($sql);
That will fetch the "first" from the resultset (if there's at least one row).
Then you have a while loop, that does another fetch:
$row1 = mysql_fetch_array($sql)
That will get the "second" and following row. (Since you've already retrieved the first row.)
If you don't want to "skip" that first row, then remove this line from your code:
$row = mysql_fetch_array($sql);
Seems to be logicial to get only last row result.
If inside the While loop, you put "echo 'in the loop';", you'll probably see that two times.
But as you do:
'$product_ids[]=$row1['pro_id'];'
you fill $product_ids[] first time with $row1['pro_id'] and, at next loop, you fill it again with the new value, destroying the first one.
In fact, you're making a common mistake and I suppose I understand what you want to do:
loop to getresult
display result
using
foreach($product_ids as $pro) {
echo $pro;
But you have put the foreach inside the while loop as it must be outside.
A most simple and understable way would be:
`$index=0;
while($row1 = mysql_fetch_array($sql))
{
$product_ids[$index]=$row1['pro_id'];
$index++;
}
foreach($product_ids as $pro) {
echo $pro;
}
}`
A detail: use another MySQL Driver, like mysqli as mysql basic driver is obsolote.
Related
This code was written 10-15 years ago from what I can see. Friday, the webhost stopped supporting php4 and forced upgrade to 5.6.23 and the web app stopped working. I have been going over it all weekend. Got the system running, but there is one serious issue and I've narrowed it to a specific line of code and still can't figure it out due to my not doing php OOP programming myself. Looking for a quick fix here as my friend is dead in the water.
This code:
$ins = & $_SESSION["ins"];
$serv = new Services();
print "post - ";
print_r($_POST)."<br />";
reset($_POST);
foreach ($_POST as $key => $value) {
//$key = addslashes($key);
$query = mysql_query("SELECT $valueNumber
FROM CLIENTS_SERVICES
where serviceID = '$key' and clientID = '$ins->client' and effectiveDate <= '$effectiveDate'
order by effectiveDate DESC LIMIT 1")
or die("SELECT services function query failed!!");
$query_data = mysql_fetch_object($query);
$serv->value = $query_data->$valueNumber;
$serv->quantity = $value;
$ins->services[$key] = $serv; //<----- this is the offender
// Calculate services running total
$total = $total + ($serv->quantity * $serv->value);
print $key." - key<br />";
print $value." - value<br />";
print "serv array - ";
print_r($serv);
print "<br />";
print "ins array - ";
print_r($ins->services);
print "<br />";
print $total." - total<br />";
}
outputs:
post - Array (
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] => 1.5
[7] =>
[8] =>
[9] =>
[10] =>
[11] =>
[12] =>
[13] =>
[14] =>
[15] =>
[16] => 3
[17] =>
[50] =>
[51] => 1.75
[58] =>
[save_services] => Save )
6 - key
1.5 - value
serv object - Services Object ( [quantity] => 1.5 [value] => 56 )
ins array - Array ( [6] => Services Object ( [quantity] => 1.5 [value] => 56 ) )
84 - total
16 - key
3 - value
serv object - Services Object ( [quantity] => 3 [value] => 45 )
ins array - Array ( [6] => Services Object ( [quantity] => 3 [value] => 45 ) [16] => Services Object ( [quantity] => 3 [value] => 45 ) )
219 - total
51 - key
1.75 - value
serv object - Services Object ( [quantity] => 1.75 [value] => 118 )
ins array - Array ( [6] => Services Object ( [quantity] => 1.75 [value] => 118 ) [16] => Services Object ( [quantity] => 1.75 [value] => 118 ) [51] => Services Object ( [quantity] => 1.75 [value] => 118 ) )
425.5 - total
In a nutshell, I cannot understand why the most recent object values are overwriting the previous array entries. I've spent the weekend trying to figure out what changed between the old version (4.?) and the new 5.6.23, and have been on dozens of dead ends and wild goose chases. Ignorance is not bliss.
If there is a pointer to the resolution, or you can offer some insight, I'd appreciate it.
Create a new instance of services inside of the loop
foreach ($_POST as $key => $value) {
$serv = new Services();
...
}
When you use objects in php it will use the same pointer to that object
I have created a multi-dimensional array using fgetcsv from a CSV file.
Using both DOMDocument and SimpleXML I am trying to create a XML file of the CSV document.
The array and XML variables are being passed to a function within the same class file. The XML document is being created without any issues, but no value is passing from the array into the XML. It does work it I use a static value opposed to passing a value from the array, also if I print_r the array the structure and values are all correct.
I have tried 'htmlspecialcharacters' and 'encode_UTF8' before passing the value into the XML.
An example of the code is below, product is the multi-dimensional array.
public function array_to_xml($product, &$xml)
{
foreach($product as $row)
{
$element = $xml->createElement("Product");
$xml->appendChild($element);
$element = $xml->createElement("ID", ($row[38]));
$xml->appendChild($element);
}
}
The problem is obviously with the array but I can't find the answer. Any help would be gratefully appreciated.
The output currently looks like (with not value in the ID element). Once it is working Product will have about 20 child elements.
<?xml version="1.0"?>
<ProductList/>
<Product>
<ID/>
</Product>
</ProductList>
Example of $row when printed to screen:
Array ( [0] => [1] => [2] => 6/10/2016 [3] => [4] => [5] => 7.35 [6] => N [7] => N [8] => N [9] => 0 [10] => 0 [11] => 0 [12] => 0 [13] => 0 [14] => 80 [15] => 0 [16] => 80 [17] => 0 [18] => 80 [19] => N [20] => N [21] => N [22] => N [23] => 236.50 [24] => 0.00 [25] => 4.86 [26] => AFG Home Loans - Alpha [27] => 100% Offset Lo Doc Fixed [28] => 100% Offset Lo Doc 4 Year Fixed Owner Occupied [29] => 250.00 [30] => [31] => 7.35 [32] => 0.00 [33] => 4.9 [34] => N [35] => 325.00 [36] => 48 [37] => 4.52 [38] => 1-1MX78TF [39] => N [40] => [41] => [42] => N [43] => N [44] => [45] => Y [46] => 0.00 [47] => 10,000.00 [48] => 2,000,000.00 [49] => Y [50] => 30 [51] => [52] => [53] => Y [54] => 0.00 )
A couple things stand out. First, you have a syntax error on this line:
$element = $xml->createElement("ID", ($row[38])); (note the errant parentheses around $row[38]. The createElement method takes a String for its second parameter.
Second, you're not adding the ID to the product, but to the root XML. Fixing that, your code should look closer to this.
public function array_to_xml($product, &$xml)
{
foreach ($product as $row)
{
$product= $xml->createElement("Product");
$id = $xml->createElement("ID", $row[38]);
$product->appendChild($id);
$xml->appendChild($product);
}
}
If you need it as an attribute as #Barmar commented, you'd use the DOMElement->setAttribute() method, and it would look like:
public function array_to_xml($product, &$xml)
{
foreach ($product as $row)
{
$product= $xml->createElement("Product");
$product->setAttribute('ID', $row[38]);
$xml->appendChild($product);
}
}
I have an array named $info. I want to replace string "YES" found wherever within the array with space or empty string.How can it be done?
Below is the code:
<?php
$conn = mysql_connect("localhost" , "root" , "") or die("Can not connect." . mysql_error());
$db = mysql_select_db("leothian" , $conn) or die("Can not connect." . mysql_error());
$selTable = "select * from dump_hotelbasicinfo ORDER BY id ASC LIMIT 5";
$resultTable = mysql_query($selTable,$conn);
while($rowTable = mysql_fetch_array($resultTable))
{
$selQuery = "SELECT * FROM dump_hotelamenities WHERE HotelCode='$rowTable[HotelCode]' LIMIT 5";
$resultQuery = mysql_query($selQuery);
while($row=mysql_fetch_array($resultQuery))
{
echo "<br> Hotel Code : " .$row['HotelCode'];
$info = array();
$info = (explode(';',$row['PAmenities']));
echo array_search("YES",$info);
echo "<br> Hotel Features : " ;
print_r( $info);
echo "<hr>";
}
}
?>
OUTPUT :
Hotel Features : Array ( [0] => Small pets allowed under 5 kg [1] => YES Small pets allowed under 5 kg [2] => Large pets allowed over 5 kg [3] => YES Large pets allowed over 5 kg [4] => Wheelchair-accessible [5] => YES Wheelchair-accessible [6] => Car park [7] => YES Car park [8] => Garage [9] => YES Garage [10] => Mobile phone coverage [11] => Wired Internet [12] => Wi-fi [13] => Transfer service [14] => Secure parking [15] => Room service [16] => Laundry service [17] => Hotel safe [18] => Cloakroom [19] => Lift access [20] => Newspaper stand [21] => Supermarket [22] => Bicycle storage [23] => Sun terrace [24] => Gym [25] => Newspapers [26] => Restaurant [27] => Non-smoking area [28] => Photocopier [29] => Sun loungers [30] => Children& [31] => apos [32] => s play area [33] => TV lounge [34] => Sauna [35] => Massage [36] => Spa treatments [37] => Year of construction - 2008 [38] => Number of floors main building - 10 [39] => Apartments - 25 [40] => Studios - 1 [41] => Connecting rooms [42] => YES Connecting rooms [43] => Apartment complex [44] => Nearest Bus / Metro Stop - 25000 m [45] => Ski slopes - 2000 m )
A for each loop would work
foreach($info as $k=>$v)
$info[$k] = str_replace('YES','',$v);
<?php
$array = array('this','is','a','test','yes it is','YES it is');
$array = array_map(function($item){
$item = str_replace('YES','', $item);
return $item;
}, $array);
var_dump($array);
function customSearch($keyword, $arrayToSearch){
foreach($arrayToSearch as $key => $arrayItem){
if( stristr( $arrayItem, $keyword ) ){
$arrayToSearch[key] = "yes";
return $key;
}
}
}
I haven't actually tried this but please Refer to this question here if my code is a bit off:
Search for PHP array element containing string
I have following two arrays which comes from the same database use the same query to get both. both contains information about a single sales order having two different line items(Bill of materials) the first one has Line ItemItemID= 600271 and the second one has LineItem ItemID=600274 but as you can see below they both have the same Sales Order Number [CustomerSONo] => [7] => **15020**
so How can i compare or union these two array's. ?
//query
$result= --select statement--;
while($row = mysqli_fetch_array($result)) {
print_r($row);
}
Array 1
Array (
[0] => XXX001
[CustomerId] => XXX001
[1] => XXX Company Name.*
[Customer_Bill_Name] => XXX Company Name.*
[2] => DHE
[WhichShipVia] => DHE [3] =>
[INV_POSOOrderNumber] => [4] => 2014-12-19
[ShipByDate] => 2014-12-19 [5] =>
[GoodThruDate] => [6] =>
[CustomerSONo] => [7] => 15020
[Reference] => 15020 [8] => 2014-11-25
[TransactionDate] => 2014-11-25 [9] => 1
[DistNumber] => 1
[10] => 70.0000000000000000000 //here is the difference 1
[Quantity] => 70.0000000000000000000 //here is the difference 2
[11] => 600271 //here is the difference 3
[ItemId] => 600271 //here is the difference 4
[12] => ASSY7.60-15SL/8 FRM I1 15X6 6-6, BLK (GWT-761508 (24) //here is the difference 5
[SalesDescription] => ASSY7.60-15SL/8 FRM I1 15X6 6-6, BLK (GWT-761508)(24)//here is the difference 1 //here is the difference 6
[13] => AS1577 //here is the difference 7
[PartNumber] => AS1577 //here is the difference 8
[14] => ASSY7.60-15 8PLY W/WHL15X6 BLK //here is the difference 9
[ItemDescription] => ASSY7.60-15 8PLY W/WHL15X6 BLK )
Array 2:
Array (
[0] => XXX001
[CustomerId] => XXX001
[1] => XXX Company Name.*
[Customer_Bill_Name] => XXX Company Name.*
[2] => DHE [WhichShipVia] => DHE [3] =>
[INV_POSOOrderNumber] => [4] => 2014-12-19
[ShipByDate] => 2014-12-19 [5] =>
[GoodThruDate] => [6] =>
[CustomerSONo] => [7] => 15020
[Reference] => 15020 [8] => 2014-11-25
[TransactionDate] => 2014-11-25 [9] => 2
[DistNumber] => 2
[10] => 6.0000000000000000000 //here is the difference 1
[Quantity] => 6.0000000000000000000 //here is the difference 2
[11] => 600274 //here is the difference 3
[ItemId] => 600274 //here is the difference 4
[12] => ASSY9.5L-15SL/8 FLT I1 15X8 6-6, BLK (GWT-951508)(16)
[SalesDescription] => ASSY9.5L-15SL/8 FLT I1 15X8 6-6, BLK (GWT-951508)(16) //here is the difference 5
[13] => AS1601 //here is the difference 6
[PartNumber] => AS1601 //here is the difference 7
[14] => ASSY9.5L-15 W/WHL15X8 6/6 BLK //here is the difference 8
[ItemDescription] => ASSY9.5L-15 W/WHL15X8 6/6 BLK ) //here is the difference 9
Option 1
$orders = array();
while($row = mysqli_fetch_array($result)) {
$orders[$row['CustomerSONo'][] = $row;
}
This will add all rows that share the same CustomerSONo together in one array. If you have multiple orders, you can get all the seperate orders using
foreach($orders as $orderNo => $order) {
foreach($order as $key => $orderRow) {
}
}
Option 2
If you however only want to extract the ItemIDs from each order, you can do the following:
$orderItems = array();
while($row = mysqli_fetch_array($result)) {
$orderItems[$row['CustomerSONo']][] = $row['ItemID'];
}
This will create an array called $orderItems that only stores the order numbers in the array, rather than all the information about the order.
Option 3
If you want to echo the lines, you first have to "sort" them like in Option 2. Once you have gained all ItemIDs that belong to one CustomerSONo, you do another foreach loop to echo them into a single line.
foreach($orders as $orderNo => $itemIds) {
echo "Order #" . $orderNo . ": " . implode(", ", $itemIds);
}
This will create the following:
Order #1: 18340, 1837, 13
Order #2: 183, 868, 285, 860
I have a query that I'm running in php. The DB is SQL Server 2008.
The query in PHP is:
"SELECT * FROM applicants WHERE applicants.families_id = '{$family_array['id']}'";
Where the $family_array id is matched against the families_id. I get a single row as a result. I save that row to an array in PHP by using the mssql_fetch_array function. When I print this array I get the following:
Array
(
[0] => 26
[id] => 21
[1] => 21
[user_id] => 21
[2] => Kristi
[mother_fname] => Kristi
[3] => Lochala
[mother_lname] => Lochala
[4] => Nathan
[father_fname] => Nathan
[5] => Lochala
[father_lname] => Lochala
[6] =>
[app_emergency] =>
[7] =>
[upload_mother_passport] =>
[8] =>
[upload_mother_visa] =>
[9] =>
[upload_father_passport] =>
[10] => 0
[upload_father_visa] => 0
[11] => nathan-lochala
[user_added_username] => nathan-lochala
[12] => Mar 19 2013 01:00:37:660PM
[user_added_date] => Mar 19 2013 08:48:00:000AM
[13] => 192.168.88.15
[user_added_ip] => 192.168.88.15
[14] =>
[user_updated_username] =>
[15] =>
[user_updated_date] =>
[16] =>
[user_updated_ip] =>
[17] => 21
[18] => nathan-lochala
[username] => nathan-lochala
[19] => b9a234cb37ce2b75d77befecabfa650e39489e0b
[hash_password] => b9a234cb37ce2b75d77befecabfa650e39489e0b
[20] => Nathan
[fname] => Nathan
[21] => Lochala
[lname] => Lochala
[22] => 2
[num_child] => 2
[23] => Mar 19 2013 08:48:00:000AM
[24] => 192.168.88.15
[25] =>
[26] =>
[27] => nathan-lochala#shk.qsi.org
[email] => nathan-lochala#shk.qsi.org
[28] => parent
[access] => parent
)
If you notice, the index [0] does not match the corresponding key value [id]. Why is this? I've ran the exact same query using the SQL Server Manager and it performs as expected, but when I fetch that array in PHP only the first key value gets skewed. I've tried everything I can think of short of recreating the table. Any ideas?
EDIT:
Running mssql_fetch_assoc() gives me the following results:
Array
(
[id] => 21
[user_id] => 21
[mother_fname] => Kristi
You are not including all the pertinent information either in the posted SQL or in the table data/structure you've included. Your query is SELECT * FROM applicants WHERE applicants.families_id = ? yet the table structure you've posted does not contain a families_id column (nor is it named applicants). Nor does it contain much of the data in the posted array, e.g., hash_password, username, etc.
From this I deduce that you're actually doing a JOIN on a users table. What's most likely occurring is that the JOIN is including the id column from the users table which is overwriting the id in the main table (families/applicant, whatever it's called) once the array is built. user_id is already included in your main table so you should explicitly list the columns in your SQL statement, leaving out the users.id column.
You need to make it mssql_fetch_array($result, MSSQL_ASSOC) as MSSQL_BOTH is assumed.
I found the answer here:
http://php.net/manual/en/function.mssql-fetch-array.php