PHP - Display Info From Database, Grouped By Field
Howdy,
I'm trying to display text from a table in a database. It's a list of quotes, so I just need to pull out the quote and the author name. However, the quote and name are not fields in the same record; they are separate records. Example data: Code: [Select] quoteid name value 1 content You guys are great! Thanks for being awesome. 1 author John Jackson 2 content Gosh you're amazing! Always been so darn helpful! 2 author Peter Davis So, I just need to rip out the data from 'content' and 'author', and then group them together based on the quoteid. This is my code thus far: $testimonial_resource = mysql_query("SELECT name, value FROM quotes GROUP BY quoteid ORDER BY author ASC") or die(mysql_error()); while ($testimonial = mysql_fetch_assoc($testimonial_resource)) { echo '<p>'.$testimonial['value']'.<br /><strong>'.$testimonial['value'].'</strong></p>'; } Any help would be greatly appreciated for this novice. Cheers. Similar TutorialsOr something like that... I am not sure how to put this.. Anyway, I'll just get started with explaining my problem. I have an admin-page in which you can delete the comments given on blogs, using checkboxes and clicking on a button with the value 'verwijderenSubmit'. The deletion part works just fine, nothing wrong. However, I also want to be able to EDIT the comments with an other button called 'bewerkenSubmit', using the same checkboxes that I use for deletion. Selecting the right CID (CommentID) is no problem, because that works the same as the deletion-part, but selecting the right textarea to update into the database is the problem... I uploaded a file here with the whole code: http://dhost.info/ddfs/myproblem.html I escaped the textarea within with square brackets, because otherwise the whole textarea would screw up.. I also added <!-- RELEVANT CODE --> to select the parts that I need to change. Well, I hope you understand my problem and can help. I'm currently trying...struggling....to teach myself PHP and I'm really bugged with this database stuff. I am slowly managing but I'm a tad bit stuck now. I want to show a specific piece of information from a table. Lets say my table is structured like so: id user email 1 Bob Bob@Name.com 2 Fred Fred@Name.com 3 Matt Matt@Name.com What would I need to do to display ONLY Freds user? One way I tried only displayed the first rows info (Bob) the second way I tried (with a while loop) only displayed the last rows info (Matt) Heres my current code: <html> <body> <?php include 'dbwire.php'; $query = mysql_query('SELECT * FROM user'); $row = mysql_fetch_array($query); while ($row = mysql_fetch_array($query)) { echo '<b>User:</b> ' . $row['user'] . '<br />'; } ?> </body> </html> Hi there. I have this simple code which displays 5 results. How can i grab each element separately instead of displaying all the results at once. Thanks:) Code: [Select] <?php $query = mysql_query("SELECT product_name, product_price FROM products WHERE product_type = 'laptop' LIMIT 5"); $numrows = mysql_num_rows($query); if ($numrows != 0) { while ($row = mysql_fetch_assoc($query)) { $product_name = $row['product_name']; $product_price = $row['product_price']; echo $product_name . '<br />'; echo $product_price . '<br /><br />'; } } ?> I have a standard form that displays users current data from a mysql database once logged in(code obtained from the internet). Users can then edit their data then submit it to page called editform.php that does the update. All works well except that the page does not display the updated info. Users have to first logout and login again to see the updated info. even refreshing the page does not show the new info. Please tell me where the problem is as i am new to php.
my form page test.php
<?PHP require_once("./include/membersite_config.php"); if(!$fgmembersite->CheckLogin()) { $fgmembersite->RedirectToURL("login.php"); exit; } ?> <form action="editform.php?id_user=<?= $fgmembersite->UserId() ?>" method="POST"> <input type="hidden" name="id_user" value="<?= $fgmembersite->UserId() ?>"><br> Name:<br> <input type="text" name="name" size="40" value="<?= $fgmembersite->UserFullName() ?>"><br><br> Email:<br> <input type="text" name="email" size="40" value="<?= $fgmembersite->UserEmail() ?> "><br><br> Address:<br> <input type="text" name="address" size="40" value="<?= $fgmembersite->UserAddress() ?> "><br><br> <button>Submit</button>my editform.php <?php $con = mysqli_connect("localhost","root","user","pass"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_query($con,"UPDATE fgusers3 SET name = '".$_POST['name']."', email= '".$_POST['email']."', address= '".$_POST['address']."' WHERE id_user='".$_POST['id_user']."'"); header("Location: test.php"); ?> Hello. I am trying to display info from two tables with this code. Code: [Select] <?php $query = mysql_query("SELECT users.username, users2.username FROM users INNER JOIN users2 ON users.id = users2.id"); $numrows = mysql_num_rows($query); if ($numrows != 0) { while ($row = mysql_fetch_assoc($query)) { $username = $row['username']; echo $username . "<br />"; } } ?> However it displays info only from one db (users). I suppose there's something wrong with Code: [Select] <?php ... while ($row = mysql_fetch_assoc($query)) { $username = $row['username']; echo $username . "<br />"; } ... ?> Any help will be appreciated. Thank you. I have created a form that i can see the form input info in to the form boxes but once submitted it is not updating or adding new input to the database. I am trying to keep it as simple as possible. I am also new at PHP.
Here is my code:
<?php // define variables and set to empty values $amp_20_parts_idErr = $part_numberErr = $locationErr = $quantityErr = ""; $amp_20_parts_id = $part_number = $discription = $location = $quantity = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["amp_20_parts_id"])) { $amp_20_parts_idErr = "ID is required."; } else { $amp_20_parts_id= test_input($_POST["amp_20_parts_id"]); } if (empty($_POST["part_number"])) { $part_numberErr = "Part number is required."; } else { $email = test_input($_POST["part_number"]); } if (empty($_POST["description"])) { $descriptionErr = ""; } else { $description = test_input($_POST["description"]); } if (empty($_POST["location"])) { $locationErr = "A location is required."; } else { $location = test_input($_POST["location"]); } if (empty($_POST["quantity"])) { $quantityErr = "Quantity is required"; } else { $quantity = test_input($_POST["quantity"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <div id="update_form"> Please follow instructions for updating the data base.<br>instructional text goes here.<br/><br/> <table><tr><form method="POST" action="new path"> <td>ID: <input name="amp_20_parts_id" type="text"><span><?php echo $amp_20_parts_idErr; ?></span><br/><br/></td> <td>Part Number: <input name="part_number" type="text"><span><?php echo $part_numberErr; ?></span><br/><br/></td> <td><label>Discription: <textarea name="description" rows="3" col="20"></textarea> <br/><br/></td> <td>Location: <input name="location" type="text"><span><?php echo $locationErr;?> </span><br/><br/></td> <td>Quantity: <input name="quantity" type="text"><span><?php echo $quantityErr; ?> </span><br/><br/></td><br/> <td><input type="submit"></td> </form></tr></table> <?php $con=mysqli_connect("server","user","password","db"); // Check connection if (mysqli_connect_errno()) { echo("Connect failed: %s\n", mysqli_connect_error()); // escape variables for security $amp_20_parts_id = mysqli_real_escape_string($con, $_POST['amp_20_parts_id']); $part_number = mysqli_real_escape_string($con, $_POST['part_number']); $discription = mysqli_real_escape_string($con, $_POST['description']); $location = mysqli_real_escape_string($con, $_POST['location']); $quantity = mysqli_real_escape_string($con, $_POST['quantity']); $sql="INSERT INTO amp_20 (amp_20_parts_id, part_number, description, location, quantity) VALUES ('$amp_20_parts_id', '$part_number', '$description', '$location', '$quantity')"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } echo "1 record added"; mysqli_close($con); } ?> Hi, I'm working with sessions for the first time and have been able to put a member's id into the database. However, when I try and put their display name into the database I got a message saying Unknown column 'xyz' in 'field list' xyz was the display name for the session. Just can't seem to see what I'm doing wrong. In the code below, I even tried changing $_SESSION['member_display_name'] to $_SESSION['member_id'], in which case the correct id was inserted into both the member_id and the member_display_name fields in the database, so I know the table is set up correctly. Any tips? Code: [Select] //**********************SEND TO DATABASE**************************** include 'mysql_connect.php'; $query = "INSERT INTO uploads (date, member_id, upload_name, upload_title, upload_type, subject, topic, year, status, keywords, description, member_display_name, firstname, lastname)" . "VALUES (NOW(), ".$_SESSION['member_id'] . ",'$upload_nameX', '$upload_title', '".$EXPLODED_STRING[1]."', '$subject', '$topic', '$year', '$status', '$keywords', '$description', ".$_SESSION['member_display_name'] . ", '$firstname', '$lastname')"; //if($query){echo 'data has been placed'} mysql_query($query) or die(mysql_error()); $upload_id = mysql_insert_id(); //***********************END OF DATABASE CODE*********************** Hello all, I have a directory page that is populated with a foreach loop pulling info from a db table. I want to make a "Download Directory pdf" button that will print out the directory entries in a nicely formatted way. The thing is that the foreach loop uses an OO call to what every template is being used for the HTML display: foreach ( (array) $results as $row) { ... $out .= '<div class="cn-list-row' . $alternate . ' vcard ' . $template->slug . ' ' . $entry->getCategoryClass(TRUE) . '">' . "\n"; $out = apply_filters('cn_entry_before', $out, $entry); ob_start(); include($template->file); $out .= ob_get_contents(); ob_end_clean(); $out = apply_filters('cn_entry_after', $out, $entry); $out .= '</div>' . "\n"; } $out .= '<div class="clear"></div>' . "\n"; $out .= '</div>' . "\n"; $out = apply_filters('cn_list_after', $out, $results); return $out; } Any Ideas?? Well, I have been able to create a registration and login page. Now I am trying to make an "Edit Profile" page but I can't seem to be able to pull up their primary key field which is called "userID" and I need help doing this. How would I get it from the MySQL database? I have a 'user' table and a display users page. How would I display them in alphabetical order by their username? Heres my current basic display page: <?php include 'dbwire.php'; include 'header.php'; $query = mysql_query('SELECT * FROM user'); while ($row = mysql_fetch_array($query)) { echo '<b>Username:</b> ' . $row['user'] . '<br />'; echo '<b>Real Name:</b> ' . $row['name'] . '<br />'; echo '<b>Email:</b> ' . $row['email'] . '<br />'; echo '<b>Location:</b> ' . $row['location'] . '<br /> <hr>'; } ?> Theres also an id row but since user wouldn't be added alphabetically I wouldn't be able to order them by id. Sir/ma'am,
With the script I'm using to run my website, I've been trying to add an additional feature for the users to add/edit. I'll try to provide as much info as I can, hopefully it'll help.
Here is the code I'm using to display the user's unique info from the db.
<a class="wallet-edit"><?php echo $_SESSION['simple_auth']['INFO']?></a>That displays the user's info from the column 'INFO' perfectly. It's also a js popup to a menu to where I'm hoping to add a single textbox to edit the INFO. The script uses a similar function to edit the password with a popup. I've tried modifying the code to edit the INFO column but it doesn't work. Here is the default code it has to edit the password. I'm not sure if it can be changed to edit another column or needs a new piece of code for that. // user edit $('body').on('click', '.username-edit', function() { $('#modal').html(' '); var output = '<div class="modal-content"><h5><?php echo lang::get("Change password")?></h5><hr />'; output += '<h5><?php echo lang::get("New password:")?></h5><input type="password" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />'; output += '<h5><?php echo lang::get("Confirm password:")?></h5><input type="password" name="password2" id="password2" value="" class="text ui-widget-content ui-corner-all" />'; output += '</div>'; output += '<div class="modal-buttons right">'; output += '<button id="confirm-button" type="button" class="nice radius button"><?php echo lang::get("Change")?></button>'; output += '</div>'; output += '<a class="close-reveal-modal"></a>'; $('#modal').append(output); $('#second_modal').hide(); $('#modal').reveal(); $('#confirm-button').click(function(){ $('#password').css('border-color', '#CCCCCC'); $('#password2').css('border-color', '#CCCCCC'); var password = $('#password').val(); var password2 = $('#password2').val(); if(typeof(password) === 'undefined' || password == ''){ $('#password').css('border-color', 'red'); return false; } if(password != password2){ $('#password2').css('border-color', 'red'); return false; } password_data = encodeURIComponent(password); $.post("<?php echo gatorconf::get('base_url')?>", { changepassword: password_data} ).done(function(data) { // flush window.location.href = '<?php echo gatorconf::get('base_url')?>'; }); }); });If the code above can be edited to work with what I'm trying to do, it of course only needs one textbox and doesn't have to be confirmed by a second input. Please help! Thanks! Hi Im having some trouble implementing info into a database Hello I'm trying to set up a user area for my site where it displays the current logged in users ranking and other information in the future. <? ini_set('display_errors', 1); require_once "header.php"; $sql = "SELECT * FROM users WHERE username = ?"; if($stmt = mysqli_prepare($link, $sql)){ mysqli_stmt_bind_param($stmt, 's', $_SESSION['username']); if(mysqli_stmt_execute($stmt)){ $info = mysqli_fetch_array($stmt); echo "Current rank:" . $info['rank']; } else { echo "Can't find user"; } } mysqli_stmt_close($stmt); ?> That's the code I currently have but it gives me the error "but get an error message of mysqli_fetch_array() expects parameter 1 to be mysqli_result" My data input form is not working with the first few people who have tried to use it. I think it is because they are putting ' or " or some other character that is not allowed into the database. Any ideas how I can fix it? I have two tables. Table Name:Users Fields: User_name user_email user_level pwd 2.Reference Fields: refid username origin destination user_name in the users table and the username field in reference fields are common fields. There is user order form.whenever an user places an order, refid field in reference table will be updated.So the user will be provided with an refid Steps: 1.User needs to log in with a valid user id and pwd 2.Once logged in, there will be search, where the user will input the refid which has been provided to him during the time of order placement. 3.Now User is able to view all the details for any refid 3.Up to this we have completed. Query: Now we need to retrieve the details based on the user logged in. For eg: user 'USER A' has been provided with the referenceid '1234' during the time of order placement user 'USER B' has been provided with the referenceid '2468' during the time of order placement When the userA login and enter the refid as '2468' he should not get any details.He should get details only for the reference ids which is assigned to him. Hi there, I am using this code to send the users email address to the database. That works fine, but i keep getting blank info added to the database. Does anyone know how i can stop this? <?php $con = mysql_connect("*","*","*"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ogs_mailinglist1", $con); $sql="INSERT INTO mailinglist (email) VALUES ('$_POST[rec_email]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } mysql_close($con); ?> Thanks, I've created a function to update the database with the information from the text file...I've already got additional code (not posted here) that displays the orders that have NOT been shipped (and works beautifully). Then when they click the button it should process the text file and update the database (input the tracking number into the database) and change the order status and send an email to the customer, I know I've got something mixed up because it's not working... function process_shipping($ordernumber, $status=''){ $order_updated = false; $check_status_query = tep_db_query("select customers_name, customers_email_address, orders_status, date_purchased from " . TABLE_ORDERS . " where orders_id = '" . $ordernumber . "'"); $check_status = tep_db_fetch_array($check_status_query); $orders_statuses = array(); $orders_status_array = array(); $orders_status_query = tep_db_query("select orders_status_id, orders_status_name from " . TABLE_ORDERS_STATUS . " where language_id = 1"); while ($orders_status = tep_db_fetch_array($orders_status_query)) { $orders_statuses[] = array('id' => $orders_status['orders_status_id'], 'text' => $orders_status['orders_status_name']); $orders_status_array[$orders_status['orders_status_id']] = $orders_status['orders_status_name']; } if ($status!==''){ if ($check_status['orders_status'] !== $status) { tep_db_query("update " . TABLE_ORDERS . " set fedex_track_num = '" . $tracking . "'orders_status = '". $status . "', last_modified = now() where orders_id = '" . $oID . "'"); $customer_notified = '0'; $notify_comments = ''; $email = STORE_NAME . "\n" . EMAIL_SEPARATOR . "\n" . EMAIL_TEXT_ORDER_NUMBER . ' ' . $oID . "\n" . EMAIL_TEXT_INVOICE_URL . ' ' . tep_catalog_href_link(FILENAME_CATALOG_ACCOUNT_HISTORY_INFO, 'order_id=' . $oID, 'SSL') . "\n" . EMAIL_TEXT_DATE_ORDERED . ' ' . tep_date_long($check_status['date_purchased']) . "\n\n" . $notify_comments . sprintf(EMAIL_TEXT_STATUS_UPDATE, $orders_status_array[$status]); tep_mail($check_status['customers_name'], $check_status['customers_email_address'], EMAIL_TEXT_SUBJECT, nl2br($email), STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS); $customer_notified = '1'; tep_db_query("insert into " . TABLE_ORDERS_STATUS_HISTORY . " (orders_id, orders_status_id, date_added, customer_notified, comments) values ('" . (int)$oID . "', '" . tep_db_input($status) . "', now(), '" . tep_db_input($customer_notified) . "', '" . tep_db_input($comments) . "')"); $order_updated = true; } } } if ($_POST['update']=='1') { echo '<div class="dataTableContent" align="left">'; $arr=file("/home/onest4/public_html/beta/fedex.txt"); $x=1; foreach($arr as $str){ if (trim($str) != ''){ if ($x > 3){ list($tracking,$oID)=explode(" ",$str); if(ctype_digit($tracking)){ echo "Order# $oID, <b>$tracking</b> (DATABASE UPDATED)<br>"; } }else{ $x++; continue; } } } } I have two tables. Table Name:Users Fields: User_name user_email user_level pwd 2.Reference Fields: refid username origin destination user_name in the users table and the username field in reference fields are common fields. There is user order form.whenever an user places an order, refid field in reference table will be updated.So the user will be provided with an refid Steps: 1.User needs to log in with a valid user id and pwd 2.Once logged in, there will be search, where the user will input the refid which has been provided to him during the time of order placement. 3.Now User is able to view all the details for any refid 3.Up to this we have completed. Query: Now we need to retrieve the details based on the user logged in. For eg: user 'USER A' has been provided with the referenceid '1234' during the time of order placement user 'USER B' has been provided with the referenceid '2468' during the time of order placement When the userA login and enter the refid as '2468' he should not get any details.He should get details only for the reference ids which is assigned to him. well I know the standard way of retrieving mysql data was through the following codes: Code: [Select] $query = "SELECT * FROM {$tablename} WHERE columnmame = '{$var}'"; $result = mysql_query($query); $row = mysql_fetch_array($result); This will return all properties inside a table row by an associative array indexed by column names. I am, however, wondering if there is an easier way to retrieve database info from more than one table. For now, what I am doing is: Code: [Select] $result = mysql_query( "SELECT * FROM {$tablename} WHERE columnmame = '{$var}'"); $row = mysql_fetch_array($result); $result2 = mysql_query( "SELECT * FROM {$tablename2} WHERE columnmame2 = '{$var2}'"); $row2 = mysql_fetch_array($result2); which is a bit tedious and can cause problems when two or more coders work on the same project(it will be difficult to tell what is $row1, $row2 and $row3...). Is there away to write a simpler code than the one above? I mean, if it is possible to run mysql_fetch_array only once and retrieve database info from multiple tables? Hi, I have a website where users can log on and edit their profile pic, name, biography etc. I was wondering about the correct way to:- Add data to the database through forms (Register.php) Display the data on a page Using mysql escape sting, however, the way I am currently using will display a '\' before any ' symbol. So it's >> it\'s ... Here is a snippet of the code I am using... Code: [Select] //insert data $about1 = mysql_real_escape_string($_POST['about']); //get $query = mysql_query("SELECT * FROM `staff` WHERE username='$username'"); $row = mysql_fetch_array($query); $about = $row['about']; echo $about; |