PHP - Array Out Of A Database
Hi all,
This is a piece of code of my php page and what I need is that $n1 till $n4 is filled. Somehow only $n1 is filled. Can anyone tell me what I'm doing wrong here. Thnx Ryflex $sql = "SELECT name FROM unittype WHERE type = 1"; $result = mysql_fetch_array(mysql_query($sql)) or die("Could not find units"); $n1 = $result[0]; $n2 = $result[1]; $n3 = $result[2]; $n4 = $result[3]; echo "$n1 <BR> $n2 <BR> $n3 <BR> $n4"; Similar TutorialsHi I was just wondering would it be possible to create a database from a input statement and array, if so would it be also possible to create a table with fields the same way? I have a array for example: Code: [Select] $item = array( "Great <em>Bittern</em>"=>"Botaurus stellaris", "Little <em>Grebe</em>"=>"Tachybaptus ruficollis", "Black-necked Grebe"=>"Podiceps nigricollis"); which will output Code: [Select] Array ( [Great Bittern] => Botaurus stellaris [Little Grebe] => Tachybaptus ruficollis [Black-necked Grebe] => Podiceps nigricollis ) how can I input data from a database so it comes out as the array assuming I have $row[3] and $row[0] as the data? for example Code: [Select] while($row=mysql_fetch_array($result)){ //$item.=array($row[3],$row[0]); //array_push($item,array($row[3]=>$row[0])); //$item.=array($row[3]=>$row[0]); $item.="[".$row[3]."]=>".$row[0]; } which of course doesnt work?? Hi Guys I was just wondering if their is a function to randomize an array pulled from database is it possible i know their is array_rand() but it doesnt seem to work for me can someone show me where i am going wrong or do i have to do it from the actual SELECT statemant i.e ORDER_RAND(); ? Here is what my array prints out. $user_list = get_users_by_specialism($specialism); print_r($user_list); outputs. Array ( [0] => 129 [1] => 46 [2] => 57 [3] => 109 [4] => 92 [5] => 137 [6] => 238 [7] => 101 [8] => 60 [9] => 90 [10] => 112 [11] => 133 [12] => 121 [13] => 220 [14] => 275 [15] => 278 ) I basically need to make this array output in a random order everytime not by ID incrementing. Any help Please Cheers. I'm trying to figure out how to post an array into my database. I am able to post single entries without a problem, but trying to post several entries at once is causing me some headaches. Can anyone check this code and hopefully give me some insight as to where I'm going wrong? Here's the form: Code: [Select] <?php include("opendatabase.php"); ?> <FORM Method = "POST" action ="insert_spreads.php"> <?php $weekID = $_POST[Week]; echo "<h2>Enter Spreads for Week $weekID</h2>"; print ("<br /><br />"); $result = mysql_query(" SELECT S.game_id, TH.team_name AS HomeTeam, TA.team_name AS AwayTeam FROM schedule AS S JOIN teams AS TH ON S.H_team = TH.team_id JOIN teams AS TA ON S.A_team = TA.team_id WHERE S.week_id = '$weekID' ORDER BY S.game_id;"); while ($row = mysql_fetch_array($result)) { printf('<input type="text" size="4" name="w%dg%dAspread">', $weekID, $row['game_id']); printf(" %s vs. %s ", $row['AwayTeam'], $row['HomeTeam']); printf('<input type="text" size="4" name="w%dg%dHspread">', $weekID, $row['game_id']); print("<br /><br />"); } mysql_close($con); ?> <br /><br /> <input type="Submit" value="Submit Spreads"> </FORM> And here's the "insert_spreads.php Code: [Select] <?php header("Location: admin_main_entry.php"); include("opendatabase.php"); $aspread=$_POST['w%dg%dAspread']; $hspread=$_POST['w%dg%dHspread']; $row=$_POST[$row['game_id']; $sql=" UPDATE schedule SET A_pt_spread= '$aspread',H_pt_spread= '$hspread' WHERE week_id = '$weekID' AND game_id = '$row'"; $result = mysql_query($sql); mysql_close($con) ?> Thanks! Hi, I'm still new to php and having some problems. Sorry about the code not being formatted properly. The snippet I posted has both the code intend to work but it is commented out and a test version that has an array already set thus getting rid of the need of setting up every thing like I have. Ok this is basically my problem. I'm building a store like website. Its suppose to be very basic for now Part of the website is an RMA system where the customer enters an order number and then pulls up all items in the order on a different page in a table format with check boxes next to each item found in the database. Each item that is checked off is then saved to an array rma[] which posts to another page when submitted. What this page(copied down below) does is it pulls values from the cookie already made and creates new variables which is not a problem. After that it does a foreach loop for the array of the items into a mysql query which then is suppose to insert it into a database. When the code runs it only inserts the first item in the array into the database no matter how many items are in the array. When I echo the $insert statement I get this(using the test code) like I expect I'm suppose to. I would assume that because I'm doing a foreach loop that it is doing an INSERT for the number of items in the array. Quote INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('857442', '1','Saab','123') INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('857442', '1','Volvo','123') INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('857442', '1','BMW','123') INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('857442', '1','Toyota','123') Code: [Select] <?php //connects to the data base mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("project") or die(mysql_error()); /* //retrieving rma array from previous page $rmarequest = $_POST['rma']; //retieves using name from cookie $username = $_COOKIE['ID_my_site']; //retrieves order number from cookie $ordernumber = $_COOKIE['order']; //creates rma number $rmanumber = rand(1000, 999999); //retrieves accountid from database using the username $getid = mysql_query("SELECT AccountID FROM users WHERE username = '$username'"); $id = mysql_fetch_array( $getid ); //takes the value of $id $final = $id['AccountID']; //suppose to loop through all values for the array created by $request on the previous page and insert into database foreach($rmarequest as $key){ // $insert = "INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('".$rmanumber."', '".$AccountID."','".$key."','".$ordernumber."')"; //mysql_query($insert) OR die(mysql_error()); //this is test to see what is being passed to mysql server $insert = "INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('".$rmanumber."', '1','".$key."','123')"; //mysql_query($insert) OR die(mysql_error()); //to view what $insert is passing to the data base. echo $insert;} */ //THIS SECTION IS TEST ONLY //test array $cars[0]="Saab"; $rmarequest[1]="Volvo"; $rmarequest[2]="BMW"; $rmarequest[3]="Toyota"; //creates rma number $rmanumber = rand(1000, 999999); foreach($rmarequest as $key){ //this is test to see what is being passed to mysql server $insert = "INSERT INTO `project`.`rma` (rmanumber, AccountID, item, ordernumber) VALUES ('".$rmanumber."', '1','".$key."','123')"; mysql_query($insert) OR die(mysql_error()); //to view what $insert is passing to the data base. echo $insert."<br />"; } ?> Included is a copy of the table and the php code above. Hello all! I'm having a problem inserting an array into my database. My database is connected when I run the script but my table isn't being populated. Please help! Here's my table structure followed by the php: CREATE TABLE `demographic` ( `uid` bigint(20) unsigned NOT NULL, `first_name` varchar(50) default NULL, `last_name` varchar(50) default NULL, `email` varchar(200) default NULL, `link` varchar(255) default NULL, `affiliations` varchar(255) default NULL, `birthday` varchar(50) default NULL, `current_location` varchar(200) default NULL, `education_history` varchar(500) default NULL, `work` mediumtext, `hometown_location` varchar(400) default NULL, `interests` varchar(200) default NULL, `locale` varchar(50) default NULL, `movies` varchar(500) default NULL, `music` varchar(500) default NULL, `political` varchar(200) default NULL, `relationship_status` varchar(100) default NULL, `sex` varchar(10) default NULL, `tv` varchar(200) default NULL, `status` tinyint(4) default NULL, `created` datetime default NULL, `updated` datetime default NULL, PRIMARY KEY (`uid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; <?php $link = mysql_connect('host', 'user', 'pass'); if (!$link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db('database'); if (!$db_selected) { die ('Can\'t use beta : ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); include_once "fbmain.php"; $config['baseurl'] = "baseurl"; //if user is logged in and session is valid. if ($fbme){ //collect some data using legacy api $param = array( 'method' => 'users.getinfo', 'uids' => $fbme['id'], 'fields' => 'birthday_date, interests, locale, political, relationship_status, affiliations', 'callback' => '' ); try{ $info = $facebook->api($param); } catch(Exception $o){ error_log("Legacy Api Calling Error!"); } //using graph api //array data $workInfo = getWorkInfoAsString($fbme); $education = getEducationAsString($fbme); $moviesArr = $facebook->api("/me/movies"); $musicArr = $facebook->api("/me/music"); $televisionArr = $facebook->api("/me/television"); //format some api data $movies = getArrayDataAsString($moviesArr['data']); $music = getArrayDataAsString($musicArr['data']); $television = getArrayDataAsString($televisionArr['data']); //data from legacy api $networks = ''; if (!empty($info[0]['affiliations'])){ $flag = true; foreach ($info[0]['affiliations'] as $item){ if (!$flag) $networks.= ' # '; $networks .= $item['name']; $flag = false; } } $now = date("Y-m-d G:i:s"); $insData = array( 'uid' => $fbme['id'], 'first_name' => $fbme['first_name'], 'last_name' => $fbme['last_name'], 'email' => isset($fbme['email']) ? $fbme['email'] : '', 'link' => $fbme['link'], 'affiliations' => $networks, 'birthday' => $info[0]['birthday_date'], 'current_location' => isset($fbme['location']['name']) ? $fbme['location']['name'] : '', 'education_history' => $education, 'work' => $workInfo, 'hometown_location' => isset($fbme['hometown']['name']) ? $fbme['hometown']['name'] : '', 'interests' => $info[0]['interests'], 'locale' => $info[0]['locale'], 'movies' => $movies, 'music' => $music, 'political' => $info[0]['political'], 'relationship_status' => $info[0]['relationship_status'], 'sex' => isset($fbme['gender']) ? $fbme['gender'] : '', 'tv' => $television, 'status' => '0', 'created' => $now, 'updated' => $now, ); $this->db->insert('demographic', $insData); } function getWorkInfoAsString($fbme, $delim = '#', $partDelim = ' | '){ $info = ""; $flag = false; if (empty($fbme['work'])) return ''; foreach($fbme['work'] as $item){ if ($flag) $info .= $partDelim; $flag = true; $info .= (isset($item['employer']['name']) ? $item['employer']['name'] : '' ). $delim . (isset($item['location']['name']) ? $item['location']['name'] : '' ). $delim . (isset($item['position']) ? $item['position']['name'] : '' ). $delim . (isset($item['start_date']) ? $item['start_date'] : '' ). $delim . (isset($item['end_date']) ? $item['end_date'] : '' ); } return $info; } function getEducationAsString($fbme, $delim = '#', $partDelim = ' | '){ $info = ""; $flag = false; if (empty($fbme['education'])) return ''; foreach($fbme['education'] as $item){ if ($flag) $info .= $partDelim; $flag = true; $info .= (isset($item['school']['name']) ? $item['school']['name'] : '' ). $delim . (isset($item['year']['name']) ? $item['year']['name'] : ''); } return $info; } function getArrayDataAsString($data, $delim = '#', $partDelim = ' | '){ $info = ""; $flag = false; foreach($data as $item){ if ($flag) $info .= $partDelim; $flag = true; $info .= $item['name']; } return $info; } ?> Hello, I am developing a PayPal IPN interface which works fine, all is passed for verification and comes back 'VALID'. After validation with PayPal I update a users subscription and do the rest I want to do, but there is one thing really really irritating me. It seems to be that this one particular table in the database does not want to accept anything I throw at it through PHP. Here's the code: Code: [Select] $query = "INSERT INTO `ipn_txn_logs` ( `date` , `payment_reason` , `pp_txn_id` , `pp_amount` , `pp_txn_charge` , `pp_txn_net_amount` , `ltj_txn_id` , `description` , `failsafe` , `member` ) VALUES ( '$date', 'subscribe', '$txn[txn_id]', '$txn[payment_amount]', '$txn[payment_charges]', '$txn[net_payment]', '$txn[custom]', '$desc', 'yes', '$fname $lname')"; $query = mysql_query($query); The array is set on the IPN return using all values from PayPal. The database will insert when all variable and arrays are left out of the INSERT and replaced with just the number 1.. I am unable to see a PHP error as it's done in the background after a PayPal response... is there anyway to collect this error? Also, any suggestions on this fault? George.[/code] There is a "PHP ajax cascading dropdown using MySql" at codestips.com/php-ajax-cascading-dropdown-using-mysql/ I want to use this technique but with a XML or array file instead of mysql database, but my knowledge about mysql is very low. How I can modify this code to catch the categories and products from an array, instead of mysql database? Code: [Select] $connect=mysql_connect($server, $db_user, $db_pass) or die ("Mysql connecting error"); echo '<table align="center"><tr><td><center><form method="post" action="">Category:<select name="category" onChange="CategoryGrab('."'".'ajaxcalling.php?idCat='."'".'+this.value);">'; $result = mysql_db_query($database, "SELECT * FROM Categories"); $nr=0; while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $nr++; echo "<option value=".'"'.$row['ID'].'" >'.$row['Name']."</option>"; } echo '</select>'."\n"; echo '<div id="details">Details:<select name="details" width="100" >'; $result = mysql_db_query($database, "SELECT * FROM CategoriesDetails WHERE CategoryID=1"); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "<option value=".$row['ID'].">".$row['Name']."</option>"; } echo '</select></div>'; echo '</form></td></tr></table>'; mysql_close($connect); ajaxcalling.php is Code: [Select] include("config.php"); $ID=$_REQUEST['idCat']; $connect=mysql_connect($server, $db_user, $db_pass); echo 'Details:<select name="details" width="100">'; $result = mysql_db_query($database, "SELECT * FROM CategoriesDetails WHERE CategoryID=".$ID); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "<option value=".$row['ID'].">".$row['Name']."</option>"; } echo '</select>'; mysql_close($connect); Hi, I'm trying to store the first+lastname from my mysql user datababase into arrays like this: // Fill up array with names $a[]="Anna"; $a[]="Brittany"; $a[]="Cinderella"; $a[]="Diana"; $a[]="Eva"; $a[]="Fiona"; $a[]="Gunda"; $a[]="Hege"; $a[]="Inga"; $a[]="Johanna"; $a[]="Kitty"; $a[]="Linda"; $a[]="Nina"; $a[]="Ophelia"; $a[]="Petunia"; $a[]="Amanda"; $a[]="Raquel"; $a[]="Cindy"; $a[]="Doris"; $a[]="Eve"; $a[]="Evita"; $a[]="Sunniva"; $a[]="Tove"; $a[]="Unni"; $a[]="Violet"; I have a list of products in database and some have the same itemid but a different price depending on size What i want to do i if the itemid has more than one size, take the smallest price and then add the word "From" at the beginning. I've tried using the MIN() function but can't get it to do what i want. If there is only one size it works fine but if there is more than one it just says "From 0.00" Code: [Select] while ($row = $result->fetch()) { if(!isset($items[$row['itemid']])) { $items[$row['itemid']] = $row; } $items[$row['itemid']]['sizes'][$row['size']] = $row['price']; ### CHANGED ### } foreach($items AS $subitem) { list($prodid, $itemid, $item, $size, $description, $shortdesc, $image, $price) = $subitem; //Create field for item name based upon record count if(count($subitem['sizes']) > 1) { /*$item_name_field = "<ul>\n"; foreach($subitem['sizes'] as $size => $price) ### CHANGED ### {*/ //} //$item_name_field .= "<ul>\n"; $myprice = explode(".",number_format(min($subitem['price']),2)); $item_name_field .= "<li>From ".$myprice[0].".".$myprice[1]." {$size}</li>\n"; } else { $myprice = explode(".",number_format($subitem['price'],2)); $item_name_field .= "<li><span class=\"ucprice\">£".$myprice[0]."<?span><span class=\"lcprice\">.".$myprice[1]."</span></li>\n"; } I have made an autocomplete form... originally the values were static: $aUsers = array( "Adams, Egbert", "Altman, Alisha", "Archibald, Janna", ); Now I want the values from a database table DEVICES row name DeviceName: $sql = "SELECT DeviceName FROM DEVICES"; $res = mysql_query($sql); $aUsers = array(); while ($row = mysql_fetch_assoc($res)) { $aUsers[] = $row; } It will not display the values in my autocomplete form when text is entered.... but with static data it will. Im confused! Thank you 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 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> I have peice of code which is designed enter a question into a database and the username of the person who asks the question. However, the code enters <?php echo Array; ?> into the database and not 'Tom'. I am using the same code which inserts the category of the question in the database which works. But the username comes up as <?php echo Array; ?>. Does anyone know why it shows "array"? Code: [Select] if($loggedIn) { echo "Welcome, ".$user['username'].". <a href=\"logout.php\">Logout</a>. <table width='300' border='0' align='center' cellpadding='0' cellspacing='1'> <tr> <td><form name='form1' method='post' action='phpviewquestion.php'> <table width='100%' border='0' cellspacing='1' cellpadding='3'> <tr> <td colspan='3'><strong>Your Question</strong></td> </tr> <tr> <td width='71'>Question</td> <td width='6'>:</td> <td width='600' height='50'><input name='question' type='text' id='question'></td> <td width='71'>Notes</td> <td width='6'>:</td> <td width='600' height='50'><input name='notes' type='text' id='notes'></td> </tr> <tr> <td colspan='3' align='center'><input type='image' name='image' value='Submit' src='http://www.domain.co.uk/images/submitbutton.PNG' name='image' width='100' height='53'></td> <input name='category' type='hidden' value='Furniture' id='category' > <input name='questionmaker' type='hidden' value='<?php echo $username; ?>' id='questionmaker' > </tr> </table> </form> </td> </tr> </table> </div> " ; } else { echo "Please <a href=\"login.php\">Login</a>."; } ?> I am trying to create a website that after you receive an email you have to use the email address and password to confirm account. Then the next page allows you to change your password. I want to save the users email from the first page and use it in the SQL statement in the second page to locate the user in the DB and update the data. There must be some problem with the way I have my code logically set up. It will make it to the 2nd step but then it will go back to the main email confirmation page. <?php include('common.php'); include('db.php'); session_start(); session_register('umail'); session_register('password'); session_register('pwd1'); session_register('pwd2'); if(!isset($_POST['email']) && !isset($_POST['password'])) { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "BLOCKED URL"> <html> <head> This is a test of my patience</head> <meta http-equov="Content-Type" content="text/html; charset=iso-8859-1"/> </head> <body> <form method="post" action="<?=$_SERVER['PHP_SELF']?>"> Email: <input type="text" name="email" size="8" /> password:<input type="password" name="password" size="8" /> <input type ="submit" name ="submit" value ="submit" /> </form> </body> </html> <? exit; } else { $umail = $_SESSION['umail'] = $_POST['email']; $password = $_SESSION['password'] = $_POST['password']; dbConnect("web2"); $sql ="SELECT * FROM `user` WHERE email ='$umail'"; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); if(!$result) error('Contact DB admin'); if($result='') error('not in db'); if($_SESSION['umail'] != $row['email'] && $_SESSION['password'] != $row['password']) error('Wrong email or password'); } if(!isset($_POST['pwd1']) && !isset($_POST['pwd2'])) { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "BLOCKED URL"> <html> <head> This is a test of my patience</head> <meta http-equov="Content-Type" content="text/html; charset=iso-8859-1"/> </head> <body> <form method="post" action="<?=$_SERVER['PHP_SELF']?>"> password: <input type="text" name="pwd1" size="8" /> password confirmation:<input type="password" name="pwd2" size="8" /> <input type ="submit" name ="submit" value ="submit" /> </form> </body> </html> <? } else { $pwd1 = $_SESSION['pwd1'] = $_POST['pwd1']; $pwd2 = $_SESSION['pwd2'] = $_POST['pwd2']; if($_SESSiON['pwd1'] == $_SESSION['pwd2']) { dbConnect("web2"); mysql_query("UPDATE user SET password ='$pwd1' WHERE email ='$umail'"); $sql="SELECT * FROM 'user' WHERE email='$umail'"; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); if($_SESSION['pwd1'] != $row['password']) { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "(BLOCKED URl"> <html> <head> This is a test of my patience</head> <meta http-equov="Content-Type" content="text/html; charset=iso-8859-1"/> </head> <body> <form method="post" action="<?=$_SERVER['PHP_SELF']?>"> password: <input type="text" name="pwd1" size="8" /> password confirmation:<input type="password" name="pwd2" size="8" /> <input type ="submit" name ="submit" value ="submit" /> </form> </body> </html> <? } else { error(' the man'); session_unset(); session_destroy(); } } } ?> 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? How do I access objects inside an array of database results? I have a method that returns MySQL results as an array "$projects". Running print_r($projects) gives me this: array(1) ( "projects" => object Database_MySQL_Result(6) { protected _internal_row => integer 0 protected _query => string(875) "SELECT [skipping remainder of long query]" protected _result => resource(mysql result) protected _total_rows => integer 53 protected _current_row => integer 0 protected _as_object => string(13) "Model_Project" } ) If I do this: foreach($projects as $project) { echo $project->PROJECT_NAME; } I get "Undefined property: Database_MySQL_Result::$PROJECT_NAME" If I do this: foreach($projects as $project) { echo $project[0]; } the browser will display projects.id for the first returned row *only* echo $project[1] returns the project.id for the second row only. And so on. Each returned row contains over a dozen cells. It's almost as if I'm referring to the array incorrectly, or referring to the wrong array. I feel as though I'm making a very simple (and perhaps dumb) mistake here, but can't quite figure out what it is. Thanks. 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 every1 im driveing crazy with this... i have a database with a field with descriptions of products named "DESCRIP" in the main page i have a text field where user write the words to search for i wanrt make an "SELECT * FROM models where descrip like xxx OR descrip like xxx... bla bla bla" i wrote this code but send me an error... waht can be wrong??? $word='"SELECT * FROM models WHERE descrip LIKE ' ."'"; $srched=$_POST['words']; $pieces = explode(" ", $srched); $all=count($pieces)-1; for($i=0;$i<=$all;$i ++) { $word = $pieces[$i] ."'"; if($i!=$all) { $word .= $word . ' OR descrip like ' . "'"; } else { $word .= $word .'"' . ";"; } } $colname=$word; mysql_select_db($database_zero1, $zero1); $query_srch = $colname; $buscar = mysql_query($query_srch, $zero1) or die(mysql_error()); $row_srch = mysql_fetch_assoc($srch); $totalRows_srch = mysql_num_rows($srch); tnx in advcd 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? |