PHP - Newbie - Please Help With Create Db Code
I'm just starting out with mysqli and php. Actually I more or less know how to create/connect/populate mysqli databases through php. But I can only do so by using a separate php page for each objective. Anyway, I learning with the kindle version of Joy of Php. The code though isn't very good...I had to edit it just to make it conform to php/mysqli syntax. Programmer's Notebook was a big help actually.
Anyway, I just wanted to point out my experience level. Below is the code, I haven't run it through wamp (Phpmyadmi) yet, only because it probably won't run and I'll be crushed...side note: it took me a while to figure out that tables and databases require the use ` and not '. The book doesn't even mention the difference!!!!
Anyway, can someone tell me if this edited code is viable? I'm concerned about line 4: $mysqli.... since this is wamp, and I log into phpmyadmin via -u root -p , -p NULL in the code is correct yes?
<?php /*Joy of PHP sample code*/ $mysqli = new mysqli('localhost', 'root', NULL ); if (mysqli_connect_error()) { die('Could not connect: ' . mysqli_connect_error()); } echo 'Connected successfully to mySQL.'; /* Create table doesn't return a resultset */ if ($mysqli->query("CREATE DATABASE Cars") === TRUE) { echo "Database Cars created"; } else { echo "Error creating Cars database: " . $mysqli->error."<br>"; } $mysqli->select_db("Cars"); Echo ("Selected the Cars database"); $query= " CREATE TABLE INVENTORY (VIN varchar(17) PRIMARY KEY, YEAR INT, Make varch(50), Model varchar(100))"; //echo "<p>*****</p>"; //echo $query; //echo "<p>*****</p>"; if ($mysqli->query ($query) === TRUE) { echo "<p>Database table 'INVENTORY' CREATED</p>"; } else { echo "<p> ERROR: </p>" . mysqli_error($mysqli); } $query = "INSERT INTO `cars` . `inventory` (`VIN`, `YEAR`, `Make`, `Model`) VALUES '5FNYF4H91CB054036', '2012', 'Honda', Pilot')"; if ($mysqli->query($query) === TRUE) { echo "<p>Honda Pilot inserted into inventory table. </p>"; } else { echo "<p>Error inserting Honda Pilot:</p>" . mysqli_error($mysqli); echo "<p>*****</p>"; echo $query; echo "<p>*****</p>"; } //Insert a Dodge Durango $query= "INSERT INTO `cars` . `inventory` ('VIN', 'YEAR', 'Make', 'Model') VALUES ('LAKSDFJ234LASKRF2', '2009', 'Dodge', 'Durango')"; if ($mysqli->query($query) ===TRUE) { echo "<p>Dodge Durango inserted into inventory table </p>"; } else { echo "<p>Error inserting Dodge: </p>" . mysqli_error($mysqli); echo "<p>*****</p>"; echo $query; echo "<p>*****</p>"; } $mysqli->close(); ?>Thank you, I apologize if I seem critical of the book but it really skips over A LOT of stuff that newbies don't necessarily know (example: -u something -p = username something and password is blank) Edited by baltar, 17 May 2014 - 05:59 PM. Similar TutorialsHi Guys I have some code, written by somebody else, which i think updates a 'comments' table when a comment is written on my home page... Code: [Select] <?php include("db.php"); if(isSet($_POST['comentario_valor'])){ $id=time();// Demo Use $comment=$_POST['comentario_valor']; $id=$_POST['id']; $sql=mysql_query("insert into comments(comment,msg_id_fk)values('$comment','$id')"); $result=mysql_query("select * from comments order by com_id desc"); $row=mysql_fetch_array($result); $com_id=$row['com_id']; $comment=$row['comment']; } ?> What i need to do now tho is try to ammend this script to also update the table with the 'userid' of the person who posted the comment. The userid should be the same as in my 'users' table. Can anybody point me in the right direction? I am new to PHP and trying to decipher this peice is code is beyond me at the minute Many thanks I am a complete newbie. I have installed xampp. I created a database and the tables but that is all. I need to create all my relationships and test my database. to do this, do I now need to write the php code to view the results in a browser or... do I do it in MySQL. If so, Can someone just point me in the direction I need to go for my next step.
Thanks
Hello,
I would like to create a window through JavaScript with PHP code that would insert data into a database, but I don't know if it's possible, because I tried everything I could so far and had no results at all.
The code I am using is
<script language="JavaScript"> <!-- top.consoleRef = new Object(); top.consoleRef.closed = true; function writeConsole(content) { top.consoleRef=window.open('em_branco.php','myconsole','width=350,height=250') top.consoleRef.document.writeln( '<html><head><title>página nova</title></head><body><?php $db = pg_connect("host=localhost dbname=dpf_db user=postgres password=asdasd"); $query = "INSERT INTO tbl_dummy(nome) VALUES(' + '´treco´' + ')"; $result = pg_query($query); if (!$result) { $errormessage = pg_last_error(); echo "Error with query: " . $errormessage; exit(); } printf ("These values were inserted into the database"); pg_close(); ?></body></html>' ) //top.consoleRef.document.close() } //--> </script>Note that line 13 has a sort of aberration, because I'd need three kinds of quotes, and not only two (the +'´treco´' stuff). And I don't know how to circumvent this, because escaping didn't work either. Any help is most welcome, and thank you in advance for your attention. Nicole Hey php developers. I'm Brent from Beanstream. We just recently opened up some code bounties to create a PHP SDK that uses our payment gateway API. Each bounty is around 1-5 hours work and their reward is between $150 and $400. The SDK is open source (MIT license) and will be hosted on GitHub. There are already 2 other SDKs written in Java and C# that use the same RESTful payments API, so a lot of the code and functionality can be copied over to the PHP SDK. If you are interested in helping out you can sign up here. You can also check out Beanstream's Payments API to see what the SDK will be implementing: http://developer.beanstream.com Feel free to message me if you have questions. Cheers, Brent Beanstream Internet Commerce Rules: 1) It has to be legit and actually work and have a useful function in society/web world. 2) The code cannot be minimized into one line. It has to have line breaks. (Not necessarily for each new function or short hand property, but so it's partly readable) 3) It has to be written in PHP or Javascript. For example, (Not my original code) but I'll start: A time_ago function: function timeago($tm,$rcs = 0) { $cur_tm = time(); $dif = $cur_tm-$tm; $pds = array('second','minute','hour','day','week','month','year','decade'); $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600); for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]); $no = floor($no); if($no <> 1) $pds[$v] .='s'; $x = sprintf("%d %s ",$no,$pds[$v]); if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm); return $x; }Your turn! Edited by Monkuar, 24 January 2015 - 05:06 PM. Hello, I am novice in PHP, I read book and try to write some PHP code, but I don't have success in that my attempt. Do someone can to help me? I think that this what I work isn't hard, but I don't know to do. I need to create in PHP some code which will: 1. In text field I enter some words in 2-3 rows, example word11 word12 word13 word21 word22 word23 word31 word32 word33 and click to button Convert, 2. After click on that button php script will take that words and convert into this mode: word11-word12-word13(TAB here without space)word11 word12 word23 word21-word22-word23(TAB here without space)word21 word22 word23 word31-word32-word33(TAB here without space)word31 word32 word33 (spaces between words will convert into - and between first and second mode with TAB) 3. On that way converted text to be saved into new file which will be with name of first line "word11 word12 word13". I know procedure to make this, but I don't know syntax very well Can someone write me code or part of code, to give me idea how I to make this? Thank you very much, Mladen Hello everyone, I am working on a form that is similar to a shopping cart system and I am thinking of creating a button that submits the checked value and saves them to a $_SESSION variable. And also a link that links to a cart.html that takes the values of a $_SESSION variable. I am have trouble figuring what tag/attribute should I use in order to achieve that.
Right now my code attached below submits the checked values to cart.html directly. However I want my submit button to save the checked box to a $_SESSION variable and STAY on the same page. And then I will implement a <a> to link to the cart.php.
I researched a little bit about this subject and I know it's somewhat related to ajax/jquery. I just wanted to know more about it from you guys. I appreciate your attention for reading the post and Thanks!
Below is the form that I currently have:
<form name= "finalForm" method="POST" action="cart.php"> <input type="Submit" name="finalSelected"/> <?php foreach($FinalName as $key => $item) {?> <tr> <td><input type="checkbox" name="fSelected[]" value="<?php echo htmlspecialchars($FinalID[$key])?>" /> <?php echo "$FinalID[$key] & $item";?> </td> </tr> <?php } ;?>Below is the code for cart.php <?php require ('connect_db.php'); if(isset($_POST['finalSelected'])) { if(!empty($_POST['fSelected'])) { $chosen = $_POST['fSelected']; foreach ($chosen as $item) echo "aID selected: $item </br>"; $delimit = implode(", ", $chosen); print_r($delimit); } } if(isset($delimit)) { $cartSQL = "SELECT * from article where aID in ($delimit)"; $cartQuery = mysqli_query($dbc, $cartSQL) or die (mysqli_error($dbc)); while($row = mysqli_fetch_array($cartQuery, MYSQLI_BOTH)) { $aTitle[] = $row[ 'name' ]; } } ?> <table> <?php if(isset($delimit)) { $c=0; foreach($aTitle as $item) {?> <tr> <td> <?php echo $aTitle[$c]; $c++;?> </td> </tr> <?php }}?> </table> I have got some xml which I have ran $xml = simplexml_load_string($result); Now I need to be able to access the values in a for loop, I've done this before, but it escapes me. The XML code is as follows... <?xml version="1.0" encoding="iso-8859-1" standalone="yes"?> <branches xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:noNamespaceSchemaLocation="http://webservices.vebra.com/export/xsd/v1/exportapi.xsd"> <branch> <name>Swindon</name> <firmid>11548</firmid> <branchid>1</branchid> <url>http://webservices.vebra.com/export/primaryexechomesAPI/v1/branch/3762</url> </branch> <branch> <name>Swindon</name> <firmid>17548</firmid> <branchid>11</branchid> <url>http://webservices.vebra.com/export/primaryexechomesAPI/v1/branch/10061</url> </branch> </branches> My code for trying to get the values when in a for loop is... # format xml and insert the different branches into the db $xml = simplexml_load_string($result); # loop through the number of branches //$branches = count($xml); for($b = 0; $b < count($xml); $b++) { //$name = $xml->name; //$name = $xml->['name']; //$name = $xml['name']; //$name = $xml['branch']; //$name = $xml->['branch']['name']; //$name = $xml[$b]->['branch']['name']; $name = $xml->['branch']['name']; print "<h1>Name</h1>"; } As you can see I've tried to get the value out, just cant seem to do it. Any help will be much appreciated! Hi all, I am completing an assignment for Uni and I have run it to a bit of difficulty. I hope someone can help me out. I am deleting a record from the database and I want it to then display the student record number, firstname and surname. I know it is probably something simple but I can see where I am going wrong! <?php $id=$_REQUEST['id']; $firstname=$_GET['firstname']; $surname=$_GET['surname']; $db="prs"; $link=mysql_connect("localhost","gandalf","bella") or die("Cannot Connect to the database!"); mysql_select_db($db,$link) or die ("Cannot select the database!"); $query="DELETE FROM students WHERE upn='".$id."'"; if(!mysql_query($query,$link)) {die ("An unexpected error occured while <b>deleting</b> the record, Please try again!");} else { echo "Student with Student Number #".$id." ".$firstname." ".$surname." removed successfully!";} ?>() Thanks in advance for any and all help, it is much appreciated. Cheers, Fergal I have the following xml file... <property id="21179035" propertyid="111290" system="A" firmid="11548" branchid="1" database="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:noNamespaceSchemaLocation="http://webservices.vebra.com/export/xsd/v1/exportapi.xsd"> <reference> <agents>11290</agents> </reference> <address> <name>16</name> <street>Bardsey Close</street> <locality>Wootton Bassett</locality> <town>Swindon</town> <county>Wilts</county> <postcode>SN4 8NA</postcode> <custom_location>West of Swindon</custom_location> <display>Wootton Bassett, Swindon</display> </address> <price qualifier="" currency="GBP">107750</price> <rm_qualifier>0</rm_qualifier> <available>01/01/1900</available> <uploaded>04/08/2010</uploaded> <longitude>-1.886723</longitude> <latitude>51.54373</latitude> <easting>407855</easting> <northing>182820</northing> <web_status>1</web_status> <custom_status /> <comm_rent /> <premium /> <service_charge /> <rateable_value /> <type>Maisonette</type> <type /> <furnished>3</furnished> <rm_type>0</rm_type> <let_bond>0</let_bond> <rm_let_type_id>0</rm_let_type_id> <bedrooms>2</bedrooms> <receptions>0</receptions> <bathrooms>1</bathrooms> <userfield1 /> <userfield2>0</userfield2> <area measure="metric" unit="sqm"> <min>0</min> <max>0</max> </area> <area measure="imperial" unit="sqft"> <min>0</min> <max>0</max> </area> <description>Primary are pleased to offer this two bedroom first floor maisonette in Wootton Bassett. The accommodation comprises of private entrance hall, lounge, kitchen, two bedrooms and bathroom. The property also benefits from uPVC double glazing, central heating and two allocated parking spaces. No onward chain. </description> <hip> <energy_performance> <energy_efficiency> <current>67</current> <potential>77</potential> </energy_efficiency> <environmental_impact> <current>67</current> <potential>80</potential> </environmental_impact> </energy_performance> </hip> <paragraphs> <paragraph id="1" type="0"> <name>DESCRIPTION</name> <file /> <dimensions> <metric /> <imperial /> <mixed /> </dimensions> <text>Primary are pleased to offer this two bedroom first floor maisonette in Wootton Bassett. The accommodation comprises of private entrance hall, lounge, kitchen, two bedrooms and bathroom. The property also benefits from uPVC double glazing, central heating and two allocated parking spaces. No onward chain. </text> </paragraph> <paragraph id="2" type="0"> <name>PRIVATE ENTRANCE PORCH</name> <file /> <dimensions> <metric /> <imperial /> <mixed /> </dimensions> <text>Storage cupboard.</text> </paragraph> <paragraph id="3" type="0"> <name>PRIVATE ENTRANCE HALL</name> <file /> <dimensions> <metric /> <imperial /> <mixed /> </dimensions> <text>Stairs leading to first floor. Radiator.</text> </paragraph> <paragraph id="4" type="0"> <name>FIRST FLOOR</name> <file /> <dimensions> <metric /> <imperial /> <mixed /> </dimensions> <text>Landing: Loft access (part boarded), built in storage cupboard with hanging rail, airing cupboard. Doors leading to lounge, bathroom and both bedrooms.</text> </paragraph> <paragraph id="5" type="0"> <name>LIVING ROOM</name> <file ref="1" /> <dimensions> <metric /> <imperial /> <mixed>5.05m(16'7'') x 3.43m(11'3'')</mixed> </dimensions> <text>uPVC double glazed window to front elevation. TV point. Telephone point. Radiator. Door leading to:</text> </paragraph> <paragraph id="6" type="0"> <name>KITCHEN</name> <file ref="2" /> <dimensions> <metric /> <imperial /> <mixed>2.57m(8'5'') x 2.54m(8'4'')</mixed> </dimensions> <text>uPVC double glzed window to rear elevation. Wall and base units with rolled edge work surfaces over. Wall mounted central heating boiler and thermostat. Space for fridge freezer, oven and washer drier. Tiled splashbacks.</text> </paragraph> <paragraph id="7" type="0"> <name>BEDROOM ONE</name> <file ref="3" /> <dimensions> <metric /> <imperial /> <mixed>3.76m(12'4'') x 3.05m(10'0'')</mixed> </dimensions> <text>uPVC double glazed window to front elevation. Built in double wardrobe. Telephone extension. Radiator.</text> </paragraph> <paragraph id="8" type="0"> <name>BEDROOM TWO</name> <file /> <dimensions> <metric /> <imperial /> <mixed>3.71m(12'2'') x 2.26m(7'5'')</mixed> </dimensions> <text>uPVC double glazed window to rear elevation. Radiator.</text> </paragraph> <paragraph id="9" type="0"> <name>BATHROOM</name> <file /> <dimensions> <metric /> <imperial /> <mixed /> </dimensions> <text>Obscure uPVC double glazed window to rear elevation. White suite comprising of panel bath with shower over, pedestal hand wash basin and low level WC. Radiator.</text> </paragraph> <paragraph id="10" type="0"> <name>VIEWING</name> <file /> <dimensions> <metric /> <imperial /> <mixed /> </dimensions> <text>Strictly via our Swindon office telephone (01793) 641641, out of office hours Dawn Graham 07887763163.</text> </paragraph> <paragraph id="11" type="0"> <name>MORTGAGES</name> <file /> <dimensions> <metric /> <imperial /> <mixed /> </dimensions> <text>If you would like independent mortgage advice please call Primary Mortgage Centre on (01793) 616617. Home visits available.</text> </paragraph> <paragraph id="12" type="0"> <name>MONEY LAUNDERING</name> <file /> <dimensions> <metric /> <imperial /> <mixed /> </dimensions> <text>Intending purchasers will be asked to produce identification documentation at a later stage and we would ask for your co-operation in order that there will be no delay in agreeing the sale.</text> </paragraph> <paragraph id="13" type="2"> <name /> <file /> <dimensions> <metric /> <imperial /> <mixed /> </dimensions> <text>This footer paragraph is an example only and should not be relied upon as complying with current legislation. These particulars, whilst believed to be accurate are set out as a general outline only for guidance and do not constitute any part of an offer or contract. Intending purchasers should not rely on them as statements of representation of fact, but must satisfy themselves by inspection or otherwise as to their accuracy. No person in this firms employment has the authority to make or give any representation or warranty in respect of the property.<br/></text> </paragraph> </paragraphs> <bullets> <bullet id="1">First Floor Maisonette</bullet> <bullet id="2">Two Bedrooms</bullet> <bullet id="3">Lounge</bullet> <bullet id="4">Kitchen</bullet> <bullet id="5">Private Entrance</bullet> <bullet id="6">Allocated Parking</bullet> <bullet id="7">Good Location</bullet> <bullet id="8">No Onward Chain</bullet> </bullets> <files> <file id="0" type="0"> <name /> <url>http://images.vebra.com/images/1548/001/type1/bardse~1.jpg</url> <updated>30/08/2011 17:03:00</updated> </file> <file id="1" type="0"> <name>LIVING ROOM</name> <url>http://images.vebra.com/images/1548/001/type1/bardse~2.jpg</url> <updated>30/08/2011 17:03:00</updated> </file> <file id="2" type="0"> <name>KITCHEN</name> <url>http://images.vebra.com/images/1548/001/type1/bardse~3.jpg</url> <updated>30/08/2011 17:03:00</updated> </file> <file id="3" type="0"> <name>BEDROOM ONE</name> <url>http://images.vebra.com/images/1548/001/type1/bardse~4.jpg</url> <updated>30/08/2011 17:03:00</updated> </file> <file id="4" type="9"> <name>Energy efficiency chart</name> <url>http://images.vebra.com/home/hip/EE_0275_067_077.png</url> </file> <file id="5" type="9"> <name>Environmental impact chart</name> <url>http://images.vebra.com/home/hip/EI_0275_067_080.png</url> </file> </files> </property> I have the following code... # address - basic info if(is_object($xml->address)) { foreach($xml->address as $address) { //print_r($property); $name = $address->name; $street = $address->street; $locality = $address->locality; $town = $address->town; $county = $address->county; $postcode = $address->postcode; $custom_location = $address->custom_location; $display = $address->display; $insertS = "INSERT INTO $tablec (pal, afield, bfield, cfield, dfield, efield, ffield, hfield, ifield, jfield) VALUES (110, '$bD->afield', '$name', '$street', '$locality', '$town', '$county', '$postcode', '$custom_location', '$display')"; $insertQ = mysql_query($insertS); $iid = mysql_insert_id(); } } # property - basic info if(is_object($xml)) { foreach($xml as $property) { //print_r($property); $long = $property->longitude; $lat = $property->latitude; $type = $property->type; $furnished = $property->furnished; $bedrooms = $property->bedrooms; $bathrooms = $property->bathrooms; $description = $property->description; $updateS = "UPDATE $tablec SET kfield = '$long', lfield = '$lat', mfield = '$type', nfield = '$furnished', ofield = '$bedrooms', pfield = '$bathrooms', atext = '$description' WHERE pal = 110 AND id = $iid"; $updateQ = mysql_query($updateS); print "<p>$updateS</p>"; } } The first bit is working fine (# address - basic info) and I am able to get the information out, however the longitude and latitude bit I'm struggling with (# property - basic info) Any help would be much appreciated. I need the following XML code http://primarymortgages.co.uk/dev/property-xml-donotdelete.xml to be entered into the database, while I have done the first bit... <code> # address - basic info if(is_object($xml->address)) { foreach($xml->address as $address) { $name = $address->name; $street = $address->street; $locality = $address->locality; $town = $address->town; $county = $address->county; $postcode = $address->postcode; $custom_location = $address->custom_location; $display = $address->display; $insertS = "INSERT INTO $tablec (pal, afield, bfield, cfield, dfield, efield, ffield, hfield, ifield, jfield) VALUES (110, '$bD->afield', '$name', '$street', '$locality', '$town', '$county', '$postcode', '$custom_location', '$display')"; $insertQ = mysql_query($insertS); $iid = mysql_insert_id(); } } # property - basic info if(is_object($xml)) { $long = $xml->longitude; $lat = $xml->latitude; $type = $xml->type; $furnished = $xml->furnished; $bedrooms = $xml->bedrooms; $bathrooms = $xml->bathrooms; $description = $xml->description; $updateS = "UPDATE $tablec SET kfield = '$long', lfield = '$lat', mfield = '$type', nfield = '$furnished', ofield = '$bedrooms', pfield = '$bathrooms', atext = '$description' WHERE pal = 110 AND id = $iid"; $updateQ = mysql_query($updateS); } </code> I need to be able to get the paragraphs... <paragraph id="1" type="0"> <name>DESCRIPTION</name> <file /><dimensions> <metric /> <imperial /> <mixed /> </dimensions> <text>Primary are pleased to offer this two bedroom first floor maisonette in Wootton Bassett. The accommodation comprises of private entrance hall, lounge, kitchen, two bedrooms and bathroom. The property also benefits from uPVC double glazing, central heating and two allocated parking spaces. No onward chain.</text> </paragraph> <paragraph id="2" type="0"> <name>PRIVATE ENTRANCE PORCH</name> <file /> <dimensions> <metric /> <imperial /> <mixed /> </dimensions> <text>Storage cupboard.</text> </paragraph> <paragraph id="3" type="0"> <name>PRIVATE ENTRANCE HALL</name> <file /> <dimensions> <metric /> <imperial /> <mixed /> </dimensions> <text>Stairs leading to first floor. Radiator.</text> </paragraph> etc, etc... However the following code isn't working for me... <code> # paragraphs print_r ($xml->paragraph); foreach($xml->paragraph as $paragraph) { $thetitle = $paragraph->title; $thetext = $paragraph->text; $insertS = "INSERT INTO $tablec (pal, afield, bfield, atext) VALUES (111, '$iid', '$thetitle', '$thetext')"; $insertQ = mysql_query($insertS); print "<p>$insertS</p>"; } </code> Can someone adjust the # paragraphs code for me so it can work Many Thanks. Hi guys - i have some code which echos an image from a directory based on the user who is logged in... Code: [Select] <?php //to display image from source $dir = "profpics"; $sql = "SELECT prof_pic FROM users WHERE username = '{$_SESSION['MM_Username']}'"; $res = mysql_query($sql) or die(mysql_error()); if(mysql_num_rows($res) == 0) die("Username not found in database."); $row = mysql_fetch_array($res); echo "<img src='$dir/{$row['prof_pic']}' width='38' height='38'><br>"; ?> I have some other code which allows users to post a message on my 'wall' The message is saved in my database in a 'messages' table with 3 columns: messageid, messgae, userid. The userid column is the same in my messages table as in my users table where the image is echo'd from. Can anybody help me write some code which will allow me to echo the images based on who created the message instead of who is logged in? Thanks in advance HI guyz, want help in a code that can help find the GCD of two input numbers Use the example of GCD (12,15). I would love to find someone that I can ask all my annoying narbish questions to. Code: [Select] $username="a1624814_bento"; $password="Password123"; $database="a1624814_siteDB"; $localhost="mysql13.xxx.xxx"; mysql_connect($localhost,$user,$password); line 13 Code: [Select] mysql_connect($localhost,$user,$password); Quote Host '31.100.100.200 is not allowed to connect to this MySQL server in /home/member/insert.php on line 13 Now after I fix this, Im sure that I will hafve a string of other failiurs, what do i do with them? some i can figure out, and normally will try to figure something out before asking. Thanks for taking the time to read!!! Hi all I'm learning php and can't see where my error is in this simple code. I just want the country title to display with the states name below. here is the code. And thnk you for any help Code: [Select] // create arrays $_Mexico = array ('YU' => 'Yucatan', 'BC' => 'Baja California', 'QA' => 'Oaxaca'); $_US = array ('MD' => 'Maryland', 'IL' => 'Illinois', 'PA' => 'Pennsylvania', 'IA' => 'Iowa'); $_Canada = array ('QC' => 'Quebec', 'AB' => 'Alberta', 'NT' => 'North Territories', 'YT' => 'Yukon', 'PE' => 'Prince Edward Island'); // combine them $_N_america = array ('Mexico' => $_Mexico, 'United States' => $_US, 'Canada' => $_Canada ); // create loop foreach ($_N_america as $country => $list) { echo "<h2>$country</h2><ul>"; } foreach ($list as $k => $v) { echo "<li>$k - $v</li>\n"; } echo '</ul>'; Ok, I am currently at Uni, with one of my units needing me to build a content management system. I have been learning PHP for about 2 months, so go easy on me. So I was developing happily, I was able to use the CMS to add a product, edit that product and delete it. I load it up today to carry on working on it, but find that adding a product no longer works. I investigate further and find that the HTML form on the "Add a product" section's processing page (createProduct.php) is not receiving the values from the form using the $_POST method, therefore the mysql query was containing empty values. I found this confusing as I had not changed any of the code. So i investigate further, creating a test php page, copying the $_POST method into here and echoing the variables. And.. it worked. Even more confused, I delved deeper and found that the culprit for the $_POST method not working was one of my includes. connection.php. Here is the connection.php include: Code: [Select] <?php //1. Create database connection $connection = mysql_connect("localhost", "root"); //No password on the DB yet as it is only local. if (!$connection) { die("Database connection failed: " . mysql_error()); } //2. Select database to use $db_select = mysql_select_db("cms",$connection); if (!$db_select) { die("Database selection failed: " . mysql_error()); } ?> And here is createProduct.php; Code: [Select] <?php require_once("../includes/connection.php");?> <?php require_once("../includes/functions.php");?> <?php ?> <?php //Populating the variables with values from the HTML form $Product_Name = mysql_prep($_POST['Product_Name']); $Price = mysql_prep($_POST['Price']); $Product_Information = mysql_prep($_POST['Product_Information']); $category_id = $_POST['category']; echo $Product_Name . "<br />"; echo $Price . "<br />"; echo $Product_Information . "<br />"; echo $category_id . "<br />"; ?> <?php //Creating and submitting the mysql query echo $category_id; $query = "INSERT INTO tblProducts( Product_Name, Price, Product_Information, category_id ) VALUES ( '{$Product_Name}', {$Price}, '{$Product_Information}', {$category_id} )"; echo $query; if (mysql_query($query, $connection)) { header("Location: createProduct.php"); exit; } //error handling else { echo "<p>Product creation failed.</p>"; echo "<p>" . mysql_error() . "</p>"; } ?> <?php mysql_close($connection); ?> So my question is.. why, when suddenly loading it up today after a few days absence would the database connection code be conflicting ONLY ON THIS PAGE. editing and deleting a product still work. I am truly stumped as this seems completley illogical and is probably something really obvious. Any help would be greatly appreciated. Good day people, got this open source script for a dog pedigree database on the net. I have no programming skills at all. Need some help with the script, i want to change the font color of the Sire's side of the pedigree that is displayed , but have no idea how to do it, any help would be appreciated. Example of displayed pedigree - http://www.sa-apbt.co.za/details.php?id=63854 below are the code. Thanks in advance <?php function DbTriad($dogVO, $level, $generations, $childText) { global $THUMBNAIL_WIDTH; global $dogDAO; # do the individual. if ($level == $generations) { echo "<TD >"; } else { echo "<TD ROWSPAN=" . pow(2,($generations - $level)); echo " >"; } if (($dogVO != -1) && (!empty($dogVO ))) { if (empty($dogVO)) { echo "Unknown Individual"; } else { $name = $dogVO->name; $sireId = $dogVO->sire->id; $damId = $dogVO->dam->id; $landofbirth = $dogVO->landofbirth; $yearofbirth = $dogVO->yearofbirth; $color = $dogVO->color; $title = $dogVO->title; $photo = $dogVO->photo->thumb_ref; if (empty($photo)) $photo = $dogVO->photo->reference; } ### Highlight title w/ Blue font if (!empty($title)) { echo "<label>"; echo "<font color=\"blue\">$title</font><BR>"; echo "</label>"; } echo '<a href="'.$_SERVER['PHP_SELF'].'?id='.$dogVO->id.'">'; if (!empty($photo)) { echo '<p><img SRC="'.$photo.'" width="'.$THUMBNAIL_WIDTH.'"></p>'; } echo "$name</a>"; echo "<label>"; //if (($level <= 3) && (!empty($color))) { if (!empty($color)) { echo "<BR>$color "; } if (!empty($landofbirth)) { echo "<BR>$landofbirth"; } if (!empty($yearofbirth)) { echo "<BR>$yearofbirth"; } echo "</label>"; } else { echo " "; if (!empty($childText) ) echo '<a href="addDog.php?child='.$childText.'">Add Dog</a>'; } echo "</TD>"; # do the father. if ($level < $generations) { if (!empty($dogVO)) $childText = "fatherOf_".$dogVO->id; else unset($childText); $dogDAO = new DogDAO(); if (empty($sireId)) $father = null; else $father = $dogDAO->get($sireId); DbTriad($father, $level + 1, $generations, $childText); } # do the mother. if ($level < $generations) { if (!empty($dogVO)) $childText = "motherOf_".$dogVO->id; else unset($childText); $dogDAO = new DogDAO(); if (empty($damId)) $mother = null; else $mother = $dogDAO->get($damId); DbTriad($mother, $level + 1, $generations, $childText); } # finish up. if ($level == $generations) { echo "</TR><TR>"; } } # begin table echo '<table id="pedigree" align="center" width="96%" border="0"><tr><th colspan='.$generations.'>Pedigree of '.$dog->name.' '.$dog->title.'</th></tr>'; # do tree. $dogDAO = new DogDAO(); $dog = $dogDAO->get($currId); DbTriad ($dog, 1, $generations, null); # end table echo "</td></tr></table>"; ?>[/php] I am brand new to php and the following code gives me an error of undefined variable although it seems to be defined. Please tell what I'm doing wrong cause this code comes from a book: <?php // Definition of the class Donation class Donation { private $name; private $amount; static $totalDonated = 0; static $numberOfDonors = 0; // Function to display what each person has donated function info() { $share = 100 * $this->amount / Donation::$totalDonated; return "{$this->name} donated {$this->amount} ({$share}%)"; } function __construct($nameOfDonor, $donation) { $this->name = $nameOfDonor; $this->amount = $donation; Donation::$totalDonated = Donation::$totalDonated + $donation; Donation::$numberOfDonors++; } function __destruct() { 109) Donation::$totalDonated = Donation::$totalDonated - $donation; Donation::$numberOfDonors--; } } It gives me the following error: Notice: Undefined variable: donation in C:\wamp\www\learnPHP\unitCounter.inc on line 109 <?php $visitpage = "http://mywebsite.com/wp-content/uploads/test.jpg"; ?> <div style="text-align: center;"><img src=<?php echo $visitpage; ?>/></div> do you know why the image is not appearing in the coe above? why my syntax of php and html is wrong? |