PHP - Insert Php Database Data Into A Javascript Array?
Hello =)
I'm trying to create a javascript array which should be filled with data from a mysql database. so what i wannt to do is to loop out a new array element for each row in my database. I should also say that i'm working in a php file. I tried (and failed) to do it like this: Code: [Select] <?php include('databbaseconnect.php'); ?> <script type="text/javascript"> var StoreDetails = [ ['Please select an option','','','','',''], <?php mysql_select_db("alltomboule_se", $db); $result = mysql_query("SELECT * FROM spelare"); while($row = mysql_fetch_array($result)) { echo "['".$row['namn'].$row['enamn']."','".$row['namn'].",'".$row['enamn']."','".$row['klubb']."','".$row['licensnr']."','".$row['id']."'],"; } ?> ['','','','','',''] // Note: no comma for last row ]; I wannt the array to look like this: Code: [Select] var StoreDetails = [ ['Please select an option','','','','',''], ['Oscar Andersson','Oscar','Andersson','BON','16643','2'], ['Olle Johansson','Olle','Johansson','BFT','14443','3'], ['Ingvar Andersson','Ingvar','Andersson','BON','14333','4'], ['Kalle Kula','Kalle','Kula','BON','34576','5'], ['','','','','',''] ]; Similar TutorialsHi.. Sorry, if I need to repost my problem in while loop. cause until now I can't resolve my problem in saving all data from while loop. I have this code StockRequisition.php where FORM was displayed. <?php error_reporting(0); date_default_timezone_set("Asia/Singapore"); //set the time zone $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); $sr_date =date('Y-m-d H:i:s'); $sql = "SELECT sr_number FROM stock_requisition ORDER BY sr_date DESC LIMIT 1"; $result = mysql_query($sql, $con); if (!$result) { echo 'failed'; die(); } $total = mysql_num_rows($result); if ($total <= 0) { $currentSRNum = 1; $currentYear = (int)(date('y')); $currentMonth = (int)(date('m')); $currentDay = (int)(date('d')); $currentSRYMD = substr($row['sr_number'], 0, 6); $currentYMD = date("ymd"); if ($currentYMD > $currentSRYMD) { $currentSRNum = 1; } else { $currentSRNum += 1; } } else { //------------------------------------------------------------------------------------------------------------------ // Stock Number iteration.... $row = mysql_fetch_assoc($result); $currentSRNum = (int)(substr($row['sr_number'],0,3)); $currentSRYear = (int)(substr($row['sr_number'],2,2)); $currentSRMonth = (int)(substr($row['sr_number'],0,2)); $currentSRNum = (int)(substr($row['sr_number'],6,4)); $currentYear = (int)(date('y')); $currentMonth = (int)(date('m')); $currentDay = (int)(date('d')); $currentSRYMD = substr($row['sr_number'], 0, 6); $currentYMD = date("ymd"); if ($currentYMD > $currentSRYMD) { $currentSRNum = 1; } else { $currentSRNum += 1; } } //------------------------------------------------------------------------------------------------------------------ $yearMonth = date('ymd'); $currentSR = $currentYMD . sprintf("%04d", $currentSRNum); ?> <html> <title>Stock Requisition</title> <head> <link rel="stylesheet" type="text/css" href="kanban.css"> <script type="text/javascript"> function save_sr(){ var sr_date = document.getElementById("sr_date").value; var sr_number = document.getElementById("sr_number").value; var Items1 = document.getElementById("Items1").value; var SubItems = document.getElementById("SubItems").value; var ItemCode = document.getElementById("ItemCode").value; var DemandedQty = document.getElementById("DemandedQty").value; var UoM = document.getElementById("UoM").value; var Class = document.getElementById("Class").value; var Description = document.getElementById("Description").value; var BINLocation = document.getElementById("BINLocation").value; var RequestedBy = document.getElementById("RequestedBy").value; var ApprovedBy = document.getElementById("ApprovedBy").value; var ReceivedBy = document.getElementById("ReceivedBy").value; var IssuedBy = document.getElementById("IssuedBy").value; document.stock_requisition.action="StockRequisitionSave.php?sr_date="+sr_date+"&sr_number="+sr_number+"&Items1="+Items1+ "&SubItems="+SubItems+"&ItemCode="+ItemCode+"&DemandedQty="+DemandedQty+"&UoM="+UoM+"&Class="+Class+"&Description="+ Description+"&BINLocation="+BINLocation+"&RequestedBy="+RequestedBy+"&ApprovedBy="+ApprovedBy+"&ReceivedBy="+ReceivedBy+ "&IssuedBy="+IssuedBy; document.stock_requisition.submit(); alert("Stock Requisition data save."); window.location = "StockRequisition.php"; } </script> </head> <body> <form name="stock_requisition" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div id="ddcolortabs"> <ul> <li> <a href="ParameterSettings.php" title="Parameter Settings"><span>Parameter Settings</span></a></li> <li style="margin-left: 1px"><a href="kanban_report.php" title="WIP Report"><span>Wip Report</span></a></li> <li><a href="fsn.php" title="Finished Stock Note"><span>WMS FG</span></a></li> <li id="current"><a href="StockRequisition.php" title="WMS RM"><span>WMS RM</span></a></li> </ul> </div> <div id="ddcolortabs1"> <ul> <li><a href="ReceivingMaterials.php" title="Receiving Materials"><span>Receiving Materials</span></a></li> <li><a href="Shelving.php" title="Shelving"><span>Shelving</span></a></li> <li id="current"><a href="StockRequisition.php" title="Stock Requisition"><span>Stock Requisition</span></a></li> </ul> </div> <div id="SR_date"> <label>Date :</label> <input type="text" name="sr_date" value="<?php echo $sr_date; ?>" size="16" readonly="readonly" style="border: none;"> </div> <div id="SR_number"> <label>SR# :</label> <input type="text" name="sr_number" value="<?php echo $currentSR; ?>" size="10" readonly="readonly" style="font-weight: bold; border: none;"> <br/> </div> <div> <table> <thead> <th>Items</th> <th>Sub Items</th> <th>Item Code</th> <th>Demanded Qty</th> <th>UoM</th> <th>Class</th> <th>Description</th> <th>BIN Location</th> </thead> <?php $sql = "SELECT DISTINCT Items FROM bom_subitems ORDER BY Items"; $res_bom = mysql_query($sql, $con); while($row = mysql_fetch_assoc($res_bom)){ $Items = $row['Items']; echo "<tr> <td style='border: none;font-weight: bold;'> <input type='name' value='$Items' name='Items' id='Items' readonly = 'readonly' style = 'border:none;width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='5'></td> </tr>"; $sql = "SELECT Items, SubItems, ItemCode, UoM, Class, Description, BINLocation FROM bom_subitems WHERE Items = '$Items' ORDER BY Items"or die(mysql_error()); $res_sub = mysql_query($sql, $con); while($row_sub = mysql_fetch_assoc($res_sub)){ $Items1 = $row_sub['Items']; $SubItems = $row_sub['SubItems']; $ItemCode = $row_sub['ItemCode']; $UoM = $row_sub['UoM']; $Class = $row_sub['Class']; $Description = $row_sub['Description']; $BINLocation = $row_sub['BINLocation']; echo "<tr> <td style='border: none;'> <input type='hidden' value='$Items1' id='Items1' name='Items1'></td> <td style='border: none;'> <input type='text' name='SubItems' value='$SubItems' id='SubItems' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='10'></td> <td style='border: none;'> <input type='text' name='ItemCode' value='$ItemCode' id='ItemCode' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='10'></td> <td style='border: none;'><center><input type='text' name='DemandedQty' id='DemandedQty' value='' size='7'></center></td> <td style='border: none;' size='3'> <input type='text' name='UoM' value='$UoM' id='UoM' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='3'></td> <td style='border: none;'> <input type='text' name='Class' value='$Class' id='Class' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='10'></td> <td style='border: none;'> <input type='text' name='Description' value='$Description' id='Description' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='10'></td> <td style='border: none;'> <input type='text' name='BINLocation' value='$BINLocation' id='BINLocation' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='10'></td> </tr>"; } } ?> </table> </div> <?php $RequestedBy = array('AAA', 'BBB', 'CCC', 'DDD'); $ApprovedBy = array('EEE', 'FFF', 'GGG', 'HHH'); $ReceivedBy = array('III', 'JJJ', 'KKK', 'LLL'); $IssuedBy = array('MMM', 'NNN', 'OOO', 'PPP'); ?> <div id='Requested_By'> <label>Requested By:</label> <select name="RequestedBy"> <option value="Select">Select</option> <option value="AAA" <?php if($_POST['RequestedBy'] == 'AAA') echo "selected='selected'"; ?>>AAA</option> <option value="BBB" <?php if($_POST['RequestedBy'] == 'BBB') echo "selected='selected'"; ?>>BBB</option> <option value="CCC" <?php if($_POST['RequestedBy'] == 'CCC') echo "selected='selected'"; ?>>CCC</option> <option value="DDD" <?php if($_POST['RequestedBy'] == 'DDD') echo "selected='selected'"; ?>>DDD</option> </select> </div> <div id='Approved_By'> <label>Approved By:</label> <select name="ApprovedBy"> <option name='Select'>Select</option> <option value="EEE" <?php if($_POST['ApprovedBy'] == 'EEE') echo "selected='selected'"; ?>>EEE</option> <option value="FFF" <?php if($_POST['ApprovedBy'] == 'FFF') echo "selected='selected'"; ?>>FFF</option> <option value="GGG" <?php if($_POST['ApprovedBy'] == 'GGG') echo "selected='selected'"; ?>>GGG</option> <option value="HHH" <?php if($_POST['ApprovedBy'] == 'HHH') echo "selected='selected'"; ?>>HHH</option> </select> </div> <div id='Received_By'> <label>Issued By:</label> <select name="IssuedBy"> <option name='Select'>Select</option> <option value="III" <?php if($_POST['ReceivedBy'] == 'III') echo "selected='selected'"; ?>>III</option> <option value="JJJ" <?php if($_POST['ReceivedBy'] == 'JJJ') echo "selected='selected'"; ?>>JJJ</option> <option value="KKK" <?php if($_POST['ReceivedBy'] == 'KKK') echo "selected='selected'"; ?>>KKK</option> <option value="LLL" <?php if($_POST['ReceivedBy'] == 'LLL') echo "selected='selected'"; ?>>LLL</option> </select> </div> <div id='Issued_By'> <label>Received By:</label> <select name="ReceivedBy"> <option name='Select'>Select</option> <option value="MMM" <?php if($_POST['IssuedBy'] == 'MMM') echo "selected='selected'"; ?>>MMM</option> <option value="NNN" <?php if($_POST['IssuedBy'] == 'NNN') echo "selected='selected'"; ?>>NNN</option> <option value="OOO" <?php if($_POST['IssuedBy'] == 'OOO') echo "selected='selected'"; ?>>OOO</option> <option value="PPP" <?php if($_POST['IssuedBy'] == 'PPP') echo "selected='selected'"; ?>>PPP</option> </select> </div> <div id="save_btn"> <input type="button" name="button" value="save" onClick="save_sr()"> </div> </form> </body> </html> and here is StockRequisitionSave.php code for saving data to database : <?php error_reporting(0); date_default_timezone_set("Asia/Singapore"); //set the time zone $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); $sr_date = $_POST['sr_date']; $sr_number = $_POST['sr_number']; $Items1 = $_POST['Items1']; $SubItems = $_POST['SubItems']; $ItemCode = $_POST['ItemCode']; $DemandedQty = $_POST['DemandedQty']; $UoM = $_POST['UoM']; $Class = $_POST['Class']; $Description = $_POST['Description']; $BINLocation = $_POST['BINLocation']; $RequestedBy = $_POST['RequestedBy']; $ApprovedBy = $_POST['ApprovedBy']; $ReceivedBy = $_POST['ReceivedBy']; $IssuedBy = $_POST['IssuedBy']; $sql = "INSERT INTO stock_requisition (sr_date, sr_number, Items, SubItems, ItemCode, DemandedQty, UoM, Class, Description, BINLocation, RequestedBy, ApprovedBy, ReceivedBy, IssuedBy) VALUES ('$sr_date', '$sr_number', '$Items1', '$SubItems', '$ItemCode', '$DemandedQty', '$UoM', '$Class', '$Description', '$BINLocation', '$RequestedBy', '$ApprovedBy', '$ReceivedBy', '$IssuedBy') "; $result = mysql_query($sql, $con); ?> the problem is only the last data was save. I will attach my form. I hope somebody can help me.. I really don't know how can I save all data from form into my database. Thank you so much for your understanding and help. Everything on this page works the form loads and i can insert info into the form but when i click submit it just reloads the page(action="this page") and nothing happens. thanks in advance -Adam Code: [Select] <?php require("connection/connection.php"); include("connection/functions.php"); ?> <HTML> <head> <meta content="yes" name="apple-mobile-web-app-capable" /> <meta content="index,follow" name="robots" /> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <link href="" rel="apple-touch-icon" /> <meta content="minimum-scale=1.0, width=device-width, maximum-scale=0.6667, user-scalable=no" name="viewport" /> <meta name="format-detection" content="telephone=no"/> <link href="css/style.css" rel="stylesheet" media="screen" type="text/css" /> <script src="javascript/functions.js" type="text/javascript"></script> <title>.: Bookmarks :.</title> <link href="" rel="apple-touch-startup-image" /> <meta content="apple-mobile-web-app-status-bar-style" content="default" /> </head> <body class="musiclist"> <div id="topbar"> <div id="title">.: Bookmarks :.</div> <div id="leftbutton"> <a href="default.html"><img src="images/home.png"></a> </div> <div id="rightbutton"> <a href="">Programs</a> </div> </div> <div id="tributton"> <div class="links"> <a id="pressed" href="Bookmarks/Bookmarks.php">Bookmarks</a><a href="Music/Music.html">Music</a><a href="">Movies</a> </div> </div> <div id="content" style="top: 36px"> <form method="post" action="AddBookmark.php"> <span class="graytitle">Add Bookmark</span> <ul class="pageitem"> <li class="bigfield"><input type="text" name="BookmarkName" placeholder="Bookmark Name" /></li> <li class="bigfield"><input type="text" name="BookmarkLink" placeholder="Bookmark Link" /></li> <li class="select"><select name="d"> <?php $getbookmarksections = mysql_query("SELECT * FROM bookmarksections"); confirm_query($getbookmarksections); while($getbm = mysql_fetch_array($getbookmarksections)){ $id = $getbm["ID"]; $sn = $getbm["SectionName"]; echo "<option value=\"$id\">$sn</option>"; } ?> </select><span class="arrow"></span></li> <li class="button"> <input name="AddBookmark" type="submit" value="Add Bookmark" /> </li> </ul> </form> <?php if(isset($_POST["AddBookmark"])){ $SectionID = $id; $Bookmark = $_POST["BookmarkName"]; $BookmarkLink = $_POST["BookmarkLink"]; $add = "INSERT INTO `bookmarks` (`ID` ,`SectionID` ,`Bookmark` ,`BookmarkLink`) VALUES ('NULL', '$SectionID', '$Bookmark', '$BookmarkLink')"; if(confirm_query($add)){ echo "<span class=\"graytitle\">Bookmark '$BookmarkName' in '$sn' Added.</span>"; } } ?> </div> <div id="footer"> </div> </body> </HTML> <?php //Close Connection if(isset($connection)){ mysql_close($connection); } ?> this is the code i suspect is not working Code: [Select] <?php if(isset($_POST["AddBookmark"])){ $SectionID = $id; $Bookmark = $_POST["BookmarkName"]; $BookmarkLink = $_POST["BookmarkLink"]; $add = "INSERT INTO `bookmarks` (`ID` ,`SectionID` ,`Bookmark` ,`BookmarkLink`) VALUES ('NULL', '$SectionID', '$Bookmark', '$BookmarkLink')"; if(confirm_query($add)){ echo "<span class=\"graytitle\">Bookmark '$BookmarkName' in '$sn' Added.</span>"; } } ?> I am trying to display data from mysql. Each row from the mysql database shows up under rows. I want the rows of data from mysql to appear in colums of 4. can some one help please. <?php $sql = 'SELECT * FROM dbtable ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<table>'; $output[] = '<tr>'; $output[] = '<td class="style10"><strong>'.$row['item'].'</strong></td>'; $output[] = '</tr>'; $output[] = '<tr>'; $output[] = '<td><img src="images/'.$row['pic'].'" width="100" height="150" /></td>'; $output[] = '</tr>'; $output[] = '<tr>'; $output[] = '<td>'.$row['description'].'</td>'; $output[] = '</tr>'; $output[] = '</table>'; } echo join('',$output); ?> I almost have it but I am missing something. The form is being sent and the row is being created but there is not data. It is blank. I know it is something simple I am missing but I cannot figure it out
If anyone can look at my code below and tell me what I am missing to make the inputed info be seen, I would sure appreciate it.
<?php include_once('class/class_email.php'); // contact to database $connect = mysql_connect("localhost", "admin", "password") or die ("Error , check your server connection."); mysql_select_db("database"); $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $company = $_POST['company']; $telephone = $_POST['telephone']; $comments = $_POST['comments']; $EID = $_POST['eid']; extract ($_POST); // Pick up the form data and assign it to variables // $id = intval($id); $fname = strip_tags($fname); $lname = strip_tags($lname); $email = strip_tags($email); $company = strip_tags($company); $telephone = intval($telephone); $query="INSERT INTO users(`id`, `fname`, `lname`, `email`,`company`,`telephone`) VALUES('$id','$fname','$lname','$email','$company','$telephone')"; echo $query; mysql_query($query) or die(mysql_error()); echo mysql_error(); $SQL_GetEquipment = "SELECT * FROM `new_equip` WHERE `id`='$EID' LIMIT 1;"; $result = mysqli_query($connect,$SQL_GetEquipment); $row = mysqli_fetch_assoc($result); $EmailBody = "$fname $lname has requested a quote from NAPE on Item $EID\n Information on quote request: \n Name: $fname $lname \n Email: $email \n Company: $company \n Number: $telephone \n Comments: $comments \n \n Information Requested for: {$row['itemname']}\n The URL to {$row['itemname']} is: http://www.mydomain.com.com/new-product.php?Item=$EID \n Click to send a quote now:\n http://www.mydomain.com.com/Admin/send-quote.php?id=$EID "; $e = new email(); //First value is the URL of your server, the second the port number $e->set_server( 'mail.mydomain.com.com', 26); //First value is your username, then your password $e->set_auth('noreply@mydomain.com', '112233'); //Set the "From" setting for your e-mail. The Name will be base64 encoded $e->set_sender( 'Quote Requested', 'noreply@mydomain.com' ); //for one recipient //$send_to = array('myemail@mydomain.com','myemail2@mydomain.com'); $send_to = ('myemail@gmail.com'); //you may also specify multiple recipients by creating an array like this: //$send_to = array('foo1@localhost.local', 'foo2@localhost.local', 'foo3@localhost.local'); $subject = 'Quote Request from NAPE'; $body = "$EmailBody"; if( $e->mail($send_to, $subject, $body, $headers) == true ) { //message was received by the smtp server //['last'] tends to contain the queue id so I like to save that string in the database echo 'last: '.htmlspecialchars($e->srv_ret['last']).''; }else{ //something went wrong echo 'all: '.nl2br(htmlspecialchars($e->srv_ret['all'])).''; echo 'full:'.nl2br(htmlspecialchars($e->srv_ret['full'])).''; } ?> Hello all, I hope you are doing great.I am using phpmyadmin for the first time.So I created a table called guestbook with 4 attributes: id,name,email,message..Then I created a php file with the following code (saved in htdoc in Xampp folder)and html form which would take the data from the user and insert into the database which could later be retrieved.So far I have just written the insertion code which successfully creates the form but when I click on submit button it opens the same php file with the code and no insertion is made in the database..here is my code..please help me urgently..i have my project deadline very soon. php file called guest.php: <?php $user="root"; $password=""; $database="Guestbook"; $name=$_POST['name']; $email=$_POST['email']; $body=$_POST['body']; $connect("localhost",$user,$password); mysql($connect); @mysql_select_db($database)or die("unable to select db"); $query = mysql_query("INSERT INTO Guestbook(id,name,email,body) VALUES('','$name','$email','$body')"); if(!$query) { echo mysql_errno().':'.mysql_error(); } mysql_close(); ?> html file called new.html: <html> <head> <title>Guestbook</title> </head> <body> <form method="post" action="guest.php" > Name:<input type="text" name="name" size="30"/><br/> Email: <input type="text" name="email" size="30"/><br/> <p>Text:<br/> <textarea name="message" rows="15" cols="60"></textarea></p> <br/> <input type="submit" value="Submit"/> <input type="reset" value="Clear"/> </form> </body> </html> Hello all. I have a php script which will insert csv data into database using PDO. But it's slow even with just few thousands records. So how can I prevent client from waiting for it when they want to upload data? I tried INSERT DELAYED but it's not working... Thank you. Hi, I'm having trouble adding data to the database (test) that i created. I just can't see where I'm going wrong. need some other peoples opinions. I have tried taking the id out of the SQL statement completely as it is an auto increment, but that doesn't seem to work either. Thanks in advance... <?php $fname = $_POST['fname']; $sname = $_POST['sname']; $email = $_POST['email']; $pword = $_POST['password']; $gender = $_POST['gender']; $user_name = "root"; $password = ""; $database = "test"; $server = "127.0.0.1"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "INSERT INTO members (id, fname, sname, email, password, gender) VALUES (NULL, $fname, $sname, $email, $pword, $gender);"; $result = mysql_query($SQL); mysql_close($db_handle); print "Thanks for joining us ".$fname."."; print "<br /><br />"; print $fname . "<br />"; print $sname . "<br />"; print $email . "<br />"; print $pword . "<br />"; print $gender . "<br />"; } else { print "Database NOT Found"; mysql_close($db_handle); } ?> Hi, I want to extract weather for 5 cities from www.wunderground.com/global/SB.html and put the field data such as colombo, temprature, humidity and conditions in to a mysql table so I can display the weather for this 5 cities and automatically set a cronjob to update it everyday. Issue is I am unable to extract the specific data from this page. Please help. thanks Hi I have been trying to grab some data from an XML feed parse it and then insert it into a database. I will only need to do this on one occasion so no update or deletes. Sample of xml structu Code: [Select] <property> <id>34935</id> <date>2009-11-03 06:52:45</date> <ref>SVS0108</ref> <price>450000</price> <currency>EUR</currency> <price_freq>sale</price_freq> </property> Using xml2array class to parse the feed: <?php /** * xml2array Class * Uses PHP 5 DOM Functions * * This class converts XML data to array representation. * */ class Xml2Array { /** * XML Dom instance * * @var XML DOM Instance */ private $xml_dom; /** * Array representing xml * * @var array */ private $xml_array; /** * XML data * * @var String */ private $xml; public function __construct($xml = '') { $this->xml = $xml; } public function setXml($xml) { if(!empty($xml)) { $this->xml = $xml; } } /** * Change xml data-to-array * * @return Array */ public function get_array() { if($this->get_dom() === false) { return false; } $this->xml_array = array(); $root_element = $this->xml_dom->firstChild; $this->xml_array[$root_element->tagName] = $this->node_2_array($root_element); return $this->xml_array; } private function node_2_array($dom_element) { if($dom_element->nodeType != XML_ELEMENT_NODE) { return false; } $children = $dom_element->childNodes; foreach($children as $child) { if($child->nodeType != XML_ELEMENT_NODE) { continue; } $prefix = ($child->prefix) ? $child->prefix.':' : ''; if(!is_array($result[$prefix.$child->nodeName])) { $subnode = false; foreach($children as $test_node) { if($child->nodeName == $test_node->nodeName && !$child->isSameNode($test_node)) { $subnode = true; break; } } } else { $subnode = true; } if ($subnode) { $result[$prefix.$child->nodeName][] = $this->node_2_array($child); } else { $result[$prefix.$child->nodeName] = $this->node_2_array($child); } } if (!is_array($result)) { $result['#text'] = html_entity_decode(htmlentities($dom_element->nodeValue, ENT_COMPAT, 'UTF-8'), ENT_COMPAT,'ISO-8859-15'); } if ($dom_element->hasAttributes()) { foreach ($dom_element->attributes as $attrib) { $prefix = ($attrib->prefix) ? $attrib->prefix.':' : ''; $result["@".$prefix.$attrib->nodeName] = $attrib->nodeValue; } } return $result; } /** * Generated XML Dom * */ private function get_dom() { if(empty($this->xml)) { echo 'No XML found. Please set XML data using setXML($xml)'; return false; } $this->xml_dom = @DOMDocument::loadXML($this->xml); if($this->xml_dom) { return $this->xml_dom; } echo 'Invalid XML data'; exit; } } ?> My results page: <?php require_once('classes/xml2array.php'); require_once('conn.php'); function curlURL($url) { $ch= curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2'); $output = curl_exec($ch); return $output; } $curlResults = curlURL("http://localhost/alphashare_dump/property.xml"); $xml = $curlResults; $converter = new Xml2Array(); $converter->setXml($xml); $xml_array = $converter->get_array(); $array = ($xml_array['root']['property']); echo "<pre>"; print_r($array); echo "</pre>"; ////////////// INSERT DATA INTO DB //////////////////////////////////////////////////// ?> My array structure looks like this: Code: [Select] Array ( [0] => Array ( [id] => Array ( [#text] => 34935 ) [date] => Array ( [#text] => 2009-11-03 06:52:45 ) [ref] => Array ( [#text] => SVS0108 ) [price] => Array ( [#text] => 450000 ) [currency] => Array ( [#text] => EUR ) [price_freq] => Array ( [#text] => sale ) [part_ownership] => Array ( [#text] => 0 ) Can somebody help with actually getting this into some format that will enable me to insert this into my database please GT could anyone please help me with the code which is i have already displayed data as a multi select list but now i need to select one or more from them and insert into another database table. would be appreciate your help. thanx hi guys so i have this add contacts page and the form is divided into 3 different froms 1) primary contact 2)spouse 3)child and the child form data is inserted as array into database because in the primary contact part of the form there is a "Children ?" with yes and no radio button and if yes a drop down list is enabled where if user chooses say 2 then there would be 2 child form that appears. and since theres 2 children then in the database a new row and data will be added accordingly.
image attached to be clearer.
from2.jpg 24.15KB
0 downloads
i got it inserted into database but in the specified field it says array: |child_name|dob|house_add1|mobile|office|email| inserted: |array|array-array-array|array|array|array|array| query: "INSERT INTO child VALUES('','".$childsalutations." $childfname $childlname',' ".$cday."-".$cmonth."-$cyear ','$childline1','$childline2','$childm','$childoff','$childemail')"in a stackoverflow question(not my own question) someone says: information stating arrays need to be split, before inserting into the table. does that mean something like this?: $cday = ($_POST['cday']); $cmonth = ($_POST['cmonth']); $cyear = ($_POST['cyear']); $childsalutations = ($_POST['child-salutations']); $childfname = ($_POST['child-fname']); $childlname = ($_POST['child-lname']); $childline1 = ($_POST['child-line1']); $childemail = ($_POST['child-email']); $childm = ($_POST['child-mobile']); $childoff = ($_POST['child-office']); $info = array('c_name' => $childsalutation $childfname $childlname, 'c_dob' => $cday-$cmonth-$cyear, 'c_line1' => $childline1, 'c_mobile' => $childm, 'c_office' => $childoff, 'c_email' => $childemail)just in case u wanted to c the html child form(warning its abit long,very!): <table class="prime"> <tbody> <br> <tr><td style="font-size:20px;font-weight:bold">Child <span id="number"></span></td></tr> <tr> <td>Salutation :</td> <td><select name="child-salutations[]" id="child-salutations"> <option value="" disabled selected>Salutations</option> <option value="Datin">Datin</option> <option value="Datin Paduka">Datin Paduka</option> <option value="Dato Paduka">Dato Paduka</option> <option value="Dato'">Dato'</option> <option value="Dato' Seri">Dato' Seri</option> <option value="Datuk">Datuk</option> <option value="Datuk Seri">Datuk Seri</option> <option value="Dr.">Dr.</option> <option value="Haji">Haji</option> <option value="Hajjah">Hajjah</option> <option value="HM">HM</option> <option value="HRH">HRH</option> <option value="Miss">Miss</option> <option value="Mrs.">Mrs.</option> <option value="Mr.">Mr.</option> <option value="Pehin">Pehin</option> <option value="Professor">Professor</option> <option value="Raja">Raja</option> <option value="Tan Sri">Tan Sri</option> <option value="Tengku">Tengku</option> <option value="Tuanku">Tuanku</option> <option value="Tun">Tun</option> <option value="Tunku">Tunku</option> <option value="Ungku">Ungku</option> </select> </td> </tr> <tr><td colspan="2"><label class="label" style="color:Red">*If a person has many salutations, choose the highest form of salutation</label></td></tr> <tr><td>First Name :</td><td><input type="text" name="child-fname[]" id="child-fname" class="style" /></td> <td>Last Name :</td><td><input type="text" name="child-lname[]" id="child-lname" class="style" /></td></tr> <tr> <td>Date of Birth : </td> <td> <select name="cday[]"> <option value=""selected disabled>Day</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="cmonth[]"> <option value="" selected disabled>Month</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> Year : <input type="text" name="cyear[]" maxlength="4" size="4" class="year"> </td> </tr> <tr><td>Where do they live ?</td><td colspan="3"><input type="radio" name="living[]" id="living-me" class="living-me"/>With Me<input type="radio" name="living[]" id="living-other" class="living-other"/>With Other Parent<input type="radio" name="living[]" id="living-own" class="living-own"/>Own</td></tr> <tr><td>House Address</td></tr> <tr><td>Line 1 :</td><td><input type="text" name="child-line1[]" id="child-line1" size="20" class="style" /></td> <td>Mobile No :</td><td><input type="text" name="child-mobile[]" id="child-mobile" class="style" /></td></tr> <tr><td>Office No :</td><td><input type="text" name="child-office[]" id="child-office" class="style" /></td> <td>Email Address : </td><td><input type="email" name="child-email[]" id="email" class="style" /></td></tr> </tbody> </table> Hello Guys, I want to insert an array variable into the database e.g Code: [Select] foreach($html->find('div[class=PostContent]') as $element) { echo $element; $sq = "INSERT INTO articles(original_text) VALUES ('$element') WHERE article_link='$item_url'"; $result = mysql_query($sql1) or die('Query failed: ' . mysql_error()); } i want to insert the variable $element into the database but i'm not able to do so for some reason! $element contains only a paragraph of text. how can i insert the variable $element? Hello I have this multi dimensional array which needs to be inserted to the database table.
[business] => Array ( [title] => Email Marketing [URL] => email-marketing [category] => 3 [region] => 2 ) [description_] => Array ( [text] => Some desc ) [logo_] => Array ( [blob] => mainlogo.png ) [location_] => Array ( [text] => Array ( [0] => Lemara Main Office [1] => Themi branch [2] => Sinoni branch ) [priority] => Array ( [0] => 1 [1] => 2 [2] => 3 ) ) [photo_] => Array ( [path] => Array ( [0] => lemaraphoto.png [1] => themiphoto.png [2] => sinoniphoto.png ) ) [video_] => Array ( [path] => Array ( [0] => lemaravideo.mp4 [1] => themivideo.mp4 [2] => sinonivideo.mp4 ) ) [product_] => Array ( [p_id] => Array ( [0] => product photo [1] => product 3 photo [2] => Product 2 photo ) [text] => Array ( [0] => product desc [1] => product 3 desc [2] => product 2 desc ) [expire] => Array ( [0] => product expire [1] => product 3 expire [2] => Product 2 expire ) [title] => Array ( [0] => product [1] => Product 3 [2] => Product 2 ) ) [service_] => Array ( [p_id] => Array ( [0] => Service 2 photo [1] => service 3 photo [2] => service photo ) [text] => Array ( [0] => service 2 desc [1] => service 3 desc [2] => service desc ) [expire] => Array ( [0] => Service 2 expire [1] => service 3 expire [2] => service expire ) [title] => Array ( [0] => Service 2 [1] => service 3 [2] => service ) ) )That's the data. The database table, the table field and the corresponding value to be inserted in to the database. I'm using CodeIgniter any help would be appreciated. I have managed to make it wotk in this format [[business] => Array ( [title] => Email Marketing [URL] => email-marketing [category] => 3 [region] => 2 ) [description_] => Array ( [text] => Some desc ) [logo_] => Array ( [blob] => mainlogo.png ) ]I used this code to do it function add_bz($data){ $this->db->trans_start(); $er=0; foreach($data as $table => $sql){ if($table==="business"){ $this->db->insert($table, $sql); $id = $this->db->insert_id(); } else { array_merge($sql, array('idd' => $id)); $this->db->insert($table, $sql);} } $this->db->trans_complete(); if ($this->db->trans_status() === FALSE){print "Transaction Fails";return FALSE;} return TRUE; }Thanks in advance. Hi everyone, I'm new to this group and new to php. I have created a multi-part form that allows the user the option to add multiple input fields to a form to upload images. Here is the form structu Code: [Select] <form action="Scripts/processreports2.php" method="post" enctype="multipart/form-data" name="report_form" target="uploader" class="reportfrm"> <fieldset> <legend>Upload your images</legend> <ol id="add_images"> <li> <input type="file" class="input" name="files[]" /> </li> <li> <input type="file" class="input" name="files[]" /> </li> <li> <input type="file" class="input" name="files[]" /> </li> </ol> <input type="button" name="addFile" id="addFile" value="Add Another Image" onclick="window.addFile(this);"/> </fieldset> <p>* indicates a required field.</p> <input name="submit" type="submit" id="submit" value="Send Info!" /> </form> Through php a maximum of three input fields are fed into an array that checks to make sure that the uploaded files are images and not some other type of file. The uploading porition of this script works. Now I am trying to get the values of the input fields as a string and insert them into the database as one record. Let's say the user has three files they want to upload. I have managed to get the files as a string ie; file1.jpg, file2.jpg, file3.jpg but what is happening is that I am getting three separate records with file1.jpg, file2.jpg, file3.jpg in them. If the user has only two files to upload then I get two separate records with file1.jpg and file2.jpg in them. (Hope that makes sense). I want one record. I have been struggling with this since Monnday and while every day I get closer, this is as close as I can get. Below is the php code. #connect to the database mysql_connect("localhost", "root", ""); mysql_select_db("masscic"); //Upload Handler to check image types function is_image($file) { $file_types = array('jpeg', 'gif', 'bmp'); //acceptable file types if ($img = getimagesize($file)){ //echo '<pre>'; //print_r($_FILES); used for testing //print_r($img); used for testing if(in_array(str_replace('image/', '', $img['mime']), $file_types)) return $img; } return false; } //form submission handling if(isset($_POST['submit'])) { //file variables $fname = $_FILES['files']['name']; $ftype = $_FILES['files']['type']; $fsize = $_FILES['files']['size']; $tname = $_FILES['files']['tmp_name']; $ferror = $_FILES['files']['error']; $newDir = '../uploads/'; //relative to where this script file resides for($i = 0; $i < count($fname); $i++) { //echo 'File name ' . $fname[$i] . ' has size ' . $fsize[$i]; used for testing if ($ferror[$i] =='UPLOAD ERR OK' || $ferror[$i] ==0) { if(is_image($tname[$i])) { //append the tmp_name($tname) to the file name ($fname) and upload to the server move_uploaded_file($tname[$i], ($newDir.time().$fname[$i])); echo '<li><span class="success">'.$fname[$i].' -- image has been accepted<br></span></li>'; }else echo '<li><span class="error">'.$fname[$i].' -- is not an accepted file type<br></span></li>'; } if (is_array($fname)) $files = implode(', ',$fname); //else $files = $fname; $sqlInsert = mysql_query("INSERT INTO files (file_names) VALUES('$files')") or die (mysql_error()); } } I need a help in the following : I have an admin page from where the admin attaches an gif image.This attached image should be shown to the user as a scrolling image. The code for the scrolling image is done through javascript. So my actual problem is getting the name of the attached gif image to the javascript array which is used for scrolling horizontally. I am setting up a PHP & MySql shopping cart. When a user adds products they are stored as sessions. The cart displays the products in an array: foreach($_SESSION as $product => $quantity) So the product is the product_id, and the quantity is the quantity of that product which has been added. When getting the information from the database to display it, it reads like this 1-----2 (product_id = 1, quantity = 2) 2-----1 (product_id = 2, quantity = 1) 3-----3 (product_id = 3, quantity = 3) 11---12 (product_id = 11, quantity = 12) 4-----1 (product_id = 4, quantity = 1) I'm basically trying to insert the product_id and quantity into a table called cart. I've been stuck for days and can still only manage to insert 1 row of values Searching around I saw that some people inserted arrays using implode or explode functions first, but I'm not sure how that would work in this case Any ideas? Hi, I'm trying to save data from an array to database but something is wrong. This is from i send data, as you see im using arrays [] because the user have the posibility to clone the row <div class="box-body"> <div class="form-group"> <label class="col-sm-2">Student</label> <div class="col-sm-10"> <table id="table" border="1" bordercolor="#00acc1"> <thead> <tr> <th><p>Name</p></th> <th><p>Mode</p></th> <th><p>Sport</p></th> <th> </th> </tr> </thead> <tbody> <tr> <td><select style="width:325px" name="Name[]" class="form-control"> <option value="">Select</option> <?php $search = "SELECT * FROM prof"; $data = $connect->prepare($search); $data->execute(); while($re=$data -> fetch(PDO::FETCH_ASSOC)){ echo "<option value = '".$re['id']."'>"; echo $re['n_prof'].' '.$re['ap_prof'];} ?> </select> </td> <td> <select class="form-control" name="mode[]" style="width:150px" /> <option value="">Select</option> <option value="Administrator">Administrator</option> <option value="Scholar">Scholar</option> <option value="External student">External student</option> <option value="Thesis">Thesis</option> <option value="Voluntary">Voluntary</option> </select> </td> <td> <select class="form-control" name="Sport[]" style="width:150px" /> <option value="">Select</option> <option value="Football">Football</option> <option value="Baseball">Baseball</option> <option value="Swimming">Swimming</option> <option value="Horse riding">Horse riding</option> <option value="basketball">basketball</option> </select> </td> <td class="Delete">Delete</td> </tr> </tbody> </table> <input type="button" id="add" value="+ add student" class="btn btn-primary"/> </div> </div> </div> my db.table is like this id | name | mode | sport | idstudent_fk And Im using an algorithm to read the array and every time can save every row, but im usind PDO and im having problems try{ here i insert data in a table here i got the last id from that table then ... if($_POST['name']!="" and $_POST['mode']!="" and $_POST['sport']!=""){ if(is_array($_POST['name'])){ while(list($key, $name) = each($_POST['name']) and list($val,$mode) = each($_POST['mode']) and list($id, $sport) = each($_POST['sport'])){ $sql = "INSERT INTO sports(id_studentfk, mode_stu, sport, id_projfk) values(:value, :mode, :sport, :lastid)"; $statement = $connect ->prepare($sql); $statement -> bindParam(':name', $name, PDO::PARAM_INT); $statement -> bindParam(':mode', $mode, PDO::PARAM_STR); $statement -> bindParam(':sport', $sport, PDO::PARAM_STR); $statement -> bindParam(':lastid', $lastid, PDO::PARAM_INT); $pdoExec = $statement -> execute(); } }//end if array }//end if post } catch (PDOException $e) { print 'ERROR: '. $e->getMessage(); print '<br/>Data Not Inserted'; } the idea is creating a loop to read the array and every time can insert data. Im using PDO this time is not working, im geeting this error
ERROR: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined I hope someone can help me to solve this
Hi pals, I got a complex Array from the Query. it's Structure is like Quote Array ( => Array ( [server_name] => anes.admod.net [id] => 1 [server_id] => 1 [description] => nice Anes Server [status] => 0 [max_down_count] => 9 [check_interval] => 15 [fail_recheck] => 6 [log_retain] => 1 [warning] => 12 [critical] => 15 [timeout] => 8 [audible] => Y [email] => Y [im] => Y [sms] => Y [rss] => N [rssid] => [vcare] => Y [created] => 2010-12-06 10:26:26 [last_update] => 2010-12-13 16:41:48 [name] => POP3 [port] => 110 [okay] => OK [warn] => WARNING [crit] => CRITICAL [down] => Connection refused [advanced] => N [typestatus] => 1 ) [1] => Array ( [server_name] => neseema.admod.net [id] => 2 [server_id] => 2 [description] => another server [status] => 1 [max_down_count] => 11 [check_interval] => 15 [fail_recheck] => 12 [log_retain] => 2 [warning] => 12 [critical] => 16 [timeout] => 6 [audible] => Y [email] => Y [im] => Y [sms] => N [rss] => N [rssid] => [vcare] => N [created] => 2010-12-07 10:27:42 [last_update] => 2010-12-13 16:41:48 [name] => Cpanel [port] => 2082 [okay] => OK [warn] => WARNING [crit] => CRITICAL [down] => Connection refused [advanced] => N [typestatus] => 1 ) [2] => Array ( [server_name] => anes.admod.net [id] => 3 [server_id] => 1 [description] => nice Anes Server another Service [status] => 1 [max_down_count] => 14 [check_interval] => 15 [fail_recheck] => 3 [log_retain] => 3 [warning] => 12 [critical] => 16 [timeout] => 18 [audible] => Y [email] => [im] => [sms] => [rss] => N [rssid] => [vcare] => N [created] => 2010-12-07 12:58:01 [last_update] => 2010-12-13 16:41:48 [name] => SMTP [port] => 25 [okay] => OK [warn] => WARNING [crit] => CRITICAL [down] => Connection refused [advanced] => N [typestatus] => 1 ) ) In this Result I have 2 Rows in result to show, I mean I need to merge the data of First (0th) and Third(2nd) element because it display the data of same item. So How it can done, I am working in that whole day but not get a solution fully.... I saw a near solution like : <?php $input = array( 0 => array ( 'id' => 160, 'payment_period' => 'Monthly', 'plan_payment_type_id' => 171, 'payment_type_id' => 4), 1 => Array ( 'id' => 160, 'payment_period' => 'Monthly', 'plan_payment_type_id' => 172, 'payment_type_id' => 5), 2 => Array ( 'id' => 161, 'payment_period' => 'Weekly', 'plan_payment_type_id' => 173, 'payment_type_id' => 9), ); echo "<pre>"; print_r($input); echo "</pre>"; echo "****************************************************************************"; $output = array(); $id_array = array(); $i = 0; foreach($input as $key=>$val) { if(array_key_exists($val['id'],$id_array)) { $pos = $id_array[$val['id']]; $output[$pos]['payment_types'][] = array('plan_payment_type_id'=> $val['plan_payment_type_id'],'payment_type_id' => $val['payment_type_id']); } else { $output[$i] = array('id' => $val['id'],'payment_period' => $val['payment_period'],'payment_types' => array(array('plan_payment_type_id'=> $val['plan_payment_type_id'],'payment_type_id' => $val['payment_type_id']))); $id_array[$val['id']] = $i; $i++; } } echo "<pre>"; print_r($output); echo "</pre>"; ?> But I cannot handle it nicely, please give any sample or helping code idea for same , waiting your immediate Reply Thankfully Anes P.A I am trying to array data to database against same id.
Here is code.
form.php
<form name="users" method="post" action="order_submit.php" enctype="multipart/form-data" onSubmit="return validate();" id="inv_form"> <div class="formSep"> <select name="company" onChange="showSubcat(this);"> <option value="">Company</option> <?php $s1 = mysql_query("select * from leads where lead_customer='Lead' ") or die (mysql_error()); while($s2 = mysql_fetch_array($s1)) { ?> <option value="<?php echo $s2['id']; ?>"><?php echo $s2['company']; ?></option> <?php } ?> </select> </div> <div class="formSep"> <table class="table invE_table"> <thead> <tr> <th></th> <th>Item</th> <th>Unit</th> <th>Unit Cost ($)</th> <th>Qty</th> <th>Tax (%)</th> <th>Total ($)</th> </tr> </thead> <tbody> <tr class="inv_row"> <td class="inv_clone_row"><i class="icon-plus inv_clone_btn"></i></td> <td><input type="text" class="span12" name="invE_item[]" /></td> <td><input type="text" class="span12" name="invE_description[]" /></td> <td><input type="text" class="span12 jQinv_item_unit" name="invE_unit_cost[]" /></td> <td><input type="text" class="span12 jQinv_item_qty" name="invE_qty[]" /></td> <td><input type="text" class="span12 jQinv_item_tax" name="invE_tax[]" /></td> <td><input type="text" readonly class="span12 jQinv_item_total" name="invE_total[]" /></td> </tr> <tr class="last_row"> <td colspan="5"> </td> <td colspan="2"> <p class="clearfix">Subtotal: <span class="invE_subtotal">$<span>0.00</span></span></p> <p>Tax: <span class="invE_tax">$<span>0.00</span></span></p> <p>Discount: <span class="invE_discount">$<span>0.00</span></span></p> <p><strong>Balance: <span class="invE_balance">$<span>0.00</span></span></strong></p> </td> </tr> </tbody> </table> </div>Here invE_item[], invE_description[], invE_unit_cost[].... are the array , i mean dynamically one can add as many as items and its details. In my order_submit.php page <?php error_reporting(0); include("connect.php"); include("admin_auth.php"); if(isset($_POST['save'])) { $company = $_POST['company']; $contact_person = $_POST['contact_person']; $billing = $_POST['billing_address']; $shipping = $_POST['shipping_address']; $reference = $_POST['reference']; $t_c = $_POST['t_c']; $payment = $_POST['payment']; $ship_in = $_POST['ship_inst']; $validity = $_POST['validity']; $currency = $_POST['currency']; $order_for = $_POST['order_for']; $assigned_to = $_POST['assigned_to']; $item = $_POST['invE_item']; $unit = $_POST['invE_description']; $price = $_POST['invE_unit_cost']; $qty= $_POST['invE_qty']; $tax = $_POST['invE_tax']; $total = $_POST['invE_total']; $sql = mysql_query("insert into orders (order_id, company_id, contact_person, billing_address, shipping_address, reference, t_c, payment, shipping_inst, validity, order_for, currency, assigned_to, last_modified, order_quote) values ('', ".$company.", '".$contact_person."', '".$billing."', '".$shipping."', '".$reference."', '".$t_c."', '".$payment."', '".$ship_in."', ".$validity.", '".$order_for."', '".$currency."', '".$assigned_to."', NOW(), 'Order')"); $last_id = mysql_insert_id(); $msql = "insert into order_line_items (id, order_id, company_id, item, unit, unit_cost, quantity, tax, total) values ('', ".$last_id.", ".$company.", '".$item."', '".$unit."', ".$price.", ".$qty.", ".$tax.", ".$total.")"; $l1 = mysql_query($msql) or die (mysql_error()); }I want to insert each item in different row with $last_id , as in the attached image . Please somebody help me in this Attached Files db.PNG 11.01KB 4 downloads I need to set up a threaded comments system in a PHP project and I got this script shown below from http://www.jongales....#comment-436261
class Threaded_comments { public $parents = array(); public $children = array(); /** * @param array $comments */ function __construct($comments) { foreach ($comments as $comment) { if ($comment['parent_id'] === NULL) { $this->parents[$comment['id']][] = $comment; } else { $this->children[$comment['parent_id']][] = $comment; } } } /** * @param array $comment * @param int $depth */ private function format_comment($comment, $depth) { for ($depth; $depth > 0; $depth--) { echo "\t"; } echo $comment['text']; echo "\n"; } /** * @param array $comment * @param int $depth */ private function print_parent($comment, $depth = 0) { foreach ($comment as $c) { $this->format_comment($c, $depth); if (isset($this->children[$c['id']])) { $this->print_parent($this->children[$c['id']], $depth + 1); } } } public function print_comments() { foreach ($this->parents as $c) { $this->print_parent($c); } } }Here’s the example usage with the data provided as an array: $comments = array( array('id'=>1, 'parent_id'=>NULL, 'text'=>'Parent'), array('id'=>2, 'parent_id'=>1, 'text'=>'Child'), array('id'=>3, 'parent_id'=>2, 'text'=>'Child Third level'), array('id'=>4, 'parent_id'=>NULL, 'text'=>'Second Parent'), array('id'=>5, 'parent_id'=>4, 'text'=>'Second Child') ); $threaded_comments = new Threaded_comments($comments); $threaded_comments->print_comments();I have a sample select query that pulls data from a database and stores the result in the $comments array as shown below. The $comments array is then passed as an argument to the $threaded_comments object: $sql = 'SELECT * FROM test_comments'; // submit the query and capture the result $result = $conn->query($sql); $comments = array(); while ($row = $result->fetch_assoc()) { $comments[] = $row; }The challenge is that nothing is printed to the screen when I run the script. Inspection of the comments array with the var_dump function is shown below: array (size=4) 0 => array (size=3) 'id' => string '1' (length=1) 'parent_id' => string '0' (length=1) 'text' => string 'comment' (length=7) 1 => array (size=3) 'id' => string '2' (length=1) 'parent_id' => string '0' (length=1) 'text' => string 'comment' (length=7) 2 => array (size=3) 'id' => string '3' (length=1) 'parent_id' => string '1' (length=1) 'text' => string 'comment ' (length=8) 3 => array (size=3) 'id' => string '4' (length=1) 'parent_id' => string '3' (length=1) 'text' => string 'comment ' (length=8)I was wondering if the array format from my select query is the issue? Could anyone provide a clue as to how to fix this? Thanks. Edited by terungwa, 11 January 2015 - 05:07 PM. |