Some may know my script Basic Announce, I am trying to get the latest news entry that has been sent through so only the last know entry is called up.
In this code block is the news caller that I originally created but this decides to call all of the entries but thats for the Admin to see, but I need the last entry to be called in this file: news.php
<?php
// Connects to your Database
mysql_connect("$server","$usr","$pswd") or die(mysql_error());
mysql_select_db("$db") or die(mysql_error());
$data = mysql_query("SELECT * FROM announcements")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Announcement:</th><td>".$info['Announcement'] . "</td> ";
Print "<br>";
Print "<th>Submitted By:</th> <td>".$info['Submitted'] . "</td> ";
}
;
?>
How would I go about select the last know entry I also include my database tables sql code.
Here is the Basic Announce.sql code
CREATE TABLE IF NOT EXISTS `announcements` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Announcement` text NOT NULL,
`Submitted` text NOT NULL,
`Date_time` date NOT NULL,
PRIMARY KEY (`id`)
);
Is it possible to pull the last record using my Primary Key "id"?
Any help on this troubling matter would be greatly appreciated as I am still learn PHP via self-taught and inspiration.
Many Thanks
Order it by the id descending:
$data = mysql_query("SELECT * FROM announcements ORDER BY id DESC LIMIT 1");
I also added LIMIT 1 because you only want to retrieve the first row in the set. Given you only want a single row, you don't need the while loop, just make a single call to fetch:
$data = mysql_query("SELECT * FROM announcements ORDER BY id DESC LIMIT 1");
if($data && mysql_num_rows($data) == 1) // check for success and a row found
{
$info = mysql_fetch_array( $data );
Print "<tr>";
Print "<th>Announcement:</th><td>".$info['Announcement'] . "</td> ";
Print "<br>";
Print "<th>Submitted By:</th> <td>".$info['Submitted'] . "</td> ";
}
else
{
// no rows or an error occurred
}
Side notes:
The mysql_* library is deprecated. For new code you should consider upgrading to PDO or MySQLi.
.. or die(mysql_error()) should be avoided. A better option is trigger_error(mysql_error()).
try out this.
SELECT Top 1 * FROM announcements order by id desc
Related
I am a novice when it comes to PHP but I don't understand if my syntax is wrong in this statement, or how would I grab an int from my MySQL server.
I know that my server credentials are working fine. How would I fix this statement to give me a returned integer of the number of reviews in the userinfo table?
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$amountofreviews = $numberofpreviousreviews + 1;
$query2 = mysql_query("ALTER TABLE userinfo ADD `amountofreviews` VARCHAR(10000)") or die(mysql_error()); //Make another column in database for the new review
You need to fetch your results after you run your query. There are several ways to do this but using mysql_fetch_assoc() will work for you.
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$row = mysql_fetch_assoc($numberofpreviousreviews);
$amountofreviews = $row['number_of_reviews'] + 1;
FYI, you shouldn't be using mysql_* functions anymore. They are deprecated and going away. You should use mysqli or PDO.
Assume you have a table userinfo which has the following structure and data :
Scenario #1 :
If you want to retrieve the all number_of_reviews, then do like this,
$query = "SELECT `number_of_reviews` FROM `userinfo`";
$result = mysqli_query($db,$query);
while ($row = mysqli_fetch_assoc($result)) {
echo "Number of reviews : " . $row['number_of_reviews'] . "<br/>";
}
It will give you,
Number of reviews : 20
Number of reviews : 40
Since, the result has many rows, it will display like above.
Scenario #2:
If you want to retrieve only the specific number_of_reviews for some user id (which is unique). I take id as 1 as a example here. Then do like,
$query2 = "SELECT `number_of_reviews` FROM `userinfo` WHERE `id` = 1";
$result2 = mysqli_query($db,$query2);
while ($row2 = mysqli_fetch_assoc($result2)) {
echo $row2['number_of_reviews'] . "<br/>";
}
This will print,
20.
Because, number_of_reviews is 20 for id 1.
I know this question has been asked multiple times on here but each one is a little different.
I have a table in my database with the columns entry_id(INT- Auto_Increment), user_id(INT), firstname(VARCHAR), lastname(VARCHAR) and comment(VARCHAR).
My script is pretty much a very basic timesheet I have tried creating, the user_id, firstname and lastnames are set when the user visits the script. So what I need to do is check the last comment cell for that user to see if the comment is either "in" or "out".
Whenever I try building my query and checking if the last comment in that users field is either in or out, I visit my script and it doesn't print the comment, what am I doing wrong?
$userid = $_SESSION['user_id'];
$query = mysqli_query($mysqli, "SELECT entry_id, user_id FROM timesheet WHERE user_id = '$userid' ORDER BY entry_id DESC LIMIT 1") or die('Error: ' . mysqli_error($mysqli));
if(mysqli_num_rows($query)>0){
while ($row = mysqli_fetch_array($query, MYSQL_ASSOC)) {
echo '<pre>';
print_r($row);
echo '</pre>';
$clock = $row['comment'];
echo $clock . ' Last entry';
}
Couple of notes:
I AM connected to the database and get a simple query to work.
The userid session is set.
Prior to asking this question I looked at the answers here and here.
Here is what $row is printing, notice how comment is empty although I know I have a value in the database.
Array
(
[entry_id] => 4
[user_id] => 3
[comment] =>
)
Just as you seen on comments, you trying to access an index which is not included with the one you queried that's why you dont get any results.
$userid = $_SESSION['user_id'];
$query = mysqli_query($mysqli,
"SELECT
entry_id,
user_id,
comment <-- you're trying to access comments, but didn't include that column in the query
FROM timesheet
WHERE user_id = '$userid' ORDER BY entry_id DESC LIMIT 1")
or die('Error: ' . mysqli_error($mysqli));
if(mysqli_num_rows($query) > 0){
while ($row = mysqli_fetch_assoc($query)) {
echo $row['comment'] . ' Last entry <br/>';
}
}
If you've had turn on error reporting:
error_reporting(E_ALL);
ini_set('display_errors', '1');
You should have seen that undefined index comment.
I have transfered variable values to another page, but now I'm trying to show the database content relevant to this value.
Workflow:
There's a form that I enter a new Company. I have entered Company1. It's in companies database.
There's another form, that I list in an OPTION tag all the recorded companies. In this form, I record the company's employees information, including the chosen companies option.
There's a page that lists all the recorded companies. Each one has a link (company.php?name=$companyName).
The companies' names are passed via GET to another page.
This other page is called "company.php" and need to show the company's information (other fields in database).
It also has to show other table record, like "employees". It must list all the employees that has de same company's name, passed via GET.
The question is: how do I proceed with step 5 and 6? I tried using this select, but didn't work:
$query = mysql_query("SELECT employeeName FROM employeeForm WHERE companyName='$employeeName'") or die(mysql_error());
It's really difficult for me to be clear at this, I'm sorry if it's not understandable. 'Been working around this issue for hours.
I appreciate any help!
EDIT: Used method:
include("connect.php");
$companyName=$_GET['companyName'];
$result = mysql_query("SELECT * FROM employeeList WHERE company = '$companyName'");
while($result = mysql_fetch_array($query))
{
echo '<div class="form">'.$result['employeeName'].'</div>';
}
ANSWER:
your code:
while($result = mysql_fetch_array($query))
{
echo '<div class="form">'.$result['employeeName'].'</div>';
}
should be:
while($res = mysql_fetch_array($result)) //changed to the name of the variable that stores the query (can't store the array in a variable named after the query so i've changed it to $res...)
{
echo '<div class="form">'.$res['employeeName'].'</div>';
}
OLD:
Are you retrieving the result of the query? To return just one result use the mysql_fetch_assoc() function and to return an entire row (or more variables) use mysql_fetch_array().
Example:
$test = mysql_fetch_assoc($query);
$array = mysql_fetch_array($query);
Ps. To Select an array use a syntax similar to :
"SELECT * FROM table WHERE var = condition"
PPs. This was taken from php.net:
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
EDIT:
Your code:
$query = mysql_query("SELECT employeeName FROM employeeForm WHERE companyName='$employeeName'") or die(mysql_error());
You treat the variable as text (variable name not content :) )... use:
WHERE '".$employeeName."'
to parse variables into query... (observe the double quotes)
Also... to access the results of the query use something like:
$array['COLUMN NAME'];
..assuming you use : $array = mysql_fetch_array($query);
I'd highly recommend you use PDO, here's a sample using PDO.
<?php
$dsn = 'mysql:dbname=so;host=localhost';
$user = 'root';
$password = '';
// try to connect.
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit(1);
}
// the sql which gets all employees for this company.
$getEmployeesSQL = '';
$getEmployeesSQL .= ' SELECT c.name AS company_name, e.name AS employee_name, e.salary, c.location ';
$getEmployeesSQL .= ' FROM company c';
$getEmployeesSQL .= ' LEFT JOIN employee e';
$getEmployeesSQL .= ' ON c.id = e.company_id';
$getEmployeesSQL .= ' WHERE c.name = :cname';
// sql to get company data.
$companyDataSQL = "SELECT * FROM company WHERE name = :cname";
// prepare the sql.
$stmtOne = $dbh->prepare($getEmployeesSQL);
$stmtTwo = $dbh->prepare($companyDataSQL);
// execute
$stmtOne->execute(array(':cname' => $_GET['company']));
$stmtTwo->execute(array(':cname' => $_GET['company']));
// print results.
$employees = $stmtOne->fetchAll(PDO::FETCH_ASSOC);
$companyData = $stmtTwo->fetchAll(PDO::FETCH_ASSOC);
/* * ****************************************** */
/* Iterate and print HTML table. */
/* * ****************************************** */
$html = '<table border="1">';
foreach ($companyData as $company) {
foreach ($company as $field => $value) {
$html.= "<tr><td>$field</td><td>$value</td></tr>";
}
}
$html . '</table>';
echo $html;
$html = '<table border="1">';
foreach ($employees as $row) {
$html.= '<tr><td>' . implode('</td><td>', array_values($row)) . '</td></tr>';
}
$html . '</table>';
echo $html;
What this snippet does is that it prints the company data in a table and then gets employee data using company name.
The table structure I'm using is as follows:
CREATE TABLE `company` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`location` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `employee` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`salary` bigint(12) DEFAULT NULL,
`company_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_company` (`company_id`),
CONSTRAINT `fk_company` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
This returns data as follows: (Not pretty, but this'll have to do for now.)
As I understand it you have two tables - one for companies and one for employees, with the obvious possibility that there are multiple employees for each company. If what you're trying to do is produce a list of employees for a given company, you need to use the Company Name (assuming it's unique) in your SQL query.
$companyName = $_GET('companyName');
$result = mysql_query("SELECT * FROM employeeList WHERE company = '$companyName'");
That will give you a list of employees (with all their info) associated with that particular company.
EDIT:
To loop through the query and print out the results, you can use something like to following (along with what's already above):
echo "<table><tbody>";
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>" . $row['employee_first_name'] . " " . $row['employee_last_name'] . "</td></tr>";
}
echo "</tbody></table>
I am trying to read in an XML file and compare it to fields in an existing database.
If the ID in the database doesn't exist in the XML file, then the whole row corresponding to the Id is no longer valid and will be deleted.
To do this I read in each line of the XML from start to finish in a while statement.
As step one I am trying to do a simple compare, and echo if it finds an Id in the database that doesn't exist in the XML.
I know there are some Ids in the database that don't exist in the XML, but the following code is not displaying them.
I've got three questions, firstly how would I display the Id that is pulled from the database, and secondly why isn't this code finding any ids that are not in the XML?
The final question is am I going about this completely the wrong way and is there a better way to do it!
$sql_result = mysql_query("SELECT id FROM `list` WHERE id = $id") or die(mysql_error());
if($sql_result)
{
// echo $id . " Id exists " . $sql_result["id"] . "\n";
}
else
{
echo "Id no longer exists" . $id . "\n";
}
Your code isn't finding what you expect because even though the id may not be found, $sql_result still holds a TRUE value because the query was successful. Instead, check if myqsl_num_rows() > 0
if($mysql_num_rows($sql_result) > 0)
{
// echo $id . " Id exists "\n";
//Now, to print the id, you need to fetch it from `$sql_result`,
//which is just a resource at this point:
$row = mysql_fetch_assoc($sql_result);
echo $row['id'];
}
This is the proper way to check:
$sql_result = mysql_query("SELECT `id` FROM `list` WHERE `id` = ".intval($id,10)." LIMIT 0,1");
if(is_resource($sql_result) && mysql_num_rows($sql_result) > 0 ){
$sql_result = mysql_fetch_assoc($sql_result);
echo $id . " Id exists " . $sql_result["id"] . "\n";
}
else{
echo "Id no longer exists" . $id . "\n";
}
You should check the number of rows returned using mysql_num_rows(). Otherwise, you are simply checking to see if the query executed without any error.
if($sql_result)
to
if(mysql_num_rows($sql_result))
You can use NOT IN() on your select with the IDs that exist on you XML like:
SELECT id FROM `list` WHERE id NOT IN($your_id_list)
With this you'll have a list of IDs that are not in the list.
Your IDs must be separated with a comma like:
SELECT id FROM `list` WHERE id NOT IN(123,654,987,45)
Question 1: how would I display the Id that is pulled from the database?
$sql_result = mysql_query("SELECT `id` FROM `list` WHERE `id` = $id") or die(mysql_error());
$sql_row = mysql_fetch_assoc($sql_result);
if(!empty($sql_row['id'])) {
echo "Id exists - " . $sql_row['id'] . "\n";
} else {
echo "Id no longer exists - " . $sql_row['id'] . "\n";
}
Question 2: why isn't this code finding any ids that are not in the XML?
I think in your code the if() condition will always return true irrespective if the Id exists in the database or not. And secondly as you might have guessed from my code above, you are missing to fetch the data from the SQL resultset
Question 3: am I going about this completely the wrong way and is there a better way to do it?
You are doing it the right way by browsing through the XML and checking each entry in the database for existence. A better way might be to first retrieve all IDs from the XML and then use them in the single SQL query:
SELECT `id` FROM `list` WHERE `id` NOT IN ($list);
Please note that this query might run slow if there are a very large number of IDs in the XML file, say a few hundreds.
mysql_num_rows()
Or
SELECT COUNT(*) [...]
i have a question for you guys.
im trying to print an array where it would display 10 values of the table acording to user.
this is what i have so far and it displays only the first row,
session_start();
// Retrieve all the data from the table
$result = mysql_query("SELECT name,location,login_id FROM table WHERE login_id = $user[login_id]")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
echo " name ".$row['name'];
echo " located ".$row['location'];
.....
how can i display the first 10 rows?
help would be apreciated.
thank you for reading.
also add "limit 10" to the query.
SELECT name,location,login_id FROM table WHERE login_id = $user[login_id] LIMIT 10
session_start();
// Retrieve all the data from the table
$result = mysql_query("SELECT name,location,login_id FROM table WHERE login_id = $user[login_id] LIMIT 10")
or die(mysql_error());
while($row = mysql_fetch_array( $result )){
echo " name ".$row['name'];
echo " located ".$row['location'];
}
And This will work only if your login_id is not unique and multiple rows can have the same login_id
You have to call mysql_fetch_array repeatedly to get all the row from the result set:
while(($row = mysql_fetch_array( $result ))) {
echo " name ".$row['name'];
echo " located ".$row['location'];
}
See further examples in the documentation.
If you really want to get only the first 10 rows, have a look at #Yasser Souri's answer (you still have to loop though).