PHP - Inserting Array Of Data Into Database
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? Similar TutorialsI 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 Hey all I really need help with a project I am doing. I need to create a website with a registration form that checks if the user exists if not to add the user details to my local database MySQL. My webpage looks like it should, it connects with the database but when I enter a new user it does nothing when it should save the new user to the database! I am guessing my problem is within the if...else section. Please help my code is: Code: [Select] <?php include('connect.php'); //connection details to database in a connect.php page $name = ""; $surname = ""; $username = ""; $password = ""; $confirmp = ""; $errorMessage = ""; $num_rows = 0; //if form was submitted if ($_SERVER['REQUEST_METHOD'] == 'POST'){ //get values from fields $submit = $_POST['Submit']; $title = $_POST['title']; $name = $_POST['name']; $surname = $_POST['surname']; $username = $_POST['username']; $password = $_POST['password']; $confirmp = $_POST['confirmp']; //getting string lengths $nameLength = strlen($name); $surnameLength = strlen($surname); $usernameLength = strlen($username); $passwordLength = strlen($password); $confirmpLength = strlen($confirmp); //testing if strings are between certain numbers if ($nameLength > 1 && $nameLength <= 20) { $errorMessage = ""; } else { $errorMessage = $errorMessage . "Name must be between 2 and 20 characters" . "<br>"; } if ($surnameLength >= 2 && $surnameLength <= 50) { $errorMessage = ""; } else { $errorMessage = $errorMessage . "Surname must be between 2 and 50 characters" . "<br>"; } if ($usernameLength = 6) { $errorMessage = ""; } else { $errorMessage = $errorMessage . "Username must be 6 characters long" . "<br>"; } if ($passwordLength = 6) { $errorMessage = ""; } else { $errorMessage = $errorMessage . "Password must be 6 characters long" . "<br>"; } if ($confirmpLength = 6) { $errorMessage = ""; } else { $errorMessage = $errorMessage . "Password must be 6 characters long" . "<br>"; } if ($errorMessage == "") { $query = "SELECT * FROM user WHERE username = '$username' AND password = '$password'"; $result = mysql_query($query); $num_rows = mysql_num_rows($result); //check to see if the $result is true if ($num_rows = 1){ $errorMessage = "Username already exists"; } else { if($password == $confirmp){ $query = "INSERT INTO user (title, name, surname, username, password) VALUES ('$title', '$name', '$surname', '$username', '$password')"; $result = mysql_query($query); session_start(); $_SESSION['login'] = "1"; header ("Location: login.php"); } else { $errorMessage = "Passwords do not match!"; } } } else { $errorMessage = "Error Registering"; } } else { $errorMessage = "Please enter your details"; } ?> <html> <head> <title>Mia's Beauty Products</title> </head> <body> <p><img src = "banner1.jpg" width = "975" height = "95" alt = "Mia's Beauty Product" /></p> <br> <p align= "center"><a href="register.php">Register</a> | <a href="login.php">Login</a> | <a href="insert.php">Insert</a> | <a href="list.php">List</a></p> <form method = "post" action = "register.php"> <table> <tr><td>Title:</td><td><select name = "title"> <option>Miss</option> <option>Mrs</option> <option>Mr</option> </select></td></tr> <tr><td>Name:</td><td><input name = "name" type = "text" value ="<?php print $name;?>"></td></tr> <tr><td>Surname:</td><td><input name = "surname" type = "text" value ="<?php print $surname;?>"></td></tr> <tr><td>Username:</td><td><input name = "username" type = "text" value ="<?php print $username;?>"></td></tr> <tr><td>Password:</td><td><input name = "password" type = "password" value ="<?php print $password;?>"></td></tr> <tr><td>Confirm Password:</td><td><input name = "confirmp" type = "password" value ="<?php print $confirmp;?>"></td></tr> <tr><td><input type = "submit" name = "Submit" value = "Submit"></td></tr> </table> </form> <p align= "center"><a href="code.txt">Code</a></p> <br> <?php print $errorMessage; ?> <p><img src = "banner2.jpg" width = "975" height = "95" alt = "Mia's Beauty Product" /></p> </body> </html> Thank you Amanda Hi,
I have a form like this
<tr> <td><a href="edit_sales_invoice_details.php?id=<?php echo $row['dispatch_id']?>"><?php echo $row['oid'] ?></a></td> <td><?php echo $row['dispatch_id'] ?></td> <td><?php echo $row['cname'] ?></td> <td><?php echo $row['iname'] ?></td> <td><?php echo $row['quantity'] ?></td> <td><?php echo $row['dispatch_quantity'] ?></td> <td><select name="tax[<?php echo $row['dispatch_id']?>]" class="span9"> <option value="<?php echo $row['rate'] ?>"><?php echo $row['tname'].'-'.$row['rate'];?> %</option> <option value="">Tax</option> <?php $s1 = mysql_query("select * from taxes"); while($s2 = mysql_fetch_array($s1)) { ?> <option value="<?php echo $s2['rate'] ?>"><?php echo $s2['name'].'-'.$s2['rate'] ?>%</option> <?php } ?> </select> </td> <td><input type="text" name="freight[<?php echo $row['dispatch_id']?>]" class="span6" /></td> <td><input type="text" name="discount[<?php echo $row['dispatch_id']?>]" class="span6" /></td> <input type="hidden" name="order_id[<?php echo $row['dispatch_id']?>]" value="<?php echo $row['oid']; ?>" /> <td><input type="checkbox" name="selector[]" value="<?php echo $row['dispatch_id']; ?>" /></td> </tr> <?php } ?> <tr><td colspan="11"><input type="submit" name="submit" value="SAVE INVOICE" class="btn btn-info" /></td></tr>Here dispatch_id will be different but the order_id will be same. I want to generate a single invoice id for this and store it in this table invoice.JPG 18.85KB 0 downloads and by taking that invoice_id, i want to insert rest of the multiple line items to this table invoice_line_items.JPG 29.7KB 0 downloads I tried doing like this Hi.. I need help in using for loop in saving data from while loop. Now, I encountered that the Demanded Qty was get only is the last Demanded Qty and save it to all Items. I want to happen is per Items will save the Demanded Qty. for example: Items Demanded Qty P28 ---1 P28 ---1 P28 ---1 P30 ---2 P30 ---2 P30 ---2 and so on.. here is my code: <?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 { $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; var Items = document.getElementById("Items").value; document.stock_requisition.action="StockRequisitionSave1.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+"&Items="+Items; document.stock_requisition.submit(); alert("Stock Requisition data save."); window.location = "StockRequisition1.php"; } function disp(){ document.stock_requisition.action="StockRequisitionDisplay.php"; document.stock_requisition.submit(); } </script> </head> <body> <form name="stock_requisition" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div id="SR_date"> <label>Date :</label> <input type="text" name="sr_date" value="<?php echo $sr_date; ?>" size="16" readonly="readonly"> </div> <div id="SR_number"> <label>SR# :</label> <input type="text" name="sr_number" value="<?php echo $currentSR; ?>" size="10" readonly="readonly"> <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> <input type='name' value='$Items' name='Items[]' id='Items' readonly = 'readonly' size='5'></td> <td> </td> <td> </td> <td><center><input type='text' name='DemandedQty' id='DemandedQty[]' value='' size='7'></center></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> <input type='hidden' value='$Items1' id='Items1' name='Items1[]'></td> <td> <input type='text' name='SubItems[]' value='$SubItems' id='SubItems' readonly='readonly' size='10'></td> <td> <input type='text' name='ItemCode[]' value='$ItemCode' id='ItemCode' readonly='readonly' size='10'></td> <td> </td> <td> <input type='text' name='UoM[]' value='$UoM' id='UoM' readonly='readonly' size='3'></td> <td> <input type='text' name='Class[]' value='$Class' id='Class' readonly='readonly' size='10'></td> <td> <input type='text' name='Description[]' value='$Description' id='Description' readonly='readonly' size='10'></td> <td> <input type='text' name='BINLocation[]' value='$BINLocation' id='BINLocation' readonly='readonly' size='10'></td> </tr>"; } } ?> </table> </div> <?php $RequestedBy = array('AAA', 'BBB'); $ApprovedBy = array('EEE', 'FFF'); $ReceivedBy = array('III', 'JJJ'); $IssuedBy = array('MMM', 'NNN'); ?> <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> </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> </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> </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> </select> </div> <div id="save_btn"> <input type="button" name="button" value="save" onClick="save_sr()" style="width: 5em;"> <input type="button" name="button" value="display" onclick="disp()"> </div> </form> </body> </html> and here is the save code: <?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']; $Items = $_POST['Items']; for($i = 0; $i < count($Items1); $i++) { if ( $DemandedQty != "" ) { $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[$i]', '$SubItems[$i]', '$ItemCode[$i]', '$DemandedQty', '$UoM[$i]', '$Class[$i]', '$Description[$i]', '$BINLocation[$i]', '$RequestedBy', '$ApprovedBy', '$ReceivedBy', '$IssuedBy') "; $result = mysql_query($sql, $con); } } ?> I attach my sample form and the data save in database. Thank you so much hello friends, actually i am trying to insert data in mysql database. here is my code <?php include_once("../includes/database.php"); ?> <!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>Insert Product</title> </head> <body> <form action="insert_product.php" method="post" enctype="multipart/form-data"> <table align="center" width="600"> <tr align="center"> <td colspan="8"><h2> Insert New Post</h2></td> </tr> <tr> <td align="right"><b>Product Title :</b></td> <td><input type="text" name="product_title" size="50" style="background-color:#06C; color:#FFF" /></td> </tr> <tr> <td align="right"><b>Product Category :</b></td> <td> <select name="product_cat" style="background-color:#06C; color:#FFF" > <option>Select A Category </option> <?php $get_cats = "SELECT * FROM categories"; $run_cats = mysqli_query($con, $get_cats); while($row_cats = mysqli_fetch_array($run_cats)){ $cat_id = $row_cats['cat_id']; $cat_title = $row_cats['cat_title']; echo "<option value='$cat_id'>$cat_title</option>"; } ?> </select> </td> </tr> <tr> <td align="right"><b>Product Platform :</b></td> <td> <select name="product_brand" style="background-color:#06C; color:#FFF" > <option>Select A Platform </option> <?php $get_brands = "SELECT * FROM brands"; $run_brands = mysqli_query($con, $get_brands); while($row_brands = mysqli_fetch_array($run_brands)){ $brand_id = $row_brands['brand_id']; $brand_title = $row_brands['brand_title']; echo "<option value='$brand_id'>$brand_title</option>"; } ?> </select> </td> </tr> <tr> <td align="right"><b>Product Image :</b></td> <td><input type="file" name="product_image" /></td> </tr> <tr> <td align="right"><b>Product Price :</b></td> <td><input type="text" name="product_price" style="background-color:#06C; color:#FFF" /></td> </tr> <tr> <td align="right" valign="top"><b>Product Description :</b></td> <td><textarea name="product_desc" cols="50" rows="10" style="background-color:#06C; color:#FFF" ></textarea></td> </tr> <tr> <td align="right"><b>Product Keywords :</b></td> <td><input type="text" name="product_keywords" size="50" style="background-color:#06C; color:#FFF" /></td> </tr> <tr align="center"> <td colspan="8"><input type="submit" name="insert_post" value="Submit Now" /></td> </tr> </table> </form> </body> </html> <?php if(isset($_POST['insert_post'])){ $product_title = $_POST['product_title']; $product_cat = $_POST['product_cat']; $product_brand = $_POST['product_brand']; $product_price = $_POST['product_price']; $product_desc = $_POST['product_desc']; $product_keywords = $_POST['product_keywords']; $product_image = $_FILES['product_image']['name']; $product_image_tmp = $_FILES['product_image']['tmp_name']; move_uploaded_file($product_image_tmp,"product_image/$product_image"); $sql = "INSERT INTO products (product_cat,product_brand,product_title,product_price,product_desc,product_image,product_keywords) VALUES ('$product_cat','$product_brand','$product_title','$product_price','$product_desc','$product_image','$product_keywords')"; $query = mysqli_query($con, $sql); if($query){ echo "<script>alert('Product Has Been Inserted')</script>"; echo "<script>windoow.open('insert_product.php','_self')</script>"; exit(); }else{ echo "<script>alert('errror')</script>"; } } ?>but somehow its not inserting data into my table can somebody tell wherre m i doing mistake. the categories and brands are displaying from database. But its not inserting data here is my database script. <?php $con = mysqli_connect("localhost","root","","sg"); ?> Lets say I have this database: table brand [brandID] [brandName] where brandID -> auto increment and one brand always has the same brandID table product [brandID] [productID] [price] where productID -> auto increment I want to insert new product into the database using only values [brandName] and [price] and want brandID and productID to be created automatically I use this form: <form id="insertingDataToBrand" action="administratorCode.php" method="post"> <div>Brand Name: <input type="text" name="brandName"/></div> <div>Price: <input type="text" name="price"/></div> </form> And here is the php code: <?php //connection to database include 'connectToDatabase.php'; //data retrieveing $brand = $_POST['brandName']; $price = $_POST['price']; //As I am inserting to two different tables I use two INSERT statements $sql = "INSERT INTO brand (brandName) values ('$brand')"; mysql_query($sql) or die (mysql_error()); //as brandID is created automatically I am going to insert the same value to another table $last_id = mysql_insert_id (); $sql = "INSERT INTO product (price, brandID) values ('$price', '$last_id')"; ?> This should work just fine (it doesnt tho) BUT my question is: I have 3 different brands (brand A with brandID 1, brand B with brandID 2, brand C with brandID 3). When want to insert brand D, automatically created brandID should be automatically set to 4. BUT when I want to insert product of the same brand, lets say brand A (with different productID) brandID is automatically set to 4(or higher) as well. What do I have to do(use) so it would be able to realise what brandID should be added? Thanks a lot. hey there I have an issue when I am inserting an array into the database. When I run the insert statements the records get inserted but it is sometimes one less record than is in the table and sometimes even less. for example if I have 5 records it only inserts the first 4. This is confusing because when I echo out the statement in the loop it shows all 4 insert statements. my loop for inserting looks like this: if(isset($_SESSION['cushArray'])){ foreach($_SESSION['cushArray'] as $key => $value){ $getCushSKU = "SELECT SKU FROM Cushion WHERE Name = '".$value['Cushion']."'"; //echo $getCushSKU; $resultGetCushSKU = mysql_query($getCushSKU); $getResultGetCushSKU = mysql_fetch_assoc($resultGetCushSKU); //echo $getResultGetCushSKU['SKU']; $getFabricSKU = "SELECT SKU FROM Fabric WHERE Name = '".$value['Fabric']."'"; $resultGetFabricSKU = mysql_query($getFabricSKU); $getResultGetFabricSKU = mysql_fetch_assoc($resultGetFabricSKU); if($_SESSION['cushArray'][$i]["ContWeltFabric"] != "N/A"){ $getWeltFabricSKU = "SELECT SKU FROM Fabric WHERE Name = '".$value['ContWeltFabric']."'"; $resultGetWeltFabricSKU = mysql_query($getWeltFabricSKU); $getResultGetWeltFabricSKU = mysql_fetch_assoc($resultGetWeltFabricSKU); }else{ $getResultGetWeltFabricSKU = "N/A"; } $sqlCush = "INSERT INTO OrdersCushion(OrderID, ProductSKU, FabricSKU, WeltFabricSKU, Quantity, ButtonColor, ZipperColor, Fill) VALUES('".$getOrderIDNum['OrderID']."', '".$getResultGetCushSKU['SKU']."', '".$getResultGetFabricSKU['SKU']."', '".$getResultGetWeltFabricSKU['SKU']."', '".$value['Quantity']."', '".$value['Button']."', '".$value['Zipper']."', '".$value['Fill']."') "; //echo $sqlCush; $resultCush = mysql_query($sqlCush); } } any help is much appreciated Hello All, First, I'm new to php and I have spent a lot of time searching forums and google for the answer to my question with no luck, so if it's a topic already covered, PLEASE reply with a link or point me in the right direction. OK, I have a form that let's users upload multiple images. The upload portion works fine. What I can't figure out how to do is put the image name of each file that gets uploaded all into the same table record. I also need each file name to be put into it's own column in the table. For example, file1, file2 and file3 will get dumped into the same record and into it's respective column (uploaded_image1, uploaded_image2, uploaded_image3). I've included the working upload code and the code that inserts some of the information into the database (just not the image names). Code: [Select] echo "<textarea name=challenge rows=15 cols=60> </textarea><br/><br/>" echo "<textarea name=insight rows=15 cols=60> </textarea><br/><br/>" for($i=1; $i<=$max_no_img; $i++){ echo "Image $i <input type=file name='image[]' ><br/>"; } echo "<input type=submit value=Submit>"; Code: [Select] // Connect to DB $host = 'xxx'; $user = 'xxx'; $pass = 'xxx'; $db = 'xxx'; mysql_connect($host,$user,$pass) or die(mysql_error()); mysql_select_db($db) or die(mysql_error()); // Post Variables $challenge = $_POST['challenge']; $insight = $_POST['insight']; $filename=serialize($_POST['filename']); // Upload Images while(list($key,$value) = each($_FILES[image][name])) { if(!empty($value)) { $filename = $value; $add = "upimage/$filename"; copy($_FILES[image][tmp_name][$key], $add); chmod("$add",0777); } } // Insert into database $query = "INSERT INTO table ( challenge, insight, uploaded_image1, uploaded_image2, uploaded_image3,)". "values ( '$challenge', '$insight', '$filename' '$filename2' '$filename3')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); I know just enough about php that the reason the above wont work, is because $filename2 and $filename3 haven't been given a value. Unfortunately, I have no idea how to separate that information in the array. If anyone can point me in the right direction I'd be forever grateful! Thanks, Gary Hello there,
I'm really new at PHP and I've been reading several beginner tutorials so please accept my apologies for any stupid questions I may ask along the way.
I've gotten as far as installing XAMPP, set up a database plus PHP form and I'm struggling to figure out how to insert values from an array into my database.
I've learnt the code in one particular way (see beginner tutorials) so I was wondering if you could help me keeping this in mind. I know there'll be a million better ways to do what I'm doing but I fear I will be bamboozled with different code or differently structured code.
Anyway the tutuorials I'm reading don't see to cover how I can insert an array of values into my database, just singular values.
In the attached file, I have 10 rows of 2x text inputs (20 text inputs total). Each row allows the user to enter a CarID and CarTitle. I've commented out the jQuery which validates the inputs so I can build a rudimentary version of this validation with PHP.
I thought that because the line $sql="INSERT INTO carids_cartitles (CarID, CarTitle) VALUES ($id, $title)"; is inside the foreach, means that for each pair of values from the form it'd insert to the database.
It doesn't do this. If I enter two or more CarIDs and CarTitles, only one pair of values gets saved to the database.
I'm sorry if I haven't explained this well enough, any questions please let me know.
Many thanks for your help in advance.
Attached Files
form.php 4.43KB
5 downloads So I've spent 2 days now searching the web on how to make my checkbox array on my form insert the value selected by the user into my database. Here is the code that I've written. All fields except for the checkbox array works fine. <?php virtual('/budgets/Connections/connAdmin.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if (isset($_POST['submit'])) { $workStyle = $_POST['art_photos']; // Setting up a blank variable to be used in the coming loop. $allStyles = ""; // For every checkbox value sent to the form. foreach ($workStyle as $style) { // Append a string called $allStyles with the current array element, and then add a comma and a space at the end. $allStyles .= $style . ", "; } // Delete the last two characters from the string. $allStyles = substr($allStyles, 0, -2); echo "<p>The resulting string is: <strong>$allStyles</strong></p>\r\n"; } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { $insertSQL = sprintf("INSERT INTO daily_budget (rundate, slug, reporter, budgetInfo, notes, `section`, deadline, art_photos sidebar, sBudget) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['rundate'], "text"), GetSQLValueString($_POST['slug'], "text"), GetSQLValueString($_POST['reporter'], "text"), GetSQLValueString($_POST['budgetInfo'], "text"), GetSQLValueString($_POST['notes'], "text"), GetSQLValueString($_POST['section'], "text"), GetSQLValueString($_POST['deadline'], "text"), GetSQLValueString($_POST['art_photos'], "text"), GetSQLValueString($_POST['sidebar'], "text"), GetSQLValueString($_POST['sBudget'], "text")); mysql_select_db($database_connAdmin, $connAdmin); $Result1 = mysql_query($insertSQL, $connAdmin) or die(mysql_error()); } ?> <!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>Budget Record</title> </head> <body> <?php if (isset($error)) { echo '<ul>'; foreach($error as $alert) { echo "<li class='warning'>$alert</li>\n"; } echo '</ul>'; } ?> <form action="<?php echo $editFormAction; ?>" method="POST" name="form1" id="form1"> <table align="center" width="60%" border="2" bgcolor="#FFFFFF"> <tr valign="baseline"> <td width="14%" align="right" nowrap="nowrap"><STRONG>Rundate:</STRONG></td> <td width="86%"> <input type="text" name="rundate" size="30" value="" id="jQueryUICalendar2"/> <script type="text/javascript"> // BeginWebWidget jQuery_UI_Calendar: jQueryUICalendar2 jQuery("#jQueryUICalendar2").datepicker(); // EndWebWidget jQuery_UI_Calendar: jQueryUICalendar2 </script></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><STRONG>Section:</STRONG></td> <td> <select name="section"> <option value=""></option> <option value="A1">A1</option> <option value="Pickup All">Pickup All</option> <option value="Region">Region</option> <option value="Atlantic">Atlantic</option> <option value="Business">Business</option> <option value="Features">Features</option> <option value="Sports">Sports</option> </select> </td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Slug:</strong></td> <td><span id="sprytextfield2"> <input type="text" name="slug" value="" size="32" /> <span class="textfieldRequiredMsg">REQUIRED</span></span><span style="color: #F00; font-weight: bold; font-size: 10px;"></span></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Budget Information:</strong></td> <td><span id="sprytextarea1"> <textarea name="budgetInfo" cols="50" rows="4"></textarea> <span class="textareaRequiredMsg">Required.</span></span><span style="color: #F00; font-weight: bold; font-size: 11px;"></span></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Notes:</strong></td> <td><input type="text" name="notes" value="" size="32" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Reporter:</strong></td> <td><span id="sprytextfield3"> <input type="text" name="reporter" value="" size="32" /> <span class="textfieldRequiredMsg">Required.</span></span><span style="color: #F00; font-weight: bold; font-size: 10px;"></span></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Deadline:</strong></td> <td><input type="text" name="deadline" size="30" value="Enter date" id="jQueryUICalendar1"/><script type="text/javascript"> // BeginWebWidget jQuery_UI_Calendar: jQueryUICalendar2 jQuery("#jQueryUICalendar1").datepicker(); // EndWebWidget jQuery_UI_Calendar: jQueryUICalendar2 </script> </td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Artwork:</strong></td> <td><label> <input type="checkbox" name="art_photos[]" value="factbox" id="art_photos_0" /> Factbox</label> <label> <input type="checkbox" name="art_photos[]" value="graphic" id="art_photos_1" /> Graphic</label> <label> <input type="checkbox" name="art_photos[]" value="photo" id="art_photos_2" /> Photo</label> <label> <input type="checkbox" name="art_photos[]" value="video" id="art_photos_3" /> Video</label> <br /></td> </tr> <tr> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"> <strong>Sidebar:</strong></td> <td valign="baseline"><span id="spryradio2"> <label> <input type="radio" name="sidebar" value="y" id="sidebar_0" /> Yes</label> <br /> <label> <input type="radio" name="sidebar" value="n" id="sidebar_1" /> No</label> <br /> <span class="radioRequiredMsg"><strong style="font-size: 11px">REQUIRED.</strong></span></span> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Sidebar Information:</strong></td> <td><input type="text" name="sBudget" value="" size="32" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"> </td> <td><input type="submit" value="Insert record" /></td> </tr> </table> <input type="hidden" name="MM_insert" value="form1" /> </form> <p> </p> <h3><a href="/new_budget/admin/manage_budgets.php"><strong>View your budget entry, make changes or delete your budget.</strong></a></h3> <script type="text/javascript"> <!-- jQuery("#jQueryUICalendar1").datepicker(); jQuery("#jQueryUICalendar2").datepicker(); var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "none", {maxChars:15, validateOn:["change"]}); var sprytextarea1 = new Spry.Widget.ValidationTextarea("sprytextarea1", {validateOn:["change"]}); var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3"); var spryradio2 = new Spry.Widget.ValidationRadio("spryradio2"); //--> </script> </body> </html> Before I get into my problem a couple of things. First, this is a work project. My organization cannot afford a full time developer so as a database guy I'm being asked to develop a web based data system using php/html/mysql/javacript/etc. So I am not asking anyone to help me cheat or violate an honor code for a school project. Also I am having to learn PHP on the fly, by the seat of my pants. Second, my organization is using a version of PHP older that 5.5.X and I am powerless to update the version. So I know that some of the syntax I am using has been deprecated in more recent PHP versions. I don't mean to sound snarky or ungrateful but I really need some help solving this problem versus unhelpful comments about deprecated code. Third I am adapting code from the guys at TechStream so H/T to them. Here is what I am trying to build. My office helps other offices in my large organization manage their records through the creation of a file plan. We are currently using a clunky, user-unfriendly Access database that was created back in 2009. I am tasked to transition that Access hoopty into a proper, web-based, user friendly system. The index.php form page consists of 2 parts. You can see the original TechStream demo he http://demo.techstre...ssing-with-PHP/ I've adapted the top part of the form ("Travel Information") for my users to enter information about their office such as Office Name, Office Code, Office Chief, Creator (the user), Status and date. I've adapted the bottom part of the form ("Passenger Details") to be "Folder Details". This is an html table where users can add up to 10000 rows to list all the folders for their office by entering the folder name in the text box and then assign descriptors to each folder using the drop down menus. I've changed the drop down menus to reflect the descriptors we need, i.e. file-series, classification, media type. The user needs the flexibility to add folders as the number of folders will vary between offices. This adding and deleting of folders is accomplished dynamically through a javascript script.js file. Now, here's my problem. When the user clicks submit button that fires a php script that runs an insert into query to place the array data into the backend mysql database. However, when the foreach loop is only inserting the office office from the top portion of the form with the first folder in the bottom portion of the form. In other words let's say the user fills out the top part with his office information and then adds 5 folders into the html table at the botton. The first folder will be inserted into the database table with both office information and folder information. However the subsequent 4 folders will have their folder information inserted into the table but the office information fields will be null. The office information needs to be inserted with each folder the user adds to the html table piece. I suspect that my foreach loop is only capturing that office information on the first iteration of the loop and then flushing or deleting the office information after the first loop. Also, I suspect there is some disconnect between the html table for entering individual folders and the top part of the form that is not in html format. Any help I can get is most welcome. Thanks in advance! Code is below. index.php <?php session_start(); if(!isset($_SESSION['myusername'])) { header('Location:index.php'); } echo $_SESSION['myusername']; echo '<a href="logout.php"><span>Logout</span></a></li>'; <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Records Management File Plan Application</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <link rel="stylesheet" type="text/css" href="css/default.css"/> <script type="text/javascript" src="js/script.js"></script> </head> <body> <form action="InsertFileDetailArraytoDB.php" class="register" method="POST"> <h1>Office File Plan Application/h1> <fieldset class="row1"> <legend>Office Information</legend> <p> <label>Office Code * </label> <input name="officecode[]" type="text" required="required"/> <label>Date* </label> <select class="date" name="day[]"> <option value="1">01 </option> <option value="2">02 </option> <option value="3">03 </option> <option value="4">04 </option> <option value="5">05 </option> <option value="6">06 </option> <option value="7">07 </option> <option value="8">08 </option> <option value="9">09 </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="month[]"> <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> <select name="year[]"> <option value="2013">2013 </option> <option value="2014">2014 </option> <option value="2015">2015 </option> <option value="2016">2016 </option> </select> </p> <p> <label>Office Chief* </label> <input name="officechief[]" required="required" type="text"/> <label>Status* </label> <select name="status[]"> <option value="Draft">Draft </option> <option value="Submitted">Submitted </option> <option value="Approved">Approved </option> </select> </p> <p> <label>Creator * </label> <input name="creator[]" required="required" type="text"/> </p> <div class="clear"></div> </fieldset> <fieldset class="row2"> <legend>Folder Details</legend> <p> <input type="button" value="Add Folder" onClick="addRow('dataTable')" /> <input type="button" value="Remove Folder" onClick="deleteRow('dataTable')" /> <p>(All actions apply only to entries with check marked check boxes.)</p> </p> <table id="dataTable" class="form" border="1"> <tbody> <tr> <p> <td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td> <td> <label>Folder Name</label> <input type="text" required="required" name="BX_NAME[]"> </td> <td> <label for="BX_fileseries">File Series</label> <select id="BX_fileseries required="required" name="BX_fileseries[]"> <option>100-01-Inspection and Survey/PII-NO</option> <option>200-02-Credit Card Purchases/PII-NO</option> <option>300-07-Time and Attendance/PII-YES</option> </td> <td> <label for="BX_classification">Classification</label> <select id="BX_classification" name="BX_classification" required="required"> <option>Unclassified</option> <option>Confidential</option> <option>Secret</option> <option>Top Secret</option> <option>Ridiculous Top Secret</option> <option>Ludicrous Top Secret</option> </select> </td> <td> <label for="BX_media">Media</label> <select id="BX_media" name="BX_media" required="required"> <option>Paper</option> <option>Shared Drive</option> <option>Film</option> <option>Floppy Disk</option> <option>Mixed</option> <option>Other</option> </select> </td> </p> </tr> </tbody> </table> <div class="clear"></div> </fieldset> <input class="submit" type="submit" value="File Plan Complete »" /> <div class="clear"></div> </form> </body> </html>PHP script with foreach loop to loop through the array from index.php and insert into database: InsertFileDetailArrayToDB.php /* When the user has finished entering their folders, reviewed the form inputs for accuracy and clicks the submit button, this will loop through all folder entries and using the SQL insert into query will place them in the database. When it completes data insertion it will redirect the user back to the file detail input form*/ <?php /*this part requires the user to be logged in and allows their user name to be included in the insert into query. If you remove the "ob_start();" piece it will screw up the header statement down at the botton. See the comments by the header statement for an explanation of its purpose*/ ob_start(); session_start(); if(!isset($_SESSION['myusername'])) { header('Location:index.php') } /*these two lines would ordinarily display the user name and a link a allowing the user to log out. However this php script does not output anything so the user will never it.*/ echo $_SESSION['myusername']; echo '<a href="logout.php"><span>Logout</span></a></li>'; ?> <?php /*this include statement connects this script to the MySQL database so the user form inputs can be inserted into the file_plan_details table*/ include ('database_connection.php'); foreach($_POST['BX_NAME'] as $row=>$BX_NAME) { $BX_NAME1 = mysql_real_escape_string($_POST['BX_NAME'); $officecode1 = mysql_real_escape_string($_POST['officecode'][$row]); $username1 = mysql_real_escape_string($_SESSION['myusername'][$row]); $day1 = mysql_real_escape_string($_POST['day'][$row]); $month1 = mysql_real_escape_string($_POST['month'][$row]); $year1 = mysql_real_escape_string($_POST['year'][$row]); $creator1 = mysql_real_escape_string($_POST['creator'][$row]); $officechief1 = mysql_real_escape_string($_POST['officechief'][$row]); $status1 = mysql_real_escape_string($_POST['status'][$row]); $BX_fileseries1 = mysql_real_escape_string($_POST['BX_fileseries'][$row]); $BX_classification1 = mysql_real_escape_string($_POST['BX_classification'][$row]); $BX_media1 = mysql_real_escape_string($_POST['BX_media'][$row]); $fileplandetailinsert1 = "INSERT INTO file_plan_details (folder_name, office_code, user_name, day, month, year, creator, office_chief, status, file_series, classification, media) VALUES ('$BX_NAME1','$officecode1','$username1','$day1','$month1','$year1','$creator1','$officechief1','$status1','$BX_fileseries1','$BX_classification1','$BX_media1')"; mysql_query($fileplandetailinsert1); } /*this header statement redirects the user back to the folder detail input form after it inserts data into the db After I build a main navigation page, I will switch out index.php with whatever I name the script that will produce the main navigation page*/ header('Location:index.php'); ?>script.js function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; if(rowCount < 10000){ // limit the user from creating fields more than your limits var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for(var i=0; i<colCount; i++) { var newcell = row.insertCell(i); newcell.innerHTML = table.rows[0].cells[i].innerHTML; } }else{ alert("Maximum Passenger per ticket is 5."); } } function deleteRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; for(var i=0; i<rowCount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childNodes[0]; if(null != chkbox && true == chkbox.checked) { if(rowCount <= 1) { // limit the user from removing all the fields alert("Cannot Remove all the Passenger."); break; } table.deleteRow(i); rowCount--; i--; } } } Edited by mac_gyver, 17 December 2014 - 01:13 PM. code tags around posted code please Hello all, What I'm trying to do is insert dynamic data supplied by the user into an array, but for some reason, the loop only builds arrays inside of arrays (or so it seems) and doesn't create an array with unique indexes and associated data. I was hoping someone could point me in the right path? I've searched numerous forums, threads and google but cannot find an answer. Here is the code snippet I'm working on. What it's supposed to do is collect a user's input, which is a Quantity amount and a high number, and based on that amount, create an array of random integers. This is my latest attempt. Now, maybe I'm just losing it, but when I place print_r($output) inside the loop, I see how it's being created but no unique indexes, just nested arrays. When I place it outside of the loop, I only receive one array with one index and value even though a high quantity was sent to the script. Code: [Select] $i = 1; while ($i <= $Quantity){ $output = array(rand($RandLow, $RandHigh)); $i++; } print_r($output); Here is another attempt, which again proved to be unsuccessful, at least to my tire brain. Code: [Select] $i = 1; while ($i <= $Quantity){ $output = rand($RandLow, $RandHigh); $total = array($output); $i++; } print_r($total); I've tried the for() loop as well but I just can't seem to make heads or tails of this and I'm sure it's going to be something simple that I'm missing. Thanks in advance for any help and insight if you know a better way to do this. 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
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'], ['','','','','',''] ]; 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 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. Hi guys..... I'm having a problem that I've been tearing my hair out over for way too long. I'm hoping that some of you may be able to help me or at least point me in the right direction. I'm using MySQL 5.0.91 (via PHPmyAdmin from GoDaddy). This query should basically grab the data from the Facebook API and insert it into the database. It's not doing that. After inserting the data, it queries the database, and redirects the user to their profile page (USERNAME.php). Because there is no data in the database for that user, it has no idea what their username is, so it redirects them to ".php"....yes, that is "[dot]php". I'm not entirely sure how to debug this either. I've tried a few var_dump()'s with not much luck. Is there a specific order in which this stuff needs to be in? Maybe that's the problem, so I'm also including a screenshot from PHPmyAdmin of the database table. Here's the code: // user not in db, insert details if(!empty($user)){ $apiGet = array( 'method' => 'users.getinfo', 'uids' => $uid, 'fields' => 'uid, name, first_name, last_name, pic_square, pic_big, sex, email, birthday_date, activities, interests, status, about_me' //theses are the fields it pulls from the Facebook API ); // create array to hold returned values $fbi = $facebook->api($apiGet); // insert details $iString = "oauth_provider, oauth_uid, username, name, first_name, last_name, sex, pic_big, email, joined, lastLogon, birthday_date, user_activities, user_interests, user_status, user_about_me"; $iArray = array(); //the following are the values of the fields array_push($iArray,'facebook'); array_push($iArray,$user['id']); array_push($iArray,$user['name']); array_push($iArray,$fbi[0]['name']); array_push($iArray,$fbi[0]['first_name']); array_push($iArray,$fbi[0]['last_name']); array_push($iArray,$fbi[0]['sex']); array_push($iArray,$fbi[0]['pic_big']); array_push($iArray,$fbi[0]['email']); array_push($iArray,time()); array_push($iArray,time()); array_push($iArray,$fbi[0]['birthday_date']); array_push($iArray,$fbi[0]['user_activities']); array_push($iArray,$fbi[0]['user_interests']); array_push($iArray,$fbi[0]['user_status']); array_push($iArray,$fbi[0]['user_about_me']); var_dump($email); $db->insert('users',$iArray,$iString); $where = "oauth_uid = '{$uid}'"; $db->select('*','users',$where); $result = $db->getResult(); // the next line creates a profile page. After that, there are lines that point the user to that page. createProfile($result['username']); I've added some comments to it to articulate what is going on. Thanks in advance! Alex Hi. Am trying to make an install script but have run into a problem. ---- variables.php - holds the variables that I need install.php - connects to the database and inserts all the values. Now I have a problem. When I execute the install.php it outputs: Creating tables... Connected to database server Database webleague is selected Players table Games table News table Rules table Games table Vars table Inserting default values Inserting news Inserting rules Inserting themes Inserting vars Done. but doesnt insert ANYTHING into the database. Can anyone help? Variables.php: <?php //start //configure database info $databaseserver = "localhost"; //usually localhost $databasename = "xxxxxxxxx"; //the name of your database $databaseuser = "xxxxxxxxx"; //the name of the database user $databasepass = "xxxxxxxxx"; // the password to your database $directory ="http://xxxxxxxxxxxxxxxxxx" ; //the location of your WebLeague directory (no trailing slash) //configure the tables in the database $playerstable = "webl_players"; //the name of the table that contains information about the players $gamestable = "webl_games"; //the name of the table that stores the played games $newstable = "webl_news"; // the name of the table that stores the news $themestable = "webl_themes"; //the name of the table that stores the themes $varstable = "webl_vars"; //the name of the table that stores various information $rulestable = "webl_rules"; //the name of the table the stores the rules //set some general information on your league $leaguename = "IRC League"; //the name of your league $title = ".: IRC League :."; //the title of your pages $favicon = "$directory/WebLeaguefavicon.ico" ; //the location of the shortcut icon $report = "winner"; //who reports? winner/loser $pointswin = "3"; //the number of points awarded for a win $pointsloss = "-1"; //the number of points awarded for a loss //set the username and password for the admin panel $LOGIN = "xxxxxxxxxx"; //the username to access the admin panel $PASSWORD = "xxxxxxxxx"; //the passoword to access the admin panel // finish ?> And this is install.php: Creating tables...<br><br> <?php include "variables.php"; $db = mysql_connect($databaseserver, $databaseuser, $databasepass) or die("Connection Failure to Database Server"); echo "Connected to database server<br>"; mysql_select_db($databasename, $db) or die ($databasename . " Database not found." . $databaseuser); echo "Database " . $databasename . " is selected<br><br>"; if ($db==false) die("Failed to connect to MySQL server<br>\n"); $sql = "CREATE TABLE $playerstable (player_id int(10) DEFAULT '0' NOT NULL auto_increment, name varchar(40) DEFAULT '' NOT NULL, passworddb varchar(10), mail varchar(50), icq varchar(15), aim varchar (40), country varchar(40), games int(10) DEFAULT '0', wins int(10) DEFAULT '0', losses int(10) DEFAULT '0', points int(10) DEFAULT '0', totalwins int(10) DEFAULT '0', totallosses int(10) DEFAULT '0', totalpoints int(10) DEFAULT '0', totalgames int(10) DEFAULT '0', penalties int(10) DEFAULT '0', staff varchar(10), streakwins int(10) DEFAULT '0', streaklosses int(10) DEFAULT '0', PRIMARY KEY (player_id))"; mysql_query($sql,$db); $sql = "ALTER TABLE $playerstable ADD UNIQUE(name) "; mysql_query($sql,$db); echo"Players table<br>"; $sql = "CREATE TABLE $gamestable (game_id int(10) DEFAULT '0' NOT NULL auto_increment, winner varchar(40), loser varchar(40), date varchar(40), PRIMARY KEY (game_id))"; mysql_query($sql,$db); echo"Games table<br>"; $sql = "CREATE TABLE $newstable (news_id int(10) DEFAULT '0' NOT NULL auto_increment, news text, PRIMARY KEY (news_id))"; mysql_query($sql,$db); echo"News table<br>"; $sql = "CREATE TABLE $rulestable (rules_id int(10) DEFAULT '0' NOT NULL auto_increment, rules text, PRIMARY KEY (rules_id))"; mysql_query($sql,$db); echo"Rules table<br>"; $sql = "CREATE TABLE $themestable (theme_id int(10) DEFAULT '0' NOT NULL auto_increment, name varchar(40), color1 varchar(40), color2 varchar(40), color3 varchar(40), color4 varchar(40), aimthemepic varchar(80), bottomleftpic varchar(80), bottommiddlepic varchar(80), bottomrightpic varchar(80), headerbgpic varchar(80), headermenuleftpic varchar(80), headermenurightpic varchar(80), sideleftpic varchar(80), siderightpic varchar(80), topleftpic varchar(80), topmiddlepic varchar(80), toprightpic varchar(80), PRIMARY KEY (theme_id))"; mysql_query($sql,$db); echo"Games table<br>"; $sql = "CREATE TABLE $varstable (vars_id int(10) DEFAULT '0' NOT NULL auto_increment, theme varchar(20), font varchar(80), fontcolor varchar(40), headerfont varchar(80), numgamespage int(10), numplayerspage int (10), statsview varchar(10), stats1view varchar(10), stats2view varchar(10), stats3view varchar(10), stats4view varchar(10), stats5view varchar(10), stats6view varchar(10), stats7view varchar(10), statsnum int(10), rulesview varchar(10), standingsnogames varchar(10), pctnum varchar(10), hotcoldnum varchar(10), gamesmaxday int(10), PRIMARY KEY (vars_id))"; mysql_query($sql,$db); echo"Vars table<br><br>"; echo"Inserting default values<br>"; $sql = "INSERT INTO $newstable (news) VALUES ('Welcome to WebLeague<br><br>WebLeague is an automated league system, that makes organizing an online league a piece of cake.<br><br>To put your own news here, go to the news section in your admin panel<br><br>Have fun using WebLeague')"; mysql_query($sql,$db); echo"Inserting news<br>"; $sql = "INSERT INTO $rulestable (rules) VALUES ('Insert your rules by going to the rules section in the admin panel')"; mysql_query($sql,$db); echo"Inserting rules<br>"; $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('blue','#0080FF','#000066', '#FFFFFF', '#000099', '/themes/blue/aim.jpg', '/themes/blue/bottomleft.jpg', '/themes/blue/bottommiddle.jpg', '/themes/blue/bottomright.jpg', '/themes/blue/headerbg.jpg', '/themes/blue/headermenuleft.jpg', '/themes/blue/headermenuright.jpg', '/themes/blue/sideleft.jpg', '/themes/blue/sideright.jpg', '/themes/blue/topleft.jpg', '/themes/blue/topmiddle.jpg', '/themes/blue/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('blue2','#66809A','#29293D', '#FFFFFF', '#444466', '/themes/blue2/aim.jpg', '/themes/blue2/bottomleft.jpg', '/themes/blue2/bottommiddle.jpg', '/themes/blue2/bottomright.jpg', '/themes/blue2/headerbg.jpg', '/themes/blue2/headermenuleft.jpg', '/themes/blue2/headermenuright.jpg', '/themes/blue2/sideleft.jpg', '/themes/blue2/sideright.jpg', '/themes/blue2/topleft.jpg', '/themes/blue2/topmiddle.jpg', '/themes/blue2/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('red','#FF0000','#660000', '#FFFFFF', '#990000', '/themes/red/aim.jpg', '/themes/red/bottomleft.jpg', '/themes/red/bottommiddle.jpg', '/themes/red/bottomright.jpg', '/themes/red/headerbg.jpg', '/themes/red/headermenuleft.jpg', '/themes/red/headermenuright.jpg', '/themes/red/sideleft.jpg', '/themes/red/sideright.jpg', '/themes/red/topleft.jpg', '/themes/red/topmiddle.jpg', '/themes/red/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('red2','#9A666C','#3D2929', '#FFFFFF', '#664444', '/themes/red2/aim.jpg', '/themes/red2/bottomleft.jpg', '/themes/red2/bottommiddle.jpg', '/themes/red2/bottomright.jpg', '/themes/red2/headerbg.jpg', '/themes/red2/headermenuleft.jpg', '/themes/red2/headermenuright.jpg', '/themes/red2/sideleft.jpg', '/themes/red2/sideright.jpg', '/themes/red2/topleft.jpg', '/themes/red2/topmiddle.jpg', '/themes/red2/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('green','#00FF00','#006600', '#FFFFFF', '#009900', '/themes/green/aim.jpg', '/themes/green/bottomleft.jpg', '/themes/green/bottommiddle.jpg', '/themes/green/bottomright.jpg', '/themes/green/headerbg.jpg', '/themes/green/headermenuleft.jpg', '/themes/green/headermenuright.jpg', '/themes/green/sideleft.jpg', '/themes/green/sideright.jpg', '/themes/green/topleft.jpg', '/themes/green/topmiddle.jpg', '/themes/green/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('green2','#6C9A66','#2D3D29', '#FFFFFF', '#446644', '/themes/green2/aim.jpg', '/themes/green2/bottomleft.jpg', '/themes/green2/bottommiddle.jpg', '/themes/green2/bottomright.jpg', '/themes/green2/headerbg.jpg', '/themes/green2/headermenuleft.jpg', '/themes/green2/headermenuright.jpg', '/themes/green2/sideleft.jpg', '/themes/green2/sideright.jpg', '/themes/green2/topleft.jpg', '/themes/green2/topmiddle.jpg', '/themes/green2/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('orange','#FF8000','#662200', '#FFFFFF', '#994000', '/themes/orange/aim.jpg', '/themes/orange/bottomleft.jpg', '/themes/orange/bottommiddle.jpg', '/themes/orange/bottomright.jpg', '/themes/orange/headerbg.jpg', '/themes/orange/headermenuleft.jpg', '/themes/orange/headermenuright.jpg', '/themes/orange/sideleft.jpg', '/themes/orange/sideright.jpg', '/themes/orange/topleft.jpg', '/themes/orange/topmiddle.jpg', '/themes/orange/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('orange2','#9A7E66','#3D3129', '#FFFFFF', '#664444', '/themes/orange2/aim.jpg', '/themes/orange2/bottomleft.jpg', '/themes/orange2/bottommiddle.jpg', '/themes/orange2/bottomright.jpg', '/themes/orange2/headerbg.jpg', '/themes/orange2/headermenuleft.jpg', '/themes/orange2/headermenuright.jpg', '/themes/orange2/sideleft.jpg', '/themes/orange2/sideright.jpg', '/themes/orange2/topleft.jpg', '/themes/orange2/topmiddle.jpg', '/themes/orange2/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('purple','#9900FF','#330066', '#FFFFFF', '#660099', '/themes/purple/aim.jpg', '/themes/purple/bottomleft.jpg', '/themes/purple/bottommiddle.jpg', '/themes/purple/bottomright.jpg', '/themes/purple/headerbg.jpg', '/themes/purple/headermenuleft.jpg', '/themes/purple/headermenuright.jpg', '/themes/purple/sideleft.jpg', '/themes/purple/sideright.jpg', '/themes/purple/topleft.jpg', '/themes/purple/topmiddle.jpg', '/themes/purple/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('purple2','#83669A','#32293D', '#FFFFFF', '#664466', '/themes/purple2/aim.jpg', '/themes/purple2/bottomleft.jpg', '/themes/purple2/bottommiddle.jpg', '/themes/purple2/bottomright.jpg', '/themes/purple2/headerbg.jpg', '/themes/purple2/headermenuleft.jpg', '/themes/purple2/headermenuright.jpg', '/themes/purple2/sideleft.jpg', '/themes/purple2/sideright.jpg', '/themes/purple2/topleft.jpg', '/themes/purple2/topmiddle.jpg', '/themes/purple2/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('black','#666666','#000000', '#FFFFFF', '#999999', '/themes/black/aim.jpg', '/themes/black/bottomleft.jpg', '/themes/black/bottommiddle.jpg', '/themes/black/bottomright.jpg', '/themes/black/headerbg.jpg', '/themes/black/headermenuleft.jpg', '/themes/black/headermenuright.jpg', '/themes/black/sideleft.jpg', '/themes/black/sideright.jpg', '/themes/black/topleft.jpg', '/themes/black/topmiddle.jpg', '/themes/black/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('yellow','#FFEF00','#635200', '#FFFFFF', '#999900', '/themes/yellow/aim.jpg', '/themes/yellow/bottomleft.jpg', '/themes/yellow/bottommiddle.jpg', '/themes/yellow/bottomright.jpg', '/themes/yellow/headerbg.jpg', '/themes/yellow/headermenuleft.jpg', '/themes/yellow/headermenuright.jpg', '/themes/yellow/sideleft.jpg', '/themes/yellow/sideright.jpg', '/themes/yellow/topleft.jpg', '/themes/yellow/topmiddle.jpg', '/themes/yellow/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('yellow2','#9A9666','#3D3A29', '#FFFFFF', '#666644', '/themes/yellow2/aim.jpg', '/themes/yellow2/bottomleft.jpg', '/themes/yellow2/bottommiddle.jpg', '/themes/yellow2/bottomright.jpg', '/themes/yellow2/headerbg.jpg', '/themes/yellow2/headermenuleft.jpg', '/themes/yellow2/headermenuright.jpg', '/themes/yellow2/sideleft.jpg', '/themes/yellow2/sideright.jpg', '/themes/yellow2/topleft.jpg', '/themes/yellow2/topmiddle.jpg', '/themes/yellow2/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('pink','#FF00EF','#660066', '#FFFFFF', '#990099', '/themes/pink/aim.jpg', '/themes/pink/bottomleft.jpg', '/themes/pink/bottommiddle.jpg', '/themes/pink/bottomright.jpg', '/themes/pink/headerbg.jpg', '/themes/pink/headermenuleft.jpg', '/themes/pink/headermenuright.jpg', '/themes/pink/sideleft.jpg', '/themes/pink/sideright.jpg', '/themes/pink/topleft.jpg', '/themes/pink/topmiddle.jpg', '/themes/pink/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('pink2','#9A6696','#3C293D', '#FFFFFF', '#664466', '/themes/pink2/aim.jpg', '/themes/pink2/bottomleft.jpg', '/themes/pink2/bottommiddle.jpg', '/themes/pink2/bottomright.jpg', '/themes/pink2/headerbg.jpg', '/themes/pink2/headermenuleft.jpg', '/themes/pink2/headermenuright.jpg', '/themes/pink2/sideleft.jpg', '/themes/pink2/sideright.jpg', '/themes/pink2/topleft.jpg', '/themes/pink2/topmiddle.jpg', '/themes/pink2/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('greenblue','#00FFEA','#006654', '#FFFFFF', '#009999', '/themes/greenblue/aim.jpg', '/themes/greenblue/bottomleft.jpg', '/themes/greenblue/bottommiddle.jpg', '/themes/greenblue/bottomright.jpg', '/themes/greenblue/headerbg.jpg', '/themes/greenblue/headermenuleft.jpg', '/themes/greenblue/headermenuright.jpg', '/themes/greenblue/sideleft.jpg', '/themes/greenblue/sideright.jpg', '/themes/greenblue/topleft.jpg', '/themes/greenblue/topmiddle.jpg', '/themes/greenblue/topright.jpg')"; mysql_query($sql,$db); $sql = "INSERT INTO $themestable (name, color1, color2, color3, color4, aimthemepic, bottomleftpic, bottommiddlepic, bottomrightpic, headerbgpic, headermenuleftpic, headermenurightpic, sideleftpic, siderightpic, topleftpic, topmiddlepic, toprightpic) VALUES ('greenblue2','#679B97','#293D39', '#FFFFFF', '#446666', '/themes/greenblue2/aim.jpg', '/themes/greenblue2/bottomleft.jpg', '/themes/greenblue2/bottommiddle.jpg', '/themes/greenblue2/bottomright.jpg', '/themes/greenblue2/headerbg.jpg', '/themes/greenblue2/headermenuleft.jpg', '/themes/greenblue2/headermenuright.jpg', '/themes/greenblue2/sideleft.jpg', '/themes/greenblue2/sideright.jpg', '/themes/greenblue2/topleft.jpg', '/themes/greenblue2/topmiddle.jpg', '/themes/greenblue2/topright.jpg')"; mysql_query($sql,$db); echo"Inserting themes<br>"; $sql = "INSERT INTO $varstable (theme, font, fontcolor, headerfont, numgamespage, numplayerspage, statsview, stats1view, stats2view, stats3view, stats4view, stats5view, stats6view, stats7view, statsnum, rulesview, standingsnogames, pctnum, hotcoldnum, gamesmaxday) VALUES ('blue','Arial', '#FFFFFF', 'Arial Black', '20', '30', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'yes', '10', 'yes', 'no', '10', '5', '2')"; mysql_query($sql,$db); echo"Inserting vars<br><br>"; echo"Done."; ?> Once again... it says its done when i execute the code in the browser but is not inserting anything into my database. Weird... if (($update_avatar1 == 'http://images.toxicpets.co.cc/vPets/Acara11.gif') OR ($update_avatar1 == 'http://images.toxicpets.co.cc/vPets/Aisha5.gif')) { mysql_query("UPDATE avatar SET avatar = '$update_avatar1' WHERE username = '$username' AND game = '$game'") or die ("Database error: ".mysql_error()); mysql_query("INSERT INTO avatar ($update_avatar1 WHERE id = '$userid')"); This is an avatar System But It Is Not Inserting Into The Database Hi guys, I am building a website with basic e-commerce functionality, using php and using xampp to test it. I am having issues when attempting to submit a quantity (into table orders) using a form and validating it against an existing value (from table products), giving a response on whether there is sufficient quantity in the second table. I am then, in another page (same one performing the validations), attempting to then show a result based on the initial quantity entered, with a summary of the order details and calculation of the quantity * price to display a total as well. This has all been built from scratch, however I may have taken the wrong approach for these two pages... any assistance or insight as to where I am going wrong would be greatly appreciated. Here is the page I have placed the products, existing quantity and a text field they are able to enter their desired quantity: Code: [Select] <?php session_start(); require_once "../database/db.php"; require_once "../includes/functions.php"; $page_title = 'Product Catalogue'; include_once "header.php"; $conn = mysqli_connect ($dbhost, $dbuser, $dbpassword, $dbname); $query = "SELECT * from products"; $result = mysqli_query($conn, $query); if (!$result) { include_once "header.php"; die ("Error, could not query the database"); } else { $rows = mysqli_num_rows($result); if ($rows>0) { while ($row = mysqli_fetch_array($result)) { ?> <form> <br /> <br /> <br /> <table> <tr> <td style="width: 200px">Product Code:</td> <td><?php echo $row['ProductCode']; ?></td> </tr> <tr> <td>Product Name:</td> <td><?php echo $row['ProductName']; ?></td> </tr> <tr> <td>Product Description:</td> <td><?php echo $row['ProductDescription']; ?></td> </tr> <tr> <td>Product Colour:</td> <td><?php echo $row['ProductColour']; ?></td> </tr> <tr> <td>Product Price:</td> <td>$<?php echo number_format($row['ProductPrice'],2); ?></td> </tr> <tr> <td>Product Image:</td> <td><img src="<?php echo $row['ProductImagePath']?>"/></td> </tr> <tr> <td>Quantity in Stock:</td> <td><?php echo $row['ProductQuantity']; ?></td> </tr> </table> </form> <form method="post"action="processQuantity.php"> <table> <tr> <td style="width: 200px">Quantity:</td> <td><input type="number" name="Quantity" id="Quantity" value="<?php if (isset ($quantity)) echo $quantity; ?>"size = "20" /></td> <td><input type="submit" name="Purchase" value= "Purchase" /></td> </tr> </table> </form> <hr /> <?php } include "footer.html"; } } ?> Here is the page that I am using to validate the data as well as show a result based on the entered amount: Code: [Select] <?php session_start(); require_once "../includes/functions.php"; require_once "../database/db.php"; $quantity = $_POST['Quantity']; $productquantity = $_POST['ProductQuantity']; $orderid = $_POST['orderid']; $productcode = $_POST['productcode']; $productprice = $_POST['productprice']; $total = $quantity * $productprice; $error_message = ''; if ($error_message != '') { include_once "displayCatalogue-PlaceOrder.php"; exit(); $conn = mysqli_connect ($dbhost, $dbuser, $dbpassword, $dbname); if (!$conn) { echo "Error"; } else { //sanitise date $scustomerid = sanitiseMySQL($customerid); $sproductcode = sanitiseMySQL($productcode); $squantity = sanitiseMySQL($quantity); $sproductprice = sanitiseMySQL($productprice); $sorderdate = sanitiseMySQL($orderdate); $query = "select productquantity from products where productcode = '$sproductcode'"; $result = msqli_query ($conn, $query); $productquantity = mysqli_num_rows($result); if ($quantity < $productquantity) { $error_message = "You cannot order more than what is currently instock"; include_once "displayCatalogue-PlaceOrder.php"; exit (); } else { $row = mysqli_fetch_row($result); $query = "INSERT into orders (customerid, productcode, quantity, productprice, orderdate) values ('$scustomerid', $sproductcode', '$squantity', '$sproductprice', '$sorderdate')"; $result = mysqli_query($conn, $query); $row = mysqli_affected_rows($conn); if ($row > 0) { include "header.php";?> <h3>Order Confirmation</h3> <p>Thank you, your order is now being processed.</p> <table> <tr> <td style="width: 200px">Order Number:</td> <td><?php echo $orderid; ?></td> </tr> <tr> <td>Product Code:</td> <td><?php echo $productcode; ?></td> </tr><tr> <td>Quantity:</td> <td><?php echo $quantity; ?></td> </tr> <tr> <td>Price:</td> <td><?php echo $productPrice; ?></td> </tr> <tr> <td>Total Cost of Order:</td> <td><?php echo $total; ?></td> </tr> </table> <?php include "footer.html"; } else { $error_message ="Error placing your order, please try again"; include "displayCatalogue-PlaceOrder.php"; exit(); } } } } //this is used to validate the quantity entered against what is available in the database ?> |