PHP - Storing An Array In A Mysql Database
I've got an array like this:
$firstquarter = array('January', 'February', 'March'); Then I'm adding it to a MySQL DB as follows: $insert = "INSERT INTO sometable (months) VALUES ('$firstquarter') "; $insertresult = mysql_query($insert) or die ('Error in Insert query: ' . mysql_error()); When I use PHPMyAdmin I see a this value stored in the DB: 'Array' Can I retrieve the values, by index, from this database field?? Similar TutorialsI am working on a kind of CMS for my own website which no one else will be using but me as a way of improving my php skills, and am having problems with retrieving data from the database that holds both text and php code. I have searched the web and found that i should be using eval() for the code to be executed before it is send to the browser but cannot get it to work and can't find my mistake(s). the php code will always be the same, and is supposed to retrieve the id number of a page to use in a link (and works fine when tested by loading the code directly without retrieving it from the database) this is an example of data stored in the database Code: [Select] The <a href="page_builder.php?id=<?php echo $page->id('mines_DwarvenMines') ?>">Dwarven Mines</a> have a great selection of Ores,... Of course when I leave it like this, hovering over the link in my page will show exactly that and lead to nowhere Code: [Select] localhost/page_builder.php?id=<?php echo $page->id('mines_DwarvenMines') ?> Most of these links appear in tips given at the end of the page and are processed as followed Code: [Select] $questtips = $quest->getQuestTips(); $tips = ""; if ($questtips == "none") { $tips = "/"; } else { foreach($questtips as $tip) { $tips .= "<li>"; $tips .= $tip->getTip(); $tips .= "</li>"; } } and finally put on screen by the presentation layer as followed Code: [Select] <h2>Tips & Extra Info</h2> <div class="tipsList"> <ul> <?php echo $tips ?> </ul> </div> I have tried all sorts to get the code to be executed when retrieved from the database before being send to the browser so that this particular link would say "localhost/page_builder.php?id=57" but I cannot get it to work, though I suspect it is fairly easy. I suspect I would have to store the data in a different format in the database? And how exactly do I use the eval() function in my case? Could someone please adjust my code so that it does work? Thanks Hello everyone,
I have a card database and everything works perfectly besides one thing..
I can't store
'in my database via my form, i however do can store them into the database via PHPMyAdmin. I dont know what i've been doing wrong and it really bothers me. If any of you guys could help me out. Here's all the code you would need to find the issue. This is the form file <!doctype html> <html> <head> <meta charset="utf-8"> <title>Edit Page</title> </head> <body> <h1 align="center"> Add Cards</h1> <form action="insert.php" method="POST"> <input type="text" name="name" placeholder="Name" /> <input type="text" name="color" placeholder="Color" /> <input type="text" name="type" placeholder="Type" /> <input type="text" name="subtype" placeholder="Sub Type" /> <input type="text" name="power" placeholder="Power" /> <input type="text" name="toughness" placeholder="Toughness" /> <br> <input type="text" name="manacost" placeholder="Converted Mana Cost" /> <input type="text" name="rarity" placeholder="Rarity" /> <input type="text" name="expansion" placeholder="Expansion" /> <input type="text" name="foil" placeholder="Foil" /> <input type="text" name="stock" placeholder="Stock" /> <input type="submit" value="Save" /> </form> </body> </html>This inserts it into my database. <?php ($GLOBALS["___mysqli_ston"] = mysqli_connect("", "", "", , ))or die("cannot connect"); ((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE e_industries"))or die("cannot select DB"); $name = $_POST['name']; $color = $_POST['color']; $type = $_POST['type']; $subtype = $_POST['subtype']; $power = $_POST['power']; $toughness = $_POST['toughness']; $manacost = $_POST['manacost']; $rarity = $_POST['rarity']; $expansion = $_POST['expansion']; $foil = $_POST['foil']; $stock = $_POST['stock']; $sql="INSERT INTO Osiris (Name, Color, Type, Subtype, Power, Toughness, Manacost, Rarity, Expansion, Foil, Stock) VALUES ('$name', '$color', '$type', '$subtype', '$power', '$toughness', '$manacost', '$rarity', '$expansion', '$foil', '$stock')"; $result=mysqli_query($GLOBALS["___mysqli_ston"], $sql); if($result){ echo "Successful"; echo "<BR>"; echo "<a href='add.html'>Back to main page</a>"; } else { echo "ERROR"; } ?>If anyone could help me out that would be great! Edited by OsirisElKeleni, 05 October 2014 - 12:29 PM. helllo dear php-commmunity new to Ruby - i need some advices - i plan to do some requests in osm-files. (openstreetmap) Question - how can i store the results on a Database - eg mysql or - (if you prefer postgresql) - note: my favorite db - at least at the moment is mysql here the code require 'open-uri' require "net/http" require 'rexml/document' def query_overpass(object_type, left,bottom,right,top, key, value) base_url = "http://www.overpass-api.de/api/xapi?" query_string = "#{object_type}[bbox=#{left},#{bottom},#{right},#{top}][#{key}=#{value}]" url = "#{base_url}#{URI.encode(query_string)}" resp = Net::HTTP.get_response(URI.parse(url)) data = resp.body return data end overpass_result = REXML::Document.new(query_overpass("node", 7.1,51.2,7.2,51.3,"amenity","restaurant|pub|ice_cream|food_court|fast_food|cafe|biergarten|bar|bakery|steak|pasta|pizza|sushi|asia|nightclub")) overpass_result.elements.each('osm/node') {|x| if !x.elements["tag[@k='name']"].nil? print x.elements["tag[@k='name']"].attributes["v"] end print " | " if !x.elements["tag[@k='addr:postcode']"].nil? print x.elements["tag[@k='addr:postcode']"].attributes["v"] print ", " end if !x.elements["tag[@k='addr:city']"].nil? print x.elements["tag[@k='addr:city']"].attributes["v"] print ", " end if !x.elements["tag[@k='addr:street']"].nil? print x.elements["tag[@k='addr:street']"].attributes["v"] print ", " end if !x.elements["tag[@k='addr:housenumber']"].nil? print x.elements["tag[@k='addr:housenumber']"].attributes["v"] end print " | " print x.attributes["lat"] print " | " print x.attributes["lon"] print " | " if !x.elements["tag[@k='website']"].nil? print x.elements["tag[@k='website']"].attributes["v"] end print " | " if !x.elements["tag[@k='amenity']"].nil? print x.elements["tag[@k='amenity']"].attributes["v"] print " | " end puts } look forward to hear from you again - i would love to store it on a mysql - database - if possible. If you would prefer postgresql - then i would takte this one.... ;-) look forward to hear from you again - i would love to store it on a mysql - database - if possible. If you would prefer postgresql - then i would takte this one.... ;-) well - i guess that the answer to this will be the same no matter what language we are using. If the db is a sql database we need to design the database schema and create the tables in the database. The first step in accessing a db in our code is to get a connection to it. If ruby is our choice of language, a search for "ruby sql connector" will give us lots of options to read about. Well - we also can do it in PHP. What do you think!? Next, based on the schema we have designed, we need to create queries suitable for storing the data. We will likely need to consider our transactional model. Again, searching "ruby sql transactional model" will give us plenty of food for thought. Finally, we may want or need to close the connection to the database. i have a dictionary - THIS IS obviously a python dictionary an this has approx 8 000 lines with records [/CODE] $ python printer.py {'url': 'http://www.site1_com' 'cname': 'butcher', 'name': 'cheng', 'email': 'mail1@hotmail.com'} {'url': 'http://www.site2_com' 'cname': 'dilbert', 'name': 'James', 'email': 'mail2@hotmail.com'} [code=auto:0]i have a mysql-db up and runing in my opensuse there i have created a db with the fields url cname name i use the import MySQLdb i studied this documentation he http://stackoverflow...abase-in-python but i think this goes a bit over my head. - well how can i get the data ( in other words the dictionary) into the database? love to hear from you greetings 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 guys so i have this add contacts page and the form is divided into 3 different froms 1) primary contact 2)spouse 3)child and the child form data is inserted as array into database because in the primary contact part of the form there is a "Children ?" with yes and no radio button and if yes a drop down list is enabled where if user chooses say 2 then there would be 2 child form that appears. and since theres 2 children then in the database a new row and data will be added accordingly.
image attached to be clearer.
from2.jpg 24.15KB
0 downloads
i got it inserted into database but in the specified field it says array: |child_name|dob|house_add1|mobile|office|email| inserted: |array|array-array-array|array|array|array|array| query: "INSERT INTO child VALUES('','".$childsalutations." $childfname $childlname',' ".$cday."-".$cmonth."-$cyear ','$childline1','$childline2','$childm','$childoff','$childemail')"in a stackoverflow question(not my own question) someone says: information stating arrays need to be split, before inserting into the table. does that mean something like this?: $cday = ($_POST['cday']); $cmonth = ($_POST['cmonth']); $cyear = ($_POST['cyear']); $childsalutations = ($_POST['child-salutations']); $childfname = ($_POST['child-fname']); $childlname = ($_POST['child-lname']); $childline1 = ($_POST['child-line1']); $childemail = ($_POST['child-email']); $childm = ($_POST['child-mobile']); $childoff = ($_POST['child-office']); $info = array('c_name' => $childsalutation $childfname $childlname, 'c_dob' => $cday-$cmonth-$cyear, 'c_line1' => $childline1, 'c_mobile' => $childm, 'c_office' => $childoff, 'c_email' => $childemail)just in case u wanted to c the html child form(warning its abit long,very!): <table class="prime"> <tbody> <br> <tr><td style="font-size:20px;font-weight:bold">Child <span id="number"></span></td></tr> <tr> <td>Salutation :</td> <td><select name="child-salutations[]" id="child-salutations"> <option value="" disabled selected>Salutations</option> <option value="Datin">Datin</option> <option value="Datin Paduka">Datin Paduka</option> <option value="Dato Paduka">Dato Paduka</option> <option value="Dato'">Dato'</option> <option value="Dato' Seri">Dato' Seri</option> <option value="Datuk">Datuk</option> <option value="Datuk Seri">Datuk Seri</option> <option value="Dr.">Dr.</option> <option value="Haji">Haji</option> <option value="Hajjah">Hajjah</option> <option value="HM">HM</option> <option value="HRH">HRH</option> <option value="Miss">Miss</option> <option value="Mrs.">Mrs.</option> <option value="Mr.">Mr.</option> <option value="Pehin">Pehin</option> <option value="Professor">Professor</option> <option value="Raja">Raja</option> <option value="Tan Sri">Tan Sri</option> <option value="Tengku">Tengku</option> <option value="Tuanku">Tuanku</option> <option value="Tun">Tun</option> <option value="Tunku">Tunku</option> <option value="Ungku">Ungku</option> </select> </td> </tr> <tr><td colspan="2"><label class="label" style="color:Red">*If a person has many salutations, choose the highest form of salutation</label></td></tr> <tr><td>First Name :</td><td><input type="text" name="child-fname[]" id="child-fname" class="style" /></td> <td>Last Name :</td><td><input type="text" name="child-lname[]" id="child-lname" class="style" /></td></tr> <tr> <td>Date of Birth : </td> <td> <select name="cday[]"> <option value=""selected disabled>Day</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="cmonth[]"> <option value="" selected disabled>Month</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> Year : <input type="text" name="cyear[]" maxlength="4" size="4" class="year"> </td> </tr> <tr><td>Where do they live ?</td><td colspan="3"><input type="radio" name="living[]" id="living-me" class="living-me"/>With Me<input type="radio" name="living[]" id="living-other" class="living-other"/>With Other Parent<input type="radio" name="living[]" id="living-own" class="living-own"/>Own</td></tr> <tr><td>House Address</td></tr> <tr><td>Line 1 :</td><td><input type="text" name="child-line1[]" id="child-line1" size="20" class="style" /></td> <td>Mobile No :</td><td><input type="text" name="child-mobile[]" id="child-mobile" class="style" /></td></tr> <tr><td>Office No :</td><td><input type="text" name="child-office[]" id="child-office" class="style" /></td> <td>Email Address : </td><td><input type="email" name="child-email[]" id="email" class="style" /></td></tr> </tbody> </table> Hello 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> Hey there... I'm so stuck on this problem I was hoping someone could help... I need to query a MySQL Database using array values... Here is my array ... $query_keywords = Array ( [7] => business [10] => home [11] => depo ) Here is my php ...$query = "SELECT * FROM product WHERE product_name, product_comment IN ($query_keywords)"; $result=mysql_query($query); if(mysql_num_rows($result) > 0) { echo "results"; } else { echo "no results"; } Unfortunately, I get this ... Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in blah\blah\results.php on line 99 Please help me All comments greatly appreciated... Hi All, First time posting here. I've googled the problem, but can't seem to find a response that's the same. All I want to do is have a list of id numbers and for each id number in the array, submit a MySQL query to retrieve information relating to the id number. When I execute the code below however, I end up with only the last item in the array being printed in the echo statement. Any clues? Thanks, Code: [Select] // get array of ids $ids = getIDs($ids); // loop through input list foreach ($ids as &$id) { getVarDetails($id); } function getVarDetails($local) { $con = mysql_connect('localhost:3306', 'root', '********'); if (!$con) { die('Could not connect: ' . mysql_error()); } // set database as Ensembl mysql_select_db("Ensembl", $con); $result = mysql_query("SELECT * FROM variations WHERE name = '$local' LIMIT 1"); $row = mysql_fetch_array($result) while($row = mysql_fetch_array($result)) { echo $row['name'] . " " . $row['id']; echo "<br />"; } // close connection mysql_close($con); } Quote i want to store a value from a database and use it as variable in php code can anyone help me out in this code i want to store value of copies in a php variable and want that it should be more than 0 (zero) for furthur calculations $update_book="update book set copies=copies-1 where bookid='$bookid'"; $result=mysql_query($update_book,$linkID1); if($result) { print "<html><body background=\"header.jpg\"> <p>book successfully subtracted from database</p></body></html>"; } else { print "<html><body background=\"header.jpg\"> <p>problem occured</p></body></html>"; } For some reason my for loop only seems to be storing some data in my fields, most of the time the data is not true but simply duplicating one of the entries. So instead of having a string of 1,2,3,4 for instance it would store all of them as 4. The entires are selected using fields in a multiple select box, in theory of someone choses 10 unique entries from the "Systems" category all 10 should be made into rows in the MySQL table. Any idea why this is happening? The form, if ($type == "games") { echo "<tr><td>".$name."</td><td><select name='".$name."_".$i."'[] multiple='multiple'><option value='' selected>--------</option>"; $sqla = mysql_query("SELECT * FROM ".$pre."games ORDER BY `name` ASC") or die(mysql_error()); while($row2a = mysql_fetch_array($sqla)) { $system = mysql_fetch_array(mysql_query("SELECT * FROM ".$pre."systems WHERE id = '".$row2a[system]."'")); echo "<option value='".$row2a[id]."'>".$row2a[name]." - ".$system[name]."</option>"; } echo "</select></td></tr>"; } if ($type == "system") { echo "<tr><td>".$name."</td><td><select name='".$name."_".$i."'[] multiple='multiple'><option value='' selected>--------</option>"; $sqlb = mysql_query("SELECT * FROM ".$pre."systems ORDER BY `name` ASC") or die(mysql_error()); while($row2b = mysql_fetch_array($sqlb)) { echo "<option value='".$row2b[id]."'>".$row2b[name]."</option>"; } echo "</select></td></tr>"; } The PHP code, while($row = mysql_fetch_array($query)) { $name = "$row[name]"; for ($i = 0; $i < count($_POST["systems_$i"]); $i++) { mysql_query("INSERT INTO ".$pre."fielddata VALUES (null, 'systems', '".$_POST["systems_$i"]."', '".$fetch[0]."', 'content')"); } for ($i = 0; $i < count($_POST["games_$i"]); $i++) { mysql_query("INSERT INTO ".$pre."fielddata VALUES (null, 'games', '".$_POST["games_$i"]."', '".$fetch[0]."', 'content')"); } Dear All, I am developing a like/dislike voting system for a scientific experiment in which the user will cast vote on a number of images. I have already written the code for it but the code is unable to store the data in the database. Kindly help me out in this issue. Below is my code for it: HTML Form for Like/Dislike Button: Code: [Select] <html> <head> <title> Like/Dislike buttons </title> </head> <body> <h1> Like/Dislike buttons </h1> <form name="form1" action="likedislike.php" method ="post"> <input type="submit" name="Like" value="Like"> <input type="submit" name="Dislike" value="dislike"> </form> </body> </html> PHP code for retrieving data and storing the vote in the database: Code: [Select] <?php session_start(); ob_start(); $host="localhost"; $username="computat_abhi"; $password="1123581321"; $databasename="computat_button"; $tbl_name="record"; $db=mysql_connect ("localhost","computat_abhi","1123581321")or die("cannot connect"); mysql_select_db($databasename,$db); if( isset($_POST['Like']) ) { $sql = 'INSERT INTO record(Image Number,Like Counter) VALUES ("b1.php",1)'; $result = mysql_query($sql); } elseif(isset($_POST['Dislike'])){ $sql = 'INSERT INTO record(Image Number,Dislike Counter) VALUES ("b1.php",1)'; $result = mysql_query($sql); } ob_end_flush(); ?> Thank you for your help. Okay I'm a newbie at PHP but was trying to write a counter for my website to count the amount of times a specific button is clicked. My desired outcome is as follows: If the form submit button "like" or "dislike" is clicked, get user's ip and check to see if it already exists in the database. If it exists, don't increment the count (of either button), otherwise log the ip and increment the count (of whichever button is clicked) by 1. Currently I've got the increment working (testing only the like button at the moment) and I've got the ip being stored into the database, but cannot get the comparison to work. Each time the button is clicked it adds the ip address into the database instead of disallowing it. Note: there are two different tables--one storing the ip (counter) and one storing the like clicks (Designs) (dunno if there's a better way?) Excuse my newbieness. The problem area: (like button only): if(isset($_POST['like'])) { $ip_address = $_SERVER['REMOTE_ADDR']; $query = mysql_query("SELECT ip FROM counter WHERE ip = '$ip_address'"); $num_rows = mysql_num_rows($query); if ($num_rows > 0) { die ("You've already clicked the button!"); } else { mysql_query("INSERT INTO counter VALUES ($ip_address)"); mysql_query("UPDATE Designs SET up = up + 1 WHERE ref = 'cataclysm'"); } } $select = mysql_query("SELECT up FROM Designs"); while($row = mysql_fetch_array($select)) { echo $row['up']; } I need some advice, I'm not sure if this is the right section to post this or not but I'll give it a try. I am creating a website for a small group of people to be able to message back and forth. I ran into a problem when doing the whole reply to a message option. I dont want to have each individual message as a new entry in my database, and then look for each message in that conversation when loading the conversation, I thought about inserting something like +=+=+=+=+=+= in between messages in the conversation so that when i pull up that conversation i could just separate the messages into an array by looking for that +=+=+=+=+=+= in the string of text and separating all the messages out. I want to know if anyone knows a better way of doing this or if this is a good way to go. thanks for any suggestions. Hi, wondering if somebody can tell me where I'm going wrong (I'm new to all of this). I have the following php code which uploads an image file into my database: Code: [Select] //Connect to database include 'Resources/Include/db.inc.php'; $tmp=$_FILES['image']['tmp_name']; //get users IP $ip=$_SERVER['REMOTE_ADDR']; //Don't do anything if file wasn't selected if (!empty($tmp)) { //Copy file to temporary folder copy($tmp, "./temporary/".$ip.""); //open the copied image, ready to encode into text to go into the database $filename1 = "./temporary/".$ip; $fp1 = fopen($filename1, "rb"); //record the image contents into a variable $contents1 = fread($fp1, filesize($filename1)); $contents1 = addslashes($contents1); //close the file fclose($fp1); $ftype = $_FILES['image']['type']; //insert information into the database if(!mysql_query("INSERT INTO LetterImages (Data,Type,LetterID,Page)"." VALUES ( '$contents1', '$ftype',1,1)")){ echo mysql_error(); } //delete the temporary file we made unlink($filename1); } This seems to work ok, as when I go to the LetterImages table there is now an additional row with a file in the blob field. I then have the following code which is supposed to display the image: Code: [Select] $result=mysql_query("SELECT * FROM LetterImages WHERE LetterID=1 AND Page=1"); //fetch data from database $sqldata=mysql_fetch_array($result); $encoded=stripslashes($sqldata['Data']); $ftype=$sqldata['Type']; //tell the browser what type of image to display header("Content-type: $ftype"); //decode and echo the image data echo $encoded; Instead of displaying an image, however, this just displays pages and pages of incomprehensible data. Can anybody tell me where I'm going horribly wrong? Hi I am using Zen-Cart to which I have made significant changes. Two years ago I managed to change the Products Sort Order from Integer to Decimal(5,2) to store books such as 1, 1.5, 1.75, 2 etc. Regrettably we had a major server issue and I also lost the new coding. Having restored everything else whenever we enter a book series number such as 1.5 it only stores as 1. To date the zen-Cart forums have been unable to offer a solution so I am reaching out to see if anyone else can advise me of how to get this working again please.
Thanks in advance Owen
Hi everyone,
I'm a complete newbie here. I've looked around for help and tried a few solutions without success, so because time is short I'm asking for help.
I have a registration form which includes address details. The form holds a country field which is a listbox, the values being selected from a MySQL table. How do I assign the selected country option to a field list in the insert statement?
Here's what I have so far:
Registration page form:
<div class="form-group"> Hi,
Webapp noob here.
I have an application that is going to be data-heavy, so I would like to avoid saving things to the database whenever possible. The application in a nutshell is an android application wired up to a php web app(with MySQL) where you can send requests to the phone and the phone will respond with text or image data with POST.
The normal way to do this would be for the phone to post the data to the database, then have the webapp display it. However, what im wondering is if it is possible for a user on the webapp to request information from the phone, and then when the phone replies using a POST to display the information temporarily in maybe a popup window instead of having to save it to the database.
Thanks!
|