how to make multiple queries in PHP - php

im very new to this and have a very basic knowledge php and SQL this is my first website, please could some one help.
I currently have information being pulled from my database to my website, which is good.
however i want to run another couple of queries on the same html page one that will display a list of the latest 5 entries in the database and sort them by 'location_id' descending, the other will display a list of 5 entries and display them random every time the page refreshes. see my code below:
?php
require "connect.php";
$query = "select * from location";
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['location_id'] ?>
?php } ?>
Also when i was experimenting trying to solve this myself, i duplicated the loop shown above in a different location, and it would not display anything, can sone one explain why?
Thanks Guys

It needs reset,
mysql_data_seek( $result, 0 );

i have just seen the syntax.
i guess ";" is missing in
should be
<?php echo $row['location_id'] ; ?>

You could reset the query to do this or
create a new query and result with different names and then when the page runs have it select one of the queries to run.
$query1 = "select * from location";
$result1 = #mysql_query($query1, $connection);
or die ("Unable to perform query<br>$query1");
resetting might be easier but this is an option too

Related

Echo out user information in the same table to their page base on their store information without echoing out the same information to another user

First of all I stored users in the same table and I created a page called welcome.php, where I want it to be echoing out user info from MySQL based on their entry.
Now when I created first user and echo it out to this welcome.php, it comes out from the table, and if I create another user info in the same table for it to echo out at the same welcome.php based on the user login info such as, if I create a user called John Fred etc and a user called Michael Kenneth etc.
So user John Fred comes out to the welcome.php with its information from the same table, and then user Michael Kenneth doesn't come to welcome.php when i sign with user Michael Kenneth instead it shows only user John Fred. I don't know where this error comes from; maybe from the login.php, or from welcome.php.
Here is my code echoing in welcome.php
<?php
$tnumber2 = "{$_SESSION['tnumber2']}";
// Connect to the database
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$Tname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<? echo $rows['tnumber2']; ?>
Another script for other user info which I store for another table:
<?php
// Connect to the database
$tnumber2 = "{$_SESSION['tnumber2']}";
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$UPname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
?>
<?php
while($rows=mysql_fetch_array($result)){ // Start looping table row
?>
<? echo $rows['pdate']; ?>
<?php
// Exit looping and close connection
}
mysql_close();
?>
And here is my login.php in this case am using one input form:
<?php
session_start();
ob_start();
?>
<?php
if ($_POST['submit']) {
$tnumber2 = $_POST['user'];
if ($tnumber2) {
require("connect.php");
$query = mysql_query("SELECT * FROM users WHERE tnumber2='$tnumber2'");
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_assoc($query);
$id = $row['id'];
$tnumber2 = $row['tnumber2'];
if ($tnumber2 == $tnumber2) {
$_SESSION['id'] = $id;
$_SESSION['tnumber2'] = $tnumber2;
header("Location: welcome.php");
}
}
else
include "error.php";
}
}
?>
I have tried all I can on this, maybe I might be a fool to think that such thing is possible but I am not a PHP professional, just a learner, please any help will be gladly appreciated.
Assuming the session has indeed stored the data of the logged-in user, you need to change "welcome.php" so it reads the correct user with a WHERE clause:
<?php
// Retrieve the ID of the user (and untaint it too)
$id = (int) $_SESSION['id'];
// Connect to the database (I've removed the unnecessary quotes)
$db = mysql_connect($Sname, $Uname, $Pname) or die("Could not connect to the Database.");
$select = mysql_select_db($Dname) or die("Could not select the Database.");
// Here is the query from the users table, we're selecting one user here
$sql="SELECT * FROM `users` WHERE `id` = $id;";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
?>
<!-- Let's see what is in rows now, should be just one record -->
<?php print_r($rows) ?>
I would advise that you try to understand each part of the code above, and indeed the same for the code you have - don't just copy-and-paste without knowing what each bit does. If you get stuck on something, don't be afraid to look it up in the manual!
I've used print_r to just dump the row result - you can use the contents of that to determine what columns and other data you wish to extract out of it. After you have done that, the print_r can be removed.
Bear in mind that your login is not testing for password correctness - it only checks that someone has entered a particular username in login.php. If you want users to log on with a username and password, that needs to be designed and implemented as well. There are many questions on this site with best-practice techniques on how to do that, if that's of interest to you.
It has, incidentally, been rather difficult to understand what you are doing. I don't think this is a problem with your English, which seems fine to me. Rather, it's worth remembering to write in short sentences (no more than 20 words, say) and short paragraphs (no more than 4 or 5 sentences). And keep your descriptions as short as you can - it makes the difference between people helping you and their deciding they don't understand what you are trying to do. I expect this advice would be just as relevant in your native language as well!
Also, remember to add as much useful information to a question as you can, and if people ask for clarification, make sure you answer all their questions. Remember that people here are volunteers, and you need to make their job as easy as possible.

