PHP - Query Not Bringing Data
Hello, I hope all of you are safe with your families. Currently I am starting with PHP Coding and I am trying to do a simple query to MySQL DB using PHP but even when is able to bring the number of rows is not displaying the values in the DB. This is my code: <?php $servername = "localhost"; $database = "mydbtest"; $username = "root"; $password = "root"; // Create connection $conn = mysqli_connect($servername, $username, $password, $database); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } //echo "Connected successfully"; $myquery = "SELECT * FROM Country"; $result = $conn->query($myquery); $numf = $result->num_rows; echo "Number of rows " . $numf . "<br>"; if($numf >0){ while($row = $result->fetch_object()){ echo "Code" . $row->countrycode . "<br>"; echo "Country" . $row->countryname . "<br>"; } }else{ echo '0 results'; } mysql_free_result($myout); mysqli_close($conn); ?> What is failing?
Thanks in advance for the assistance. Similar TutorialsI was just wondering if it's possible to run a query on data that has been returned from a previous query? For example, if I do Code: [Select] $sql = 'My query'; $rs = mysql_query($sql, $mysql_conn); Is it then possible to run a second query on this data such as Code: [Select] $sql = 'My query'; $secondrs = mysql_query($sql, $rs, $mysql_conn); Thanks for any help I have a weird problem with an md5() function. I am trying to write a token system, (just for my own fun really), going off an example guestbook I got help with from here. What my main aim is to allow the moderator for the guestbook to receive an email (which is working in its own context), with a link to a script page that checks into the database and when the user clicks on the link it allows the message in the guestbook to be shown. But when I try md5() the ip address of the user it works, but I thought if that same user went in and did another post, it would come up with the same checksum, causing quite bad problems to be honest. So I thought about using something like: $time = microtime(); $checksum = md5($ip,$time); But this keeps coming up with say: Quote 3RiYD Is there anyway of getting around this at all? To show a real value as I am sure this wont work, any helps greatly appreciated, Jeremy Hi Having thought the PHP form was working OK, I took a break. Upon return, it's up to its old tricks. Could anyone glance over this code for blatant errors? It works when it wants and when it doesn't... Much appreciated <? $select=$_POST['select']; $name=$_POST['name']; $email=$_POST['email']; $confirmail=$_POST['confirmail']; $month=$_POST['month']; $day=$_POST['day']; $year=$_POST['year']; $leaving=$_POST['leaving']; $hour=$_POST['hour']; $minutes=$_POST['minutes']; $ampm=$_POST['ampm']; $going=$_POST['going']; $flightnumber=$_POST['flightnumber']; $pay=$_POST['pay']; $song=$_POST['song']; $comments=$_POST['comments']; $to="beepbeepyeah@kabeoke.com"; header('Location:http://www.kabeoke.com'); $message="Message Type: $select\n\nName: $name\n\nEmail: $email\n\n$confirmail\n\nDate of Journey: $month, $day, $year\n\nLeaving From: $leaving\n\nDeparture Time: $hour:$minutes $ampm\n\nGoing to: $going\n\nFlight Number: $flightnumber\n\nPayment Method: $pay\n\nSong Requests: $song\n\nComments: $comments"; if(mail($to,"Slap it - message from Kabeoke.com!",$message,"From: $email\n")) { } else { echo "There was a problem sending the mail. Please check that you filled in the form correctly."; } ?> Hi, I want to pull data from db, where sometimes all rows and sometimes rows matching given "username". Here is my code:
//Grab Username of who's Browsing History needs to be searched. if (isset($_GET['followee_username']) && !empty($_GET['followee_username'])) { $followee_username = $_GET['followee_username']; if($followee_username != "followee_all" OR "Followee_All") { $query = "SELECT * FROM browsing_histories WHERE username = \"$followee_username\""; $query_type = "followee_username"; $followed_word = "$followee_username"; $follower_username = "$user"; echo "$followee_username"; } else { $query = "SELECT * FROM browsing_histories"; $query_type = "followee_all"; $followed_word = "followee_all"; $follower_username = "$user"; echo "all"; } }
When I specify a "username" in the query via the url: browsing_histories_v1.php?followee_username=requinix&page_number=1 I see result as I should. So far so good.
Now, when I specify "all" as username then I see no results. Why ? All records from the tbl should be pulled! browsing_histories_v1.php?followee_username=all&page_number=1 This query shouldv'e worked:
$query = "SELECT * FROM browsing_histories";
I'm having trouble trying to separate the output into variables that I can use/echo on my page. when I do a print I see the two rows of data all grouped together how can I separate each result base on field and row? maybe something like $line['m_id'][0], $line['m_name'][0], $line['m_id'][1], $line['m_name'][1], etc... $bio = mysql_query("SELECT * FROM soc_meminfo WHERE m_id = '".mysql_real_escape_string($en['mm_id'])."'"); if (mysql_num_rows($bio) == 0) call404(); while ($line = mysql_fetch_assoc($bio)) { foreach ($line as $key => $value) { $en['b'.$key] = str_replace("\n",'<br/>',stripslashes($value)); } echo '<pre>'; print_r($line); echo '</pre>'; } Alright, I've spent over a week trying to fix this now - And Im getting frustrated! I asked at other forums, I asked co-workers and I asked friends-of-friends, and nobody can explain what happens. Let's take a look at this first: $name = mysql_real_escape_string($_POST['name']); mysql_query(sprintf("UPDATE em_users SET name='%s' WHERE id='" . $in_user['id'] . "'", $name)); This will insert NO data on the Name field in the database. Obviously, I thought the $_POST variable wasn't passed correctly, but echo'ing it just before the query WILL show data. And as I said, I tried everything possible for the last week. Switching variables, adding static text on the $name variable instead of using the $_POST content (this does work). I used very very simple test data on the form, such as my name "Mark" or "test" and "hey". The query is correctly executed everytime. The truely WEIRD thing is, if I ensure there is content in $name before executing the query it will work as expected everytime. Like this: $name = mysql_real_escape_string($_POST['name']); $name && mysql_query(sprintf("UPDATE em_users SET name='%s' WHERE id='" . $in_user['id'] . "'", $name)); Of course I could do this, but I want to know why my code does or doesn't work + it's a lot of work to do for something that worked fine a week ago. It has spread to a lot of forms on my website that $_POST variables aren't processed correctly - and it happened out of nowhere. Even on codes that havnt changed in months. I really need help on fixing this! This project has been in development for nearly two years, and without a fix it's pretty much lost hi guys Ive written this php to take in two variables from the http POST, the idea is that I can multiple devices submit temperature readings to the php script, the script then append the unix time stamp and then the the 3 variables - device id, temp and unix time are then stored in a mysql DB. I can get the variables to present on a php page for debugging but I cant get the variables to be stored in the mysql DB. See the code: Code: [Select] <?php $unixtime = time(); // get device variables $device_id=$_GET['device']; $device_temp=$_GET['temp']; /* //for testing purposes echo "unixtime: " . $unixtime . "<br />"; echo "device id: " . $device_id . "<br />"; echo "device_temp: " . $device_temp . "<br />"; */ // Make a MySQL Connection mysql_connect("localhost", "username", "password") or die(mysql_error()); mysql_select_db("test") or die(mysql_error()); //mysql query $query = "INSERT INTO temperature VALUES ('',$device_id,$temp,$unixtime)"; // Insert a row of information into the relevant device table mysql_query($query); or die(mysql_error()); mysql_close(); echo "Data Inserted!"; ?> I cant see where Im going wrong to correct this, but as nothing is displayed on the page i believe I am not forming the query correctly? - any ideas would be much appreciated. Thank you Mathew I've only been studying PHP for a week now and have come across this problem which I'm sure there is a simple answer to, but I just can't figure it out and would appreciate some help. I've spent far too long on this minor issue already! I have a table which contains a list of products, in this case books, which stores the date when each new item is added. I have a query that then searches through this table and extracts the 6 most recent additions. Here is the code I have so far: Code: [Select] $sql = mysql_query("SELECT * FROM products ORDER BY date_added DESC LIMIT 6"); $productCount = mysql_num_rows($sql); // count the output amount if ($productCount > 0) { while($row = mysql_fetch_array($sql)){ $id = $row["id"]; $title = $row["title"]; $author = $row["author"]; $price = $row["price"]; $date_added = strftime("%b %d, %Y", strtotime($row["date_added"])); $dynamiclist .= //My table showing the products } } else { $dynamicList = "There are currently no Books listed in this store"; } This works well when I need to display the 5 most recent products in a normal table fashion, one below another, on the page. However, I want to display the products in a more personalised order. For example display the newest item in one section of the page and 3rd newest in another. What is the best way to select an individual row from a query? To extract the details of the 2nd newest item to display in the header, for example. Thanks for your help. I am at a loss why my query is not inserting values into db. Even if I do echo $query or var_dump($query) there is nothing printed at all. All values are being passed successfully just not being inserted. I am getting 'Could not connect' but I do not know why. All connections are established and as a test I took this code and ran it on it's own with dummy data and it inserted the data fine. I can only think it has something to do with the $response_array. Where am I going wrong. and would appreciate any help. Thanks Code: [Select] <?php require_once('Connections/sample.php'); ?> <?php session_start(); $new = 1; $activity = 'General Contact Enquiry'; $mobile = 'Submitted from mobile'; $name = mysql_real_escape_string($_POST['GC_name']); $department = mysql_real_escape_string($_POST['GC_department']); $message = mysql_real_escape_string($_POST['GC_message']); $email = mysql_real_escape_string($_POST['GC_email']); $company = mysql_real_escape_string($_POST['GC_company']); $position = mysql_real_escape_string($_POST['GC_position']); //response array with status code and message $response_array = array(); //validate the post form //check the name field if(empty($name)){ //set the response $response_array['status'] = 'error'; $response_array['message'] = 'Name cannot be blank'; //check the name field } elseif(empty($company)) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'You must enter a company name'; //check the position field }elseif(empty($position)) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'You must enter a position'; //check the email field } elseif(empty($email)) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'You must enter a valid email address'; //check the dept field }elseif($department=="Choose Department") { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'You must select a department'; //check the message field }elseif(empty($message)) { //set the response $response_array['status'] = 'error'; $response_array['message'] = 'You must enter a message'; //check the dept field } else { //set the response $response_array['status'] = 'success'; $response_array['message'] = 'Your enquiry has been sent succesfully'; $flag=1; } //send the response back echo json_encode($response_array); if($flag == 1) { mysql_select_db($database_sample, $sample); $query = 'INSERT INTO feedback (company, department, name, email, position, feedback, date, new) VALUES (\''.$company.'\', \''.$department.'\', \''.$name.'\', \''.$email.'\', \''.$position.'\', \''.$message.'\', NOW() , \''.$new.'\')'; mysql_query($query) or die("Could not connect"); } ?> I know that I can fairly easily pull my data from the database and view it in a browser. I can also 'polish' it with some HTML or put it into a table. Can I get an item from a given VARIABLE to appear inside of an INPUT box, so that it looks the same as when it was initially submitted? Can it be done with a multiple choice SELECT dropdown, so that the item chosen is viewable again? Hi guys, im trying to connect to a database and get the value for the user in the row called 'user_credit', if it equals 1 or more then i want to show the ''You have £ ....'' bit in the script. Problem is nothing shows at all, even without the if statement. I have changed the value for me in the database so in user_credit the value is 100, which is more than 1 so it should appear. I have probably done something wrong. Any ideas? Code: [Select] <? include '../admin/database/membership_dbc.php'; $r = mysql_query("SELECT * FROM users WHERE user_name='".safe($_SESSION['user_name'])."'") or die ("Cannot find table"); while( $cred = mysql_fetch_array($r) ) { if ($cred >= '1' ) { ?> <p>You have £<? echo $cred['user_credit']; ?> available on you account, would you like to use it on this order?<br> <label for="credit"></label> <select name="credit" id="credit"> <option value="Y" selected>Yes, use credit</option> <option value="N">No, save credit</option> </select> </p> <? } } ?> Hello, I seem to have some problem with my script that has a goal of outputting data about the file size when a filename is queried.
The sql table name is file
The table columns are as followed: id | name | mime | size
The file name is stored in name. The script that i have that gets the file name is:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta name="generator" content="Adobe GoLive" /> <title>File Select</title> <!--The following script tag downloads a font from the Adobe Edge Web Fonts server for use within the web page. We recommend that you do not modify it.--><script>var __adobewebfontsappname__="dreamweaver"</script><script src="http://use.edgefonts.net/aguafina-script:n4:default.js" type="text/javascript"></script> </head> <body> <div id="title"> <h3 align="center">File Upload</h3> </div> <form action="result.php" method="post" name="fileID" target="_self" class="inp" AUTOCOMPLETE="ON"> <h1> <!--Input file name--> <label for="fileID">File Name: </label> <input type="text" name='file1' id='sampleID' list="samp"> </input><br> <datalist id="samp"> <?php $connect = mysql_connect('localhost', 'root', ''); mysql_select_db("test_db"); $query = mysql_query("SELECT * FROM `file` ORDER BY `file`.`name` ASC LIMIT 0 , 30"); WHILE ($rows = mysql_fetch_array($query)): $File_name = $rows['name']; echo "<option value=$File_name>$File_name/option> <br>"; endwhile; ?> </datalist> <input type="submit" class="button" > </form> </body> </html> Hi. I am trying to get a PHP Query to refresh every 10 seconds. I have scoured the internet for days and could not find anything of much use. Plenty of Ajax going on (whatever that is) but the scripts were immense. I only want to refresh 7 lines of PHP Query Code. Can you please tell me if this is possible? Thanks in Advance. I have a text box that I use to post comments and save them to my database. I can go to the database and the data I entered looks perfect but when I pull it out it all runs together.
This is how I entered it and the way it is in the database:
I have a text box that I use to post comments and save them to my database. This is how it came out: I have a text box that I use to post comments and save them to my database. I can go to the database, the data I entered looks perfect but when I pull it out and display it it all runs together. No new lines just all one paragraph. Can someone help? I got it indenting the paragraphs, but I get all the data back I entered all in 1 paragraph, is there something I am missing to be able to recognize the new lines?? i want the name of a picture stored in my db after i upload it the data is not stored in the db after i run this script, but i dont get errors either i print the two vars before sending them, and they get printed fine any help on this would be greatly appreciated thanks ! <?php error_reporting(E_ALL); ini_set("display_errors", 1); // INCLUDE THE CLASS FILE include('ImageLib.Class.php'); include("./includes/egl_inc.php"); $displayMessage = ''; if($_POST){ if(isset($_FILES['image_file'])){ // SEE THE MAGIC HAPPEN $destination_path = 'uploads/'; $post_file_name = 'image_file'; $width = 600; $height = 400; $scale = false; $trim = true; $uniqueName = true; $img = ImageLib::getInstance()->upload($post_file_name, $destination_path, $uniqueName)->resize($width, $height, $scale, $trim)->save(); $imgstr = mysql_real_escape_string ($img); $fileName = $_FILES['image_file']['name']; $displayMessage = '<div class="image"><img src="'.$destination_path.$fileName.'" /><br />Uploaded And Resized...With new file name : "'.$img.'"</div><br /><br />'; $playerid=$_SESSION['tid']; $matchdetails = mysql_fetch_array(mysql_query("SELECT id FROM ffa_matches WHERE status=2 and admin=$playerid")); $id = $matchdetails[id]; print $img;print $imgstr; print $id; mysql_query(" INSERT INTO ffa_screens (imgname,match) VALUES( '" . mysql_real_escape_string($imgstr) . "', '" . mysql_real_escape_string($id) . "' )"); }} ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>ImageLib Samples By Rahul Kate</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style> body{font-family: arial; font-size:12px; color:#444444; padding:20px;} li{margin-top:10px;} .image{color:green;} .image img{margin-bottom:5px;} </style> </head> <body> <h1>ImageLib | Upload Image, move it to Uploads folder and Resize it and Trim</h1> <?php echo $displayMessage; ?> <form method="post" enctype="multipart/form-data"> Select Image<br /> <input type="file" name="image_file" id="image_file" /> <br /> <br /> <input type="submit" name="submit" value="Submit" /> <br /> <br /> <a href="index.html">Back TO Home</a> </form> </body> </html> Hi, I want to develop array like following Code: [Select] $BCD=array('type' =>'TYPE1', array( 0=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), 1=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), 2=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), 3=>array('column1'=>'value1','column2'=>'value1','column3'=>'value1','column4'=>'value1','column5'=>'value1','column6'=>'value1','column7'=>0), ) )); I have written following code to achieve the same but not getting result. Code: [Select] $sql = "select * from tablename "; $result = mysql_query($sql); $k=0; while ($row = $db->mysql_fetch_array($result)) { // array_push($BCD['type'],$row['type']); $BCD1=array('type' =>$row['type'], array( $k=>array('column1'=>$row['column1'],'column2'=>$row['column2'],'column3'=>$row['column3'],'column4'=>$row['column4'], 'column5'=>$row['column5'],'column6'=>$row['column6'],'column7'=>$row['column7']) )); $k++; } I have tried several attempts and can get data to select and using echo display it, however, I need to take this data and insert it into the database in a separate table. I have the following which does hafl the job, can I get some pointers on the rest. I have looked everywhere and not found a solution, at all. // Selects the data I need <?php mysql_connect("PRIVATE INFO","PRIVATE INFO","PRIVATE INFO") or die("Could not connect: " . mysql_error()); mysql_select_db("wpdb"); $result = mysql_query("SELECT ID FROM wp_posts WHERE post_title LIKE '%future%' AND post_status = 'publish' OR post_title LIKE '%option%' AND post_content LIKE '%fundamental%' AND post_status = 'publish' ORDER BY post_date DESC"); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo $row['ID']; echo "<br />";}; ?> Thought maybe something like the following would work, but am at a loss: INSERT INTO wp_term_relationships (object_id, term_taxonomy_id, term_order) SELECT ID FROM wp_posts WHERE post_title LIKE '%future%' AND post_status = 'publish' OR post_title LIKE '%option%' AND post_content LIKE '%fundamental%' AND post_status = 'publish' ORDER BY post_date DESC while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) VALUES ($row['ID'], '25', '0') Ok so I am pretty good with mysql and performing queries to get the data that I need. However, I have a question for any of you gurus out there that may be able to help me with an issue that I always run into with certain types of queries. Say I have 2 tables like this: Galleries id name 1 My Photos Gallery Photos id gallery_id photo 1 1 photo1.jpg 2 1 photo2.jpg 3 1 photo3.jpg Now usually when I pull this info from the database I have to do 2 separate queries in order to get the data and then link them so I would do something like. <?php //make the gallery query $query = "SELECT * FROM galleries"; $results = mysql_query($query); //setup an array for the galleries data $gallery_data = array(); //loop through the galleries for($i=0;$i<mysql_num_rows($results);$i++){ //add the gallery info to the gallery data array $gallery_data[$i] = mysql_fetch_array($results); //make the photos query with the gallery id $photo_query = "SELECT * FROM gallery_photos WHERE gallery_id='".mysql_real_escape_string($gallery_data[$i]['id'])."'"; $photo_results = mysql_query($photo_query); //setup the photos array $photo_data = array(); //put the photos in the array for($n=0;$n<mysql_num_rows($photo_results);$n++){ $photo_data[$n] = mysql_fetch_array($photo_results); } //add the photos to the gallery array $gallery_data[$i]['photos'] = $photo_data; } //now to display it is like this if(is_array($gallery_data)){ foreach($gallery_data as $gallery){ echo $gallery['name']; //show the photos if(is_array($gallery['photos'])){ foreach($gallery['photos'] as $photo){ echo $photo['photo']; } } } } ?> So my question is there a way to get all of this data at one time. I know how to do multiple queries in one and to do joins but they can only return one row as far as I know of. The only other way that I know how to do this is by ordering them by name and selecting them directly from the photos table and then just getting the gallery name like this: SELECT *,(SELECT name FROM galleries WHERE id=gallery_photos.id) AS gallery_name FROM gallery_photos ORDER BY gallery_id Then I could just do one loop and see if the name has changed and if so to output the new name. But I would like to know if there is a way to get a second set of results as an array from a query so I could just select the galleries and photos all in one query. Any help is appreciated. Hey phpFreaks, im having some troubles getting my script to work correctly and im also not sure if this issue is in the right section of the forum. but heres what i have going on. I have a query result that displays a list of images with a checkbox and a couple buttons for edit and delete. everything works fine other than the checkbox stuff. I had it working when i was using a submit button, but i wanted to get rid of that button cuz it was only dealing with the checkboxes. so whats going on when using the checkboxes is that when checked or uncheck it would submit the form. It works to submit but its not submitting any data to the database. heres what i got for code for this section of checkbox. Code: [Select] <?php echo '<form method="post">'; if(isset($_POST['submit'])){ foreach($_POST['id'] as $id){ $value = (isset($_POST['location'][$id]) && $_POST['location'][$id]=="0" ? '0' : '1'); $insert = mysql_query("UPDATE items SET location='$value' WHERE id='$id'") or die('Insert Error: '.mysql_error()); } } $result = mysql_query("SELECT * FROM items") or die("Query Failed: ".mysql_error()); $counter = 0; echo '<div class="specialcontainer">'; while($row = mysql_fetch_array($result)){ list($id, $item_info, $item_img, $price, $sale, $location) = $row; if($location == '0'){ $set_checked = 'checked="checked"'; }else{ $set_checked = ''; } if($counter % 5==0) { echo '</div>'; echo '<div class="specialcontainer">'; } echo '<div class="special"><img src="../images/items/'.$item_img.'" width="130" /><br />'.$item_info.'<br />$'.$price.'<br />$'.$sale.'<br />Slide Show: <input type="checkbox" id='.$id.' value="0" name="location['.$id.']" '.$set_checked.' onchange="this.form.submit()"/><br /><input type="button" value="Edit" name="edit" id="'.$id.'" onclick="window.location.href=\'specials.php?action=edit&id='.$id.'\'"><input type="button" value="Delete" name="Delete" id="'.$id.'" onclick="window.location.href=\'specials.php?action=delete&id='.$id.'\'"><input type="hidden" name="id[]" value='.$id.' /></div>'; $counter++; } echo '</div>'; echo '</form>'; ?> This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=322237.0 |