PHP - Having A Brain Block - Adding Numbers From Database
Hi all,
for some reason I cant see this blantantly obvious query. I have 3 rows in my database, all with an id of 1, their is a column called price which contains three different float values, how the hell do I write a query in php for this?! Code: [Select] $q = mysql_query("SELECT price FROM mytable WHERE id=1") ????Thanks! Similar TutorialsIt's one of those days after a long weekend and a rainy morning. Simply trying to get the correct message depending on the variable's value if($a = 'one'){ echo "POOR";} if($a = 'two'){ echo "GOOD";} if($a = 'three'){ echo "VERY GOOD";} if($a = 'four'){ echo "EXCELLENT";} Not sure if I need to use ==, extra quotes, or ELSEIF for the best result.
This is my current script <?php $iFile = "accounts.txt"; //Put your list lagger's info in this txt file in the same directory as this script. Format is UserID(space)AuthKey $login = file($iFile, FILE_SKIP_EMPTY_LINES); if(!is_file($iFile)) echo "The logins file couldn't be found...".sleep(999999); foreach($login as $line_num => $line) { $login = explode(" ", htmlspecialchars(str_replace(" "," ",$line))); //////////////// ////////////// /////////// ///////// if(stristr($login[1], "\n")) $login[1] = substr($login[1], 0, strlen($login[1])-2); $MobLink = "http://mobsters-fb-apache-dynamic-lb.playdom.com/mob_fb/"; $RefreshStat = file_get_contents($MobLink."refresh_stat?user_id=".$login[1]."&auth_key=".$login[0]); $Mob_Name = explode("<mob_name>", $RefreshStat); $Mob_Name = explode("<", $Mob_Name[1]); $Name = $Mob_Name[0]; $Cash = explode("<cash>", $RefreshStat); $Cash = explode("<", $Cash[1]); $CurrentCash = $Cash[0]; echo $Name."-$".number_format($CurrentCash)." - ".$login[1]."\n"; } sleep(99999); ?> The Script runs through for 100 different accounts, is it possible to add all the Cash values that get echo'd? Hi all I am adding some positive and negative numbers. But i am getting strange output. Can anyone help me Here is the code. Code: [Select] $sum=7.50+6.45+12.90+12.00+13.00+0.61+32.00+4.00+27.00+18.00+10.88+129.50+92.94-100.00-38.25+76.80-305.33; echo "<br>Total: ".$sum; Basically i have to get Total is 0 but i am getting total is 5.6843418860808E-14 Can anyone help me out Please Say I do a query from a database that only asks for one field in return (which always has a number in it). How do you write the PHP to take the first number returned and add it to the next number returned (NOTE: There may be more than two numbers returned, but for now, I'm always dealing with two) For example, say I do a query that returns the number 27 first and then the number 10 second. FYI, these numbers will be available in the variable $diff['result']. So the code after the query would look something like this, but obviously i'm struggling with the part in comments... Code: [Select] if (!$numbers) { die("Database query failed: " . mysql_error()); } else { while ($diff = mysql_fetch_array($numbers)) { //this would bring back 27 first, in the variable $diff['result'] and then on the 2nd loop through, it would bring back 10 in the $diff['result'] variable //ultimately, i just want the difference between the numbers (which in the case would be 17). It's just a simple addition, so Im obviously an idiot because I can't figure out the syntax for adding the first returned number to the next returned number:) } } Hi iam currently writing some code for my website and i have a number of records that i simply want to display in a table format, i have done this in a while loop and it works well, however i only want to display a maximum of 10 records per page as my div needs to be a fixed height and was wondering how i could include a next button that would act as like a page number. The thing is at any given point there could be from 1 record to display to 500, so i need a way of allowing the user to quickly navigate to the other records. How can i do this without using mulitple pages. Hope this makes sense. Heres my code Code: [Select] <?php echo"<table width='100%' border='1' align='center'><tr><th>Referal Name</th><th>Amount Received</tr>"; while ($row = mysql_fetch_array($sql_info)) { extract($row); echo "<tr><td align='center'>".$username."</td><td align='center'>".$cumulative_referral."</td></tr>"; } echo "</table>"; ?> Thanks for your help how to block someone from visiting my page using ip adress ? this is the case if someone come to my site then we record the ip address and put it into database. when the visitor come again with the same IP they cannot see my page (block them) and redirect it to somewhere page. Hello! I need to loop through a list of numbers and check if they are present in a column in a database or not. I'm having a hard time figuring out how to check the column value by value and compare to a incrementing $i value. here is my query... Code: [Select] $query2 = mysql_query("SELECT * FROM video"); $column = mysql_fetch_array($query2); echo $column2['cable_number']; this only echoes me the first ['cable_number'] in the database. i need to get every single one, and perform actions on each one as they come through. and here is my for() statement Code: [Select] for($i=100;$i<=$highest;$i++){ check if $i is in the database. if it is(do something) if it isn't(do something) } i need to use that $i each iteration and see if it's present in the 'cable_number' column in the database. then i do something and continue on with the next i$ value. Is there a recommended BEST PRACTICE for storing (and retrieving) telephone numbers from a database table? Is it best to store (in the USA) the area code separate from the rest of the number? Remove parenthesis and/or dashes? Or is there no reason to concern myself with performance or hacking issues regarding the storage of phone numbers as 323-555-1212 or (323)555-1212 inside my table? Hi, What I'm trying to do is create a script that generates a random list of cars whenever it is run. I have a list of available cars in a MySQL database. I'm just not sure how to get php to generate a list of, say, 20 cars, that are randomly picked from the cars in the database. I may also want to add other statistics like MPG (also already in the database). Can anyone show me how to do this? And is it possible to format the returned data in a table or div format? Thanks in advance Unk Hey im trying to come up with a simple script that shows the databases in my localhost then create a insert box with a "submit button" and when i type in any name lets just say test1234 it should show up in the list and i want it to show the results below such as you successfully added a database. I have started this not too long ago but i've had experience with previous database adding and i just threw it in there to get me started. Here is my code as of now. By the way I am using PHP my admin and i have it so it creates it to the list but it does it automatically but i want it to add it by me typing it in the text box and when i hit the submit button it shows up in the list and below as well. Code: [Select] <? $connection = @mysql_connect("localhost", "root", "") or die(mysql_error());; $dbs = @mysql_list_dbs($connection)or die(mysql_error()); $db_list="<ul>"; $i =0; while ($i < mysql_num_rows($dbs)){ $db_names[$i] = mysql_tablename($dbs,$i); $db_list .="<li>$db_names[$i]"; $i++; } $db_list .="</ul>"; ?> <HTML> <HEAD> <TITLE>MySQL Databases</TITLE> </HEAD> <P><strong>Databases on localhost</strong>:</p> <? echo "$db_list"; ?> </BODY> </HTML> <HTML> <HEAD> <TITLE>Adding a Database to MySQL</TITLE> </HEAD> <BODY><H3> <FORM METHOD="post" ACTION="pretask.php"> <P>Database Name <INPUT TYPE="text" NAME="val1" SIZE=10></P> <P><INPUT TYPE="submit" NAME="submit" VALUE="Add database"></P> </FORM> </BODY></H3> </HTML> </font> <? $connection = @mysql_connect("localhost", "root", "") or die(mysql_error()); if ($connection) { $msg = "YES!"; } $sql = "CREATE DATABASE my_music "; $result = @mysql_query($sql,$connection) or die(mysql_error()) ?> <HTML> <BODY> <h1><center><? echo "$msg"; ?></h1></center> </BODY> </HTML> Code: [Select] $product_id=$_GET['product']; $sql500="SELECT * FROM $tbl_name3 WHERE product_id='$product_id'"; $result500=mysql_query($sql500); $num_rows500=mysql_num_rows($result500); while($row500=mysql_fetch_array($result500)){ extract($row500); $review_product_rating_total=$review_product_rating; //What do I do here? } $average_rating=$review_product_rating_total/$num_rows500; I need a way to take a column of product ratings (0-5 in 1/2 increments), add them together, and divide by the number of rows taken from the database. I know how to get the number of rows with mysql_num_rows. But how would I add together the data from database? Hey anybody can please guide me where I m wrong in this php code please reply here is the code Only variables should be passed by reference on line 3 in that function area function get_file_extension($file_name) main error I guess is the explode one Aand yeah I checked adding $file_name = $_FILES['fld']; before the function is started <?php require("include/dbconn.php"); //$username = mysql_real_escape_string($_POST['username1']); function get_file_extension($file_name) { return end(explode('.',$file_name)); } function errors($error){ if (!empty($error)) { $i = 0; while ($i < count($error)){ $showError.= '<div class="msg-error">'.$error[$i].'</div>'; $i ++;} return $showError; }// close if empty errors } // close function if (isset($_POST['submit'])){ $username = "Sunny"; $date1 = date("d m y"); mysql_select_db("deals") or die(mysql_error()); if($username == "") { //header("location:newnewuser1.php"); echo "Username empty"; //header("location:newnewuser1.php"); } else { function createRandomPassword() { $chars = "abcdefghijkmnopqrstuvwxyz023456789"; srand((double)microtime()*1000000); $i = 0; $pass = '' ; while ($i <= 7) { $num = rand() % 33; $tmp = substr($chars, $num, 1); $pass = $pass . $tmp; $i++; } return $pass; } // Usage $password = createRandomPassword(); //$password = mysql_real_escape_string($_POST['Password']); $date = strtotime("+2hours"); $date1 = date("d-m-y",$date); if(get_file_extension($_FILES["fld"]["name"])!= 'csv') { $error[] = 'Only CSV files accepted!'; echo "Wrong Input"; }//get_file_extension if (!$error) { $tot = 0; $handle = fopen($_FILES["fld"]["tmp_name"], "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { for ($c=0; $c < 1; $c++) { try { mysql_query("INSERT INTO newusers (email,password,location,company,name,contact,sourcename,date)VALUES('".mysql_real_escape_string($data[0])."','$password','".mysql_real_escape_string($data[1])."', '".mysql_real_escape_string($data[2])."','".mysql_real_escape_string($data[3])."','".mysql_real_escape_string($data[4])."','$username1','$date1')"); $tot++; } catch(Exception $e) { PRINT 'ERROR:' +$e; } }//for }//while fclose($handle); }// end no error }//close if isset upfile } ?> and this is the form code <form name="f1" action="" method="POST" enctype="multipart/form-data"> <table><tr><td><input type="file" value="Browse" name="fld" onselect="CheckExtension(fld)"><br/></td><td> </td></tr><tr><td>Username :<input type="text" name="username1" value="" id="user" onfocus="validateForm1()"></td> <td><input type="submit" name="submit" value="submit" id="submit"></td></tr></table> </form> Please help me I m stuck in this quite badly Please [attachment deleted by admin] I am stuck on inserting the data into mysql via php. Its a foreach method and I am just stuck Code: [Select] include '../Database/take_an_exam.php'; $intNum = 1; $intnumber = 1; while( $info = mysql_fetch_array( $sqll )){ echo "<input type='hidden' name=\"Que_ID\" value=\"{$info['Que_ID']}\" /> "; echo " $intNum, {$info['Que_Question']} <br />\n"; $intNum++; for ($i =1; $i < 5; $i++) { echo "<input type=\"checkbox\" name=\"choice[{$info['Que_ID']}.$i][]\" />{$info['Que_Choice'.$i]}<br />\n"; $intnumber++; } } ?> <input type="submit" value="submit" name="submit"> This is my form that can output the Question and its choices. I am echoing this on to the next page, the code is shown below Code: [Select] <?PHP session_start(); $name= $_SESSION['username1']; echo "User ID: $name <br/>"; $gender = $_POST["choice"]; $que_ID = $_POST["Que_ID"]; foreach ($gender as $key => $array) { if($array) { $val=1; } ///echo "Question ID and the choice ID:$key. Value is:.$val <br />\n"; $well = array(floor($key), substr(strstr($key, '.'), 1)); //$well = array(floor($key), $key - floor($key)); echo "Question ID: $well[0], "; echo "Choice: $well[1]. value: $val<br/>"; } //}break; ?> Now, instead of echoing. I just want to add this to mysql. The layout of my sql is Que_ID, Ans_Choice1, Ans_Choice2, Ans_Choice3, Ans_Choice4, Use_ID When I echo my php my outcome is Quote User ID: 2 Question ID= 1 Choice 1 Question ID= 2 Choice 3 Question ID= 3 Choice 4 Question ID= 4 Choice 1 Hey All, first off Merry X-Mas ok so I'm trying to insert something into the batabse in one of three areas' let me explain there are three fields in the users database bounceone, bouncetwo and bouncethree now what I want to do is when the user clicks add to bounce list insert a value into the databse in one of these three hole, if bounceone is empty put it there, if not check bouncetwo if it's empty put it there, if not check the final one and if it's empty put it there else echo sorry please either remove a bounce any ideas on how this can be done. Hey i have set up a database and im trying to ad records to it also upload an image, when i submit my form it clears the fields but does not add to the database. There are no errors that get outputted or anything so it gives no help I have read thru my code over and over and just cant see why its not adding. Any help would be great <html> <script language="JavaScript"> function validated(){ var matric = document.s.matric.value; var name = document.s.name.value; var course = document.s.course.value; var sem = document.s.sem.value; var semint = parseInt(sem); var tel = document.s.tel.value; var telint = parseInt(tel); var address = document.s.address.value; var picture = document.s.picture.value; if(matric==""){ window.alert("Please enter matric number!"); document.s.matric.focus(); return false; } if(name==""){ window.alert("Please enter student name!"); document.s.name.focus(); return false; } if(course==""){ window.alert("Please enter student course!"); document.s.course.focus(); return false; } if(isNaN(semint)){ window.alert("Please enter student semester!"); document.s.sem.focus(); return false; } if(isNaN(telint)){ window.alert("Please enter contact number!"); document.s.tel.focus(); return false; } if(address==""){ window.alert("Please enter student address!"); document.s.address.focus(); return false; } if(picture==""){ window.alert("Please enter student picture!"); document.s.picture.focus(); return false; } } </script> <body> <table width="100%" border="0" cellspacing="0" cellpadding="2"> <tr> <td align="center"><h1><font color="#0000FF" face="Arial">ADD STUDENT PROFILE</font></h1></td> </tr> </table> <br><br> <table width="100%" border="0" cellspacing="0" cellpadding="2"> <tr> <td align="right"><font size="1" face="Arial"><a href='main.php'>Student List</a></font></td> </tr> </table> <br><br> <form method="post" action="student_form.php" enctype="multipart/form-data" name='s' onsubmit='return validated()';> <table width="70%" border="0" align="center" cellpadding="2" cellspacing="2"> <tr> <td width="33%" align="right"><font size="2" face="Arial"><strong>Matric Number</strong></font></td> <td width="5%" align="center">:</td> <td width="62%"><input type='text' name='matric' size=30 maxlength=15></td> </tr> <tr> <td align="right"><font size="2" face="Arial"><strong>Name</strong></font></td> <td align="center">:</td> <td><input type='text' name='name' size=30 maxlength=50></td> </tr> <tr> <td align="right"><font size="2" face="Arial"><strong>Course</strong></font></td> <td align="center">:</td> <td><input type='text' name='course' size=30 maxlength=50></td> </tr> <tr> <td align="right"><font size="2" face="Arial"><strong>Semester</strong></font></td> <td align="center">:</td> <td><input type='text' name='sem' size=5 maxlength=2></td> </tr> <tr> <td align="right"><font size="2" face="Arial"><strong>Sex</strong></font></td> <td align="center">:</td> <td><input type='radio' name='sex' value='Male' checked> Male <input type='radio' name='sex' value='Female'> Female</td> </tr> <tr> <td align="right"><font size="2" face="Arial"><strong>Contact Number</strong></font></td> <td align="center">:</td> <td><input type='text' name='tel' size=30 maxlength=50></td> </tr> <tr> <td align="right"><font size="2" face="Arial"><strong>Address</strong></font></td> <td align="center">:</td> <td><input type='text' name='address' size=50 maxlength=100></td> </tr> <tr> <td align="right"><font size="2" face="Arial"><strong>Picture</strong></font></td> <td align="center">:</td> <td> <input type="hidden" name="MAX_FILE_SIZE" value="10485760"> <input type="file" name="picture" size="40"> <font size="1" face="Arial"> Maxsize 1MB</font> </td> </tr> <tr> <td> </td> <td> </td> <td><input type='submit' name="submit" value='Submit'> <input type='reset' value='Reset'></td> </tr> </table> <?php if ($submit) { include 'db_connect.php'; $data = addslashes(fread(fopen($picture, "r"), filesize($picture))); $pjpeg="image/pjpeg"; $jpeg="image/jpeg"; $gif="image/gif"; $png="image/png"; $bmp="image/bmp"; if ($picture_type == $pjpeg OR $picture_type == $jpeg OR $picture_type == $gif OR $picture_type == $png OR $picture_type == $bmp) { $sql="INSERT INTO info (matric, name, course, sem, sex, tel, address ,bin_data,filename,filesize,filetype) VALUES ('$matric', '$name', '$course', '$sem', '$sex', '$tel', '$address', '$data','$picture_name','$picture_size','$picture_type')"; $result=mysql_query($sql); header ("Location: main.php"); } else{ echo "<script language='JavaScript'>"; echo "window.alert('Error! You only can upload jpeg, gif, png, bmp file type.')"; echo "</script>"; } } ?> </form> </body> </html> Thanks, Hi, how to make this form + php to make it work this way from the drop-down box choose the database title, or ID, and then the form in which I write some content will be added to the database that matches the title or ID that is sometimes so as not to invade a mistake and content that I type is not added to another title or ID I created something like this: <?php $db = new mysqli('localhost','xxxxx','xxxx','xxxx'); mysqli_query($db,'SET NAMES `utf8`'); $sqlnowe = mysqli_query($db,'SELECT * FROM `cc` ORDER BY `id` DESC '); ?> <form action="formu.php" method="post"> <select name="tytul"> <?php while ($rownowe = mysqli_fetch_array($sqlnowe)) { ?> <option><? echo $rownowe['tytul']; ?></option><?php };?> </select> opismax:<br /> <input type="text" name="opismax" /><br /> <textarea name="opismax" cols="50" rows="10">Proszę, wpisz tutaj jakiś komentarz...</textarea> <input type="submit" value="dodaj" /> </form> <?php // odbieramy dane z formularza $tytul = $_POST['tytul']; $opismax = $_POST['opismax']; if($tytul and $opismax) { // dodajemy rekord do bazy $ins = mysqli_query("INSERT tytul='$tytul' INTO publications SET opismax='$opismax'"); if($ins) echo "Good"; else echo "Bad"; } ?> hello, i am hoping someone can help, i have a form that has a body and title fields and then sends to this function below. it all works fine, but when i add a image or a link it stores it in the text field of the db like this: <IMG alt=\"\" src=\"/public/images/231781538234094.jpg\" width=796></P> this is what it should be /public/images/231781538234094.jpg so when i view the image it doesent show it and i right click the image and goto image properties and i get this: http://test.cyberglide.co.uk/%22public/images/231781538234094.jpg/%22 Code: [Select] function content_update() { $title = mysql_real_escape_string($_POST['title']); $body = mysql_real_escape_string($_POST['body']); $page = mysql_real_escape_string($_POST['page']); $location = mysql_real_escape_string($_POST['location']); $id = mysql_real_escape_string($_POST['id']); $sql = "UPDATE content SET title = '$title', body = '$body', page = '$page', location = '$location' WHERE id = '$id'"; $res = mysql_query($sql) or die(mysql_error()); echo "<script>window.location='content.php'</script>"; } if i manually edit it on the db it works fine please help, many thanks. Good day guyz... I dont know why this code does not work... the connection is fine, the database is also fine it works with the localhost, when i upload it on free hosting site like 000webhost and infinityfree this is not working.. the database on free hosting site are also working also the connection is code, just only this code i cant figure it out.. else{ $sql = "INSERT INTO .$name (TrxID, ProductName, Price, ProductImage, PurchasedDate, PurchasedStatus) VALUES (?, ?, ?, ?, ?, ?)"; $stmt = mysqli_stmt_init($conn2); if(!mysqli_stmt_prepare($stmt, $sql)){ echo 'connection error'; } mysqli_stmt_bind_param($stmt, "isssss", $val, $PName, $Price, $PImage, $PDate, $PStatus); mysqli_stmt_execute($stmt); mysqli_stmt_close($stmt); header("location: ../customer/cart.html"); exit(); } }
Hi all, I have a code which works just fine for adding one picture to my database but when I change the form to add mutliples i get an error because my code is set for multiple pictures as an array. Error says this is a string code. Does anyone know the code for array? Code: [Select] $target = "upload/"; $target = $target . basename( $_FILES['photo']['name']); Error message says Warning: basename() expects parameter 1 to be string, array given in /home/content/19/6550319/html/listingsss.php on line 7 Thanks, Philip Like many projects, this started small, and keeps growing! I am building a photo gallery and would now like to add labels/captions below each photo, HOWEVER, I really don't want to have to build a database and do all the related coding. (I know how, but its a PITA.) To display photos in the gallery, I read in files from my "images/" directory, store them in a simple array, and then iterate through the array to display the thumbnails in a gallery. I am wondering if there would be an easy way that I could merge photo metadata (e.g. a brief caption) with my array or something like that? If I could type up the file names and a brief description/caption in a Text File or Spreadsheet and then somehow slurp that into my code and merge it with my array or something like that, then I would be willing to type up captions. (This is for like 600 photos which is why I don't want to do a database as data entry in phpMyAdmin is a PITA!) Any suggestions how I could do this and add a "cherry on the top" of this mini project I am doing for my co-workers? Thanks!
|