PHP - Querying A Table Multiple Times In The Same Script
Ok, I need some serious help here.
I have a jQuery .load method that retrieves a single users name from a database. However... I also need to incorporate error checking into the script that the .load method access, so that, if the user enters a name in the field that is not in the database, it will insert it into the database, and then then pull it back out again to be returned by the ajax call. This is the jQuery that performs the call: Code: [Select] $('#submit').click(function(e) { var user = $('#user').val(); var checkurl = "indexData.php"; $('#username').load(checkurl, 'user=' + user); e.preventDefault(); }); This is the script form indexData.php: Code: [Select] <?php $db = mysql_pconnect('localhost', 'joeme0', 'Galatians2'); if (!$db) { die('Could not connect: ' . mysql_error()); } mysql_select_db('joeme0_brave'); $name = $_POST['name']; $checkQuery = "select name from users where name='$name'"; $checkResult = mysql_query($checkQuery); if ($checkResult > 1) { $insQuery = "insert into users (id, name) values ("", '$name')"; $insResult = mysql_query($insQuery); if ($insResul 0) { $query="select name from users where name='$name'"; $result=mysql_query($query); while($row=mysql_fetch_array($result)) { echo $row['name']; } } else { echo "Cold not insert your name into the database"; } } else { $query="select name from users where name='$name'"; $result=mysql_query($query); while($row=mysql_fetch_array($result)) { echo $row['name']; } } ?> So far I can get it to pull out a name that is manually entered into the database no problem. But I can't get it to insert a name that isn't in the database, and then query the database a second time to pull that same name back out again. The page is pretty simple. The user comes to the page, enters their name in the text field, either clicks the submit button or presses the enter key. The scripts fire off the ajax call to the database, check to see if the name exists, if not enter it and pull it back out (this is where I have the problem), if so, pull it out and display it back on the page. Similar TutorialsHi, I'm very new to PHP and have managed to get through most of the problems I've encountered so far, but I have got to one point that I can't seem to solve. I have two mysql tables (Categories & Products), I have a page that shows the categories (generated from the categories table) and when a category is selected it lists the products in that category. Due to stock etc. not all categories always have products associated to them. The Category & Product Tables are automatically updated, so what I need to do is only show categories that have products associated to them, both tables have a column category_no, and nothing I've tried so far seems to work. The code I have so far is:- Code: [Select] Require_once('config.php'); Mysql_connect(db_host, db_user, db_password); @mysql_select_db(db_database) or die( "unable to select database"); $query="select * from categories"; $result=mysql_query($query); $num=mysql_numrows($result); Mysql_close(); Thanks Pete First, Happy X-Mas to all! I want to do a form for entering dog-show results. On first site of form the user is able to enter how many dogs for each class (there are youth and open class for example) he want to insert. So on second site there will be formfields for every dog in every class, created with php. User should be able to take dogname from jquery autocomplete - this works for multiple fields. But i need the according id to the dogname - and actual only one id is given - the first one is changing by choosing from autocomplete in next fields... Data came from a json array like 0: {dogidindatabase: "9892", value: "Excalibur Khali des Gardiens de la Cour ",…} dogidindatabase: "9892" label: "<img src='../main/img/female.png' height='20'>Excalibur Khali des Gardiens de la Cour " value: "Excalibur Khali des Gardiens de la Cour " 1: {dogidindatabase: "15942", value: "Excalibur from Bandit's World Kalli",…} dogidindatabase: "15942" label: "<img src='../main/img/male.png' height='20'>Excalibur from Bandit's World Kalli" value: "Excalibur from Bandit's World Kalli"all i need is inside ... the script in form is <script type='text/javascript'> //<![CDATA[ $(function() { $(".dog").autocomplete({ source: "xxx.php", minLength: 3, select: function(event, ui) { $('#dogidindatabase').val(ui.item.dogidindatabase); } }); $["ui"]["autocomplete"].prototype["_renderItem"] = function( ul, item) { return $( "<li></li>" ) .data( "item.autocomplete", item ) .append( $( "<a></a>" ).html( item.label ) ) .appendTo( ul ); }; }); //]]> </script>and the form looked like <input type='text' name='dog' class='dog' value='".strip_tags(${'dogname' .($countbabymale+1)})."' size='35' data-required='true' /><br> <input class='readonly' readonly='readonly' type='text' id='dogidindatabase' name='dogidindatabase' size='5' />I changed in script and form id='dogidindatabase' to class, but it doesn´t work. Testsite is under http://www.wolfdog-d...how.php?lang=de (only german at first) - Insert a number (higher than 1) under baby 3-6 (first box, the others are not working for testing); submit to get to page 2; you see all post-variables (for testing). Try to insert a dogname in first input-field (choose "exc") and insert first one - the id is under dogname. In second dogname inputfield you can choose second dog - the id for the first one changes to id of seond one .... How can i get both for every dog? Hi everyone. I'm a query very similar to the one below with no success. Unfortunately SQLs and joins are not my strong suit. Code: [Select] SELECT f.field1, f.field2, f.field3 FROM fields_table f WHERE f.field1 = SOME_VALUE LEFT JOIN fields_table s ON s.field2 > f.field2 AND s.field3 <= f.field3 LIMIT 1 I would like the first SELECT query to be returned even if there are no matches on the join, also I'd like the second table query to be limited to 1. Is this possible? Could anyone revise the table above to make this work? Thanks! I have three tables: events, orderdetails & orders. First I query orderdetails to find all the records that match the EventID: $query1 = SELECT * FROM orderdetails WHERE EventID = $_SESSION['EventID']; This returns 4 records. These 4 records have a field called DetailOrderID which is the foreign key for orders.OrderID. Next I need to query the results of the first query to find all the records in the orders table that match up. For example: SELECT * from orders where $query1.DetailOrderID = orders.OrderID. How would I go about doing this? I'm head down the temporary table solution but wanted to through this one out for discussion before I invest too much time. hi I have 2 tables (members & friendship) Members table columns: -------------------------------------------- username | password | email | etc .... -------------------------------------------- Person 1 xxxxxx x@x.com person 2 yyyyyy y@y.com Friendship columns: --------------------------------------- username | friend | status | --------------------------------------- person 1 person 2 friends person 2 person 1 friends person 1 person 3 pending I want to query the friendship table: "SELECT friend FROM friendship WHERE username ='$_SESSION['myusername'];' AND status='friends' " (so its basically getting the user names of anyone who is the logged in users friend) And then use the returned user names to select their data from the members table. Any help much appreciated! ^.^ Hi guys, i got the following code i wrote which displays a small pop up on screen if the user has mail, and display a little icon. The problem is it displays a new icon for each new mail message. How can i make it so it only display 1 icon no matter how many unread mail the user has. Or even better if not too complicated display a number next too the image? Code: [Select] <? require'xxxxxxxxxxxxxxxxx.php'; mysql_select_db("membership") or die( "Unable to select database"); $sql=("SELECT * FROM user_alerts WHERE user_id = '".($_SESSION['user_id'])."'") or die (mysql_error()); if ($query=@mysql_query($sql)) { if (mysql_num_rows($query) > 0) { while ($req=mysql_fetch_array($query)) { if ($req['messageRead'] == 'NO') { ?> <div> <img src="xxxxxxxxxxxxxx.png" width="32" height="32" alt="unread mail" /> <a href="http://www.xxxxxxxxxxxx/account=account">You have Mail!</a> <div id="boxes"> <div style="top: 199.5px; left: 551.5px; display: none;" id="dialog" class="window"> <h2>You have new mail!</h2> <br /> <p>Visit your account page to read it.</p> <br> <a href="#" class="close">Close Window</a> </div> <!-- Mask to cover the whole screen --> <div style="width: 1478px; height: 602px; display: none; opacity: 0.8;" id="mask"></div> </div> </div> <? } } } } You can ignore most of the div stuff but that's pretty much it. It should check my database for any entries with the users session id in the column called 'user_id'. and only show the image if it then finds an entry with 'NO' in the 'messageRead' column. It currently shows the images for each entry it finds. Thanks for any help Greetings.. I have an ajax application i'm creating, that allows uploading images 1 at a time. That part works, and it works well. What I need to know now, is how would I go about converting the existing code I have, to change the sizing of it twice as well as renaming the images to something more website friendly. here is the code that i currently have, im sure this is easy but as i can't find any workable code on the google, i am lost as to how to modify it. so any help is appreciated. Code: [Select] <script language="JavaScript" type="text/javascript"> if(!/(\.bmp|\.gif|\.jpg|\.jpeg)$/i.test(window.parent.document.form1.filefieldname.value)) { window.parent.document.form1.filefieldname.value = ""; } else { <?php function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object); } } reset($objects); rmdir($dir); } } $folder = isset($_POST['folder']) ? $_POST['folder'] : ''; if($folder == '') { $rand = rand(5, 1000000); $folder = 'temp'.$rand; ?> window.parent.document.form1.folder.value = "<?php echo $folder; ?>"; <?php } if(!is_dir("../uploads/".$folder)) { mkdir('../uploads/'.$folder); } else { $rand = rand(5, 100000); $folder = $folder.''.$rand; mkdir('../uploads/'.$folder); } $image_name = $_FILES["filefieldname"]["name"]; $newname = "../uploads/".$folder."/".$image_name; move_uploaded_file($_FILES["filefieldname"]["tmp_name"], $newname); ?> var parDoc = window.parent.document; var A = window.parent.document.form1.upload_cnt.value; A = Number(A); B = 1; var cnt = A + B; if(cnt == '8') { window.parent.document.form1.filefieldname.disabled=true; } parDoc.getElementById('upload_cnt').value = cnt; parDoc.getElementById('files_list').innerHTML += '<br><a href="../uploads/<?php echo $folder.'/'.$_FILES['filefieldname']['name'] ?>"><?php echo $_FILES['filefieldname']['name'] ?></a>'; window.parent.document.form1.filefieldname.value=""; } </script> Hi, I am having some trouble re-using a method of a class which I use to setup my pages. I have an include which instantiates the class and then I make a call at the top of each page depending on the content required. I have several javascripts I want to include for a specific page and would like to just keep calling the same method to load them. If I try to call the method twice on the last one is echoed. I don't really want have to write out different methods for each file I may need. Any help much appreciated. The included class has this: Code: [Select] class Page { public function display_top() { # page specific atrributes $this->display_js(); } public function display_js() { echo "<script type='text/javascript' src='{$this->js}'></script>\n"; } } my page has this: Code: [Select] require ('classes/page_class.php'); $page = new Page; $page->js = "js/jquery-1.3.2.min.js"; $page->js = "js/revealClass.js"; 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 have this script Code: [Select] <?php header("content-type: image/png"); include '../../api/config.php'; include "../../api/api.php"; $gamercard = getInfo($_GET['gamertag']); updateStats($gamercard['Gamertag'], "Nxe", 75); $type = $_GET['type']; switch ($type) { case "dark": $type = "dark.png"; break; case "light": $type = "light.png"; break; default: $type = "dark.png"; break; } $image = imagecreatefrompng("$type"); $img = imagecreatetruecolor(imagesx($image), imagesy($image)); $avatar_l = imagecreatefrompng($gamercard["Avatarpic-l"]); $avatar_body = imagecreatefrompng($gamercard["Avatarpic-body"]); imagecopy($img, $image, 0, 0, 0, 0, imagesx($image), imagesy($image)); imagecopy($img, $avatar_l, 64, 7, 0, 0, imagesx($avatar_l), imagesy($avatar_l)); imagecopy($img, $avatar_body, 175, -40, 0, 0, imagesx($avatar_body), imagesy($avatar_body)); for($i = 1; $i <=count($gamercard["RecentGames"]); $i++) { $gameimg = imagecreatefromjpeg($gamercard["RecentGames"][$i]["Icon"]); $x = ($i-1)*35 + 10; imagecopy($img, $gameimg, $x, 77, 0, 0, imagesx($gameimg), imagesy($gameimg)); } $ColorText = imagecolorallocate($img, 255, 255, 255); ImageTTFText($img, 10, 0, 10, 127, $ColorText, "font.ttf", $gamercard['Gamertag']); ImageTTFText($img, 10, 0, 135, 127, $ColorText, "font.ttf", $gamercard['Gamerscore']); imagepng($img); imagedestroy($img); ?> which is made to call the updateStats() function 1 time everytime the page loads. Heres the function (its in api.php) Code: [Select] function updateStats($gamertag, $type, $size) { $query = mysql_query("SELECT * FROM loadstats where Gamertag = '$gamertag' && Type = '$type'") or die(mysql_error()); $exists = mysql_num_rows($query); if ($exists == 0) { mysql_query("INSERT INTO loadstats (Gamertag, Type, Loads, Data) VALUES('$gamertag', '$type', '1', '$size' )") or die(mysql_error()); } else { $row = mysql_fetch_array($query); $newloads = $row['Loads'] + 1; $newdata = $row['Data'] + $size; mysql_query("UPDATE loadstats SET Loads = '$newloads' WHERE gamertag = '$gamertag' && Type = '$type'") or die(mysql_error()); mysql_query("UPDATE loadstats SET Data = '$newdata' WHERE gamertag = '$gamertag' && Type = '$type'") or die(mysql_error()); } } The wierd thing that is happening is, When i have the Header() set in the script, the updateStats() function appears to be called twice, but when the header is commented out, it is only called once. I can tell this by the change of data in the MYSQL database, the Loads value increases by 2 when the header is set, and it only creases by 1 when it isnt set. Any insight as to why this is happening would be greatly appreciated. I have a scenario in PHP, i need a smart way: 1. I run one process on background forever, scheduler.php - done 2. User on the web submit their task in DB to be processed by the above process(scheduler.php) - done 3. scheduler.php read the db after every 1 sec, looking for user's task. Problem: Ideally, if it founds like 10 or more tasks it should process them concurently(in parallel)..i.e it should not wait one task to be fully executed so as to run the next one as one task might take a very long time to be fullu executed. I would do like exec("nohup php <path>/file_name.php >> /dev/null 2>&1 &"), but if i have alot of tasks this will create zombie processes. Any smart way to do this will be highly appreciated! I need to know how to echo multiple things on the same page. If you do understand the last line then don't read this next part. So say if had just a textbox and a submit button. I already know how to make it where they type something and they hit submit and echo's to the page. But after it echos I want to know how to make it where if they entered in another body of text it would enter on the same page right under the last echo, or the last thing they typed. So if you could help me with this or just post a code for me that would be nice. I have a controller(generatebill.php) where I have collected all the value from the form(normaluserview.php). I can see my value is stored. But whenever I wanted to display those values in table format in another view(invoice.php in this case), it keeps repeating. For better understanding, I have uploaded the files as well.. Please help
Attached Files
generatebill.php 592bytes
2 downloads
invoice.php 31bytes
3 downloads
normaluserview.php 3.4KB
1 downloads Hi Guys just need some advice really I would like to know if there is a way I can check if a number is in a times table for example if(3 is in 4 times table){ do bla bla } the result for above will be false as 4 times table does not contain 3 if(12 is in 4 times table){ do bla bla } the above would be true Thanks guys As I title says; I need to have an image showed the number of times, the value of a table/field.. How can I do this? Hello, I'm new! I am trying to populate a list of locations based on ratings. I can populate the list just fine but it's displaying every record in the table. Is there a way of only looping 4 times so as to just display the top 4 records? Here's the code: Code: [Select] $result = mysql_query("SELECT * FROM locations ORDER BY rating DESC"); while($row = mysql_fetch_array($result)) { echo $row['name']; echo "<br>; } Thankyou in advance for any help Hello all, I'm collecting date/time information via a form and would like to convert the info into something that I can stick in my MySql database (a timestamp???). I'm collecting the current month (variable name: month-- of the form "mm"), day (variable name: day -- of the form "dd"), year (variable name: year -- of the form "yyyy"), time of day (variable name: time -- of the form "h:00"), and before or after noon (variable name: ampm -- of the form "am" or "pm"). Any suggestions as to how to change this into a quantity that I can store as a value and then use to compare to other date/times would be appreciated. Thanks! Say I have an "Entries" table. I want to submit same multiple entries using a form submission. And If I have other queries submitted in the same form, I want those quarries to be submitted only once. Is that possible to do? Here's my code. if(isset($_POST['submit'])) { $entries = 10; $id = 55; $name = 'Smith'; $insert = $db->prepare("INSERT INTO entries(id, name) VALUES(:id, :name)"); $insert->bindParam(':id', $id); $insert->bindParam(':name', $name); $result_insert = $insert->execute(); if($result_insert == false) { echo 'Fail'; } else { echo 'Success'; } } ?> <form action="" method="post"> <input type="submit" name="submit" value="SUBMIT" /> </form> Edited January 13, 2019 by imgrooot Hey all. I'm using this sort of thing to query with my application: Code: [Select] try { $stmt = $this->db->prepare($sql); /* Bind parameter if id was passed, ensure it's of integer type */ if(!empty($id)) { $stmt->bindParam(":id", $id, PDO::PARAM_INT); } $stmt->execute(); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); return $results; } catch(Exception $e) { die($e->getMessage()); }which has been working out great, with the only annoyance that sometimes, I need to run a query and I know I'm supposed to get only one row. However, I have to access associated elements via $results[0]['fieldName']. How do I run a query to return exactly one result so I can just use $results['fieldName']? |