List columns contents from sql table

I want to list the contents of a 'name' column from an sql table on a HTML/PHP web page. This page currently allows me to create records, but is there a way of listing the records by name only, and displaying them somewhere specific on the HTML page?
The comments didn't seem to answer 100% to my knowledge so maybe this broad answer might help.
If you want to grab all the names located in a specific SQL table first make sure to connect to your database using
mysql_connect('SERVER', 'USER', 'PASSWORD');
mysql_select_db('DATABASENAME');
After you have connected you ran run queries to your database as stated. For your example it would be something like this:
//Query to get values
$query= mysql_query("SELECT name FROM TABLE_NAME");
//Places all query results into an array "row"
while($row = mysql_fetch_assoc($query)){
//Prints values as though it were HTML
echo $row['name']."<br>";
}
Here's an example of getting one name back from the users table and storing it in a variable to use later in the page.
<?php
$query = mysql_query("SELECT name FROM Users");
$result = mysql_fetch_array($query);
$name = $result['name'];
?>
<div class="greeting">Hello <?php echo $name; ?></div>
In a more advanced case you can also store variables in sessions (cookies) so that you can use them throughout your website (including subdomains) without having to re-query the database each time
<?php
session_start();
$query = mysql_query("SELECT name FROM Users");
$result = mysql_fetch_array($query);
$_SESSION['name'] = $result['name'];
?>
Now whenever you want to grab the variable you just got from the query simple do <?php $_SESSION['name']; ?> Just make sure that you have session_start() at the top of the page (my suggestion is place in a header file and include the header file in all pages)
Make sure your file is a .php file and you place the code about in the proper <?php ?> tags

php mysqli help, first line in DB not being returned?

Here is my code
<?php require_once 'connect.php';
$sql = "SELECT * FROM `db-pages`";
$result = $mysqli->query($sql) or die($mysqli->error.__LINE__);
while ($row = $result->fetch_assoc()) {
echo($row['pagetitle'].' - To edit this page click here<br>');
}
}
?>
I've added a couple more rows to the Database and it's returning them all, apart from id=1 in the DB. Any idea why?
try it like this:
while ($row = $result->fetch_assoc()) {
echo($row['pagetitle'].' - To edit this page click here<br>');
}
Double check the title and ensure it's got nothing that will affect php out-putting it.
Also escape all of your DB output using htmlentities, it makes for good practise in the event someone gets creative.

CMS homepage in php

I am working on something it has 2 pages. One is index.php and another one is admin.php.I am making CMS page where you can edit information on the page yourself. Then it will go to the database, where the information is stored. I also have to have it where the user can update the information on the page. I am getting a little bit confused here.For instance here I am calling the database and I am starting a function called get_content:
<?php
function dbConnect(){
$hostname="localhost";
$database="blank";
$mysql_login="blank";
$mysql_password="blank";
if(!($db=mysql_connect($hostname, $mysql_login, $mysql_password))){
echo"error on connect";
}
else{
if(!(mysql_select_db($database,$db))){
echo mysql_error();
echo "<br />error on database connection. Check your settings.";
}
else{
return $db;
}
}
function get_content(){
$sql = "Select PageID,PageHeading,SubHeading,PageTitle,MetaDescription,MetaKeywords From tblContent ";
$query = mysql_query($sql) or die(mysql_error());
while ($row =mysql_fetch_assoc($query,MYSQL_ASSOC)){
$title =$row['PageID'[;
$PageHeading =$row['PageHeading'];
$SubHeading = $row['SubHeading'];
$PageTitle = $row['PageTitle'];
$MetaDescription =$row['MetaDescription'];
$MetaKeywords = $row['MetaKeywords'];
?>
And then on the index page and I am going to echo it out in the spot that someone can change:
<h2><?php echo mysql_result($row,0,"SubHeading");?>A Valid XHTML and CSS Web Design by WG.</h2>
I do know that the function is not finished I am still working on that part. What I am wondering is am I echoing it out right or I am way off. This is my first time messing with CMS in php and I am still learning it. I am working with navicat and text pad on this, yes I know it is old school but that is what I am being shown with. But my index is a form not a blog. I have seen many of CMS pages for blogs not to many to be used with forms. Any input will be considered thanks for reading my question.
Your question is a bit confusing and your code very incomplete. I'ts hard to say if you do it the right way since I don't see the rest of the script. You need to connect to the database there as well and get your data. The $row variable only exists in the while statement inside you function get_content() though.
You could complete the get_content() and use it in the index.php as well. Remember that the variables you define inside a function only is available there though. If you need the data outside that function you need to return the values you need and save them to some other variable there. Put if you do the same as you've started doing in the get_content() function in index.php, then you just have to echo the variables you define. Like this:
<h2><?php echo $SubHeading; ?></h2>
or you could also do it like this somewhere inside the php tags:
echo '<h2>{$SubHeading}</h2>';
I hope that answers your question.
EDIT:
What you need in the index.php page is exactly what you seem to be doing in the admin file. You need to connect to db using mysql_connect() and select db with mysql_select_db(). You then need to select the data from the db using the appropriate query with $query = mysql_query($sql). If it's more then one row you want to display you need to put it in a while loop otherwise (which seems to be the case here) you just need to do one $row = mysql_fetch_assoc($query). After that you can get the data using $row['column_name']. If you have more than one row you can just use $row['column_name'] in side the while loop to get each consecutive row's data.
Here is an example index.php:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password') or
die('Could not connect: ' . mysql_error());
mysql_select_db('database_name')) or die('Could not select database: ' .
mysql_error());
$sql = "SELECT SubHeading FROM tblContent WHERE PageID='1' LIMIT 1;";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo '<h2>{$row[\'SubHeading\']}</h2>';
mysql_close();
?>
This is just what you need to display the SubHeading from you database. You probably also need to handle your form and save the submitted data to the database in your admin.php file.

redirect page after completing update or insertion

There are two pages called result.php and getdata.php
the result.php will show a search results. if search term is not in database then it should redirect to getdata.php .
getdata.php will analyze query and grab data from other resources then insert / update MySQL database. immeadiate after inserting/updating database then it should redirect to result.php
Finally result.php will show result as per the query term.
how can be this done with php and mysql??
header('location: url');
This should help you, just put instead of url something like results.php.
Any issues with redirecting let me know, it could be due to output_buffering being turned off.
Check out the PHP docs for mysql_num_rows and header. Below is almost straight from the docs...
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
if ( $num_rows > 0 ){
// do something with your SQL result here
} else {
// redirect to result.php if no rows were found.
header('location: result.php');
}
?>
actually, I'd put all the code in one php-page, then you wouldn't have to redirect, and easier to maintain.
//if no record from search, do the insert now...
code...
//end insert
regards,
//t

Categories