I'm having a problem with PHP. I want the following code to only show one result from the databse - the one that matches the siteID field. But instead it is returning all of the results from the database.
<?php
$siteID = $_GET['siteID'];
include 'connect.php';
$sql = "SELECT id, siteID,name,description,skills,extra1,extra2 FROM folio";
$queryresult = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($queryresult)) {
$id = $row['id'];
$siteID = $row['siteID'];
$name = $row['name'];
$description = $row['description'];
$skills = $row['skills'];
$extra1 = $row['extra1'];
$extra2 = $row['extra2'];
echo "<div id='title'>
<h5>$name</h5>
</div>
<div id='holder'>
<div id='blogleft'>
</div>
<div id='blogright'>
<p>Archive / Calendar<br /><br /> Add some sort of calendar or archive here; for previous blog posts.</p>
</div>
</div>";
}
?>
the url ends with "/work.php?siteID=pluggedin"
You need a WHERE clause.
$sql = "SELECT id, siteID, name, description, skills, extra1, extra2 FROM folio WHERE siteID='".$siteID."'";
Although i don't recommend this at all. Look up SQL injection if you don't know what I'm talking about. I would do a PDO statement instead.
Something like this:
$sql = "SELECT * FROM folio WHERE siteID=:siteid";
$sth = $dbh->prepare($sql);
$sth->bindParam(':siteid', $siteid, PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
You can also do:
$result = $sth->fetch(PDO::FETCH_ASSOC);
which gives you an array with column names, similar to mysql_fetch_assoc, this will retrieve the next row, again similar to mysql_fetch_assoc.
You didnt used any where condition in your query.
Try this
$sql = "SELECT id, siteID, name, description, skills, extra1, extra2 FROM folio WHERE siteID='".(int)$_GET['siteID']."' ";
$sql = "SELECT
id,
siteID,
name,
description,
skills,
extra1,
extra2
FROM folio
where siteID = $siteID";
You just miss the where clause.
That's because you are selecting all your records in your table ... add a LIMIT clause to your query
Related
In my DB I have some "documents" which contain more items, I'm inserting that from my dashboard.
The thing is ; when displaying, the method requires a value in my case it's $id.
Right now I am using rand() with hardcoded range to show different "documents".
This is how it looks :
<?php
$num = rand(1,10);
$post->showSmallPost($num);
?>
Let's say i want to have three of these on HTML page. But instead of this rand() I want to show the last three ID imported to table. So that is my question, how to do it?
This is a method showSmallPost():
public function showSmallPost($id){
$connection = new Db();
$conn = $connection->connect();
$image = new Image();
$imgC = $image->showSmallImg($id);
$query = $conn->prepare("SELECT * FROM post WHERE id = ?");
$query->bind_param('i', $id);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
if ($row = $result->fetch_assoc()) {
$this->id = $row['id'];
$this->title = $row['title'];
$this->description = $row['description'];
echo "<div class=\"col-md-4 text-center\" style=\"margin-top: 5px;\">";
echo <<<EOT
<a href="news.php?post=$id">
$imgC
</a>
<h4 class="news-title">$this->title</h4>
<p class="news-para">$this->description</p>
EOT;
echo "</div>";
}
}
}
And yes, this showSmallImg() is just doing his job.
You can just add Sort to the Query.
You don't need to pass a random $id to the function.
You can change the SQL statement to:
$query = $conn->prepare("SELECT * FROM post ORDER BY id DESC LIMIT 0,1");
Also you can get 3 Documents in a Single Query With,
$query = $conn->prepare("SELECT * FROM post ORDER BY id DESC LIMIT 0,3");
You can even optimize the query to run faster,
$query = $conn->prepare("SELECT id, title, description FROM post ORDER BY id DESC LIMIT 0,3");
Also, rather than using HTML inside echo, you can create a multidimensional array of your preferred structure or use the one that the sql query returns.
And make use of foreach method and only print the Values inside the array with PHP and leave HTML as it is.
It will generate more cleaner code.
For Example:
<div class=col-md-4 text-center" style="margin-top: 5px;">
<?php echo $imgC; ?>
<h4 class="news-title"><?php echo $this->title; ?></h4>
<p class="news-para"><?php echo $this->description ?></p>
</div>
You can select the last id from the database, and create a for loop decrementing it.
$query = $conn->prepare("SELECT MAX(id) AS last_id FROM post");
$query->execute();
$result = $query->get_result();
$row = $result->fetch_assoc();
$lastId = $row['last_id'];
for ($i = $lastId; $i > $lastId - 3; $i--)
{
$post->showSmallPost($i);
}
Alternatively, you can use the ORDER BY and LIMIT statements to get what you want.
$query = $conn->prepare("SELECT id FROM post ORDER BY id DESC LIMIT 3");
$query->execute();
$result = $query->get_result();
$row = $result->fetch_assoc();
while ($row = $result->fetch_assoc())
{
$post->showSmallPost($row['id']);
}
If I'm understanding it right then you want to fetch the latest n records from a table and to do that you need to have a field like createdAt. Then you can write a query which will fetch the n records and order result by this createdAt field in descending order.
Your query then will look something like this
select * from posts order by createdAt desc limit 5;
This will give you the latest 5 records inserted into the table.
can someone help me on the proper way of using a variable with multiple values in MySQL LIKE clause?
by the way, I have two tables teacher and student.
Teacher table contains. (fname,lname,subject,yr,sec) columns and for the student table (lrn,yr,sec)
what I'm trying to achieve is to count the total number of students of the teacher from all sections.
Here's my query for getting teacher's sections:
<?php
$result= mysqli_query($con, "select *from teacher where lname
= 'Uy' and subject = 'Science & Technology 7'" );
while($rowx = mysqli_fetch_array($result)) {
$section = $rowx['sec'];
}
?>
echoing $section output this: Our Lady of FatimaOur Lady of Guadalupe
Heres my query to count the students.
<?php
$ratequery = mysqli_query($con, "SELECT *,
(SELECT COUNT(*) FROM student WHERE
sec LIKE '%$section%') AS responseCount FROM student");
$rateresult = mysqli_fetch_array($ratequery);
?>
Output: the count works but only the first value [Our Lady of Fatima] of $section is getting recognized by LIKE clause, so only 1 section is getting counted.
by the way, sorry for my bad English and explanation.
Use Section as a input for second query:
<?php
$final_result = array();
$result= mysqli_query($con, "select *from teacher where lname
= 'Uy' and subject = 'Science & Technology 7'" );
while($rowx = mysqli_fetch_array($result))
{
$section = $rowx['sec'];
$ratequery = mysqli_query($con, "SELECT *, (SELECT COUNT(*) FROM student WHERE
sec =$section) AS responseCount FROM student");
$rateresult = mysqli_fetch_array($ratequery);
array_push($final_result,array("section"=>$section,"rateresult"=>$rateresult));
}
var_dump($final_result); // Display section wise data
?>
somehow I have managed to achieve my goal it but in other way . I used WHERE IN clause instead of LIKE clause. stored my query results into an array.. then used implode to add seperator.
Thanks for the help mr. #ashnu
<?php
$query="$con, select *from teacher where lname = 'Uy' and subject = 'Science & Technology 7'";
$result = mysqli_query($query) or die;
$sections = array();
while($row = mysqli_fetch_assoc($result))
{
$sections[] = $row['sec'];
}
$string = implode("','",$sections)
?>
<?php
$ratequery = mysqli_query($con, "SELECT *,
(SELECT COUNT(*) FROM student WHERE sec IN ('$string')) AS responseCount FROM student");
$rateresult = mysqli_fetch_array($ratequery);
?>
I am trying to grab the largest ID number from the database. The output should be 15 but it shows 1. My PHP script:
$sql = "SELECT MAX(id) AS id FROM employees";
$sql = $db->prepare($sql);
$lid = $sql->execute();
I am outputting it here:
<input type="number" name="id" value="<?php echo $lid; ?>" disabled>
I have also tried:
$sql = "SELECT id FROM employees ORDER BY id DESC LIMIT 1";
I tried the command on phpMyAdmin. It worked fine. The output was 15. So, I suspect that there are no problems in the query.
What is the problem, then?
You should FETCH i.e., $sql->fetch(PDO::FETCH_ASSOC);
So, You shall have something like
$sql = "SELECT MAX(id) FROM employees";
$sql = $db->prepare($sql);
$sql->execute();
$result = $sql->fetch(PDO::FETCH_ASSOC);
print_r($result);
Note : Simply $lid = $sql->execute(); means it will assign whether the query is executing or not.
As your query is executing it is returning true which is 1
Update : If you are not binding any values you don't even need to prepare, you shall fetch it directly like Adelphia said
$sql = $db->query("SELECT MAX(id) FROM employees");
$result = $sql->fetch(PDO::FETCH_ASSOC);
print_r($result);
No need for prepared statements since it's a static query.
I have a MySQL database containing a user's country and whether they are an individual or an organisation. The field names are 'country' and 'type'.
Using PHP, I'd like to 'count' the number of countries, the number of individuals and the number of organisations in the database and then display the numbers in the following example format:
<p>So far, <strong>500</strong> individuals and <strong>210</strong> organisations from <strong>40</strong> countries have registered their support.</p>
I am currently listing the total number of records using the below code if this helps:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$result = mysql_query("SELECT * FROM table_name", $link);
$num_rows = mysql_num_rows($result);
echo " $num_rows\n ";
?>
My PHP / MySQL skills are very limited so I'm really struggling with this one.
Many thanks in advance!
Ben
To get the number of countries:
SELECT COUNT(DISTINCT country) AS NumCountries FROM tableName
To get the number of individuals, or the number of organisations:
SELECT COUNT(*) AS NumIndividuals FROM tableName WHERE type = 'individual'
SELECT COUNT(*) AS NumOrganisations FROM tableName WHERE type = 'organisation'
What you are looking for is a count based on a grouping. Try something like this:
$sql = "SELECT type, count(*) as cnt FROM users GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
This will give you an array like
Array (
'individual' => 500,
'organization' => 210
)
For counting the countries, use the first statement as posted by Hammerite.
EDIT: added a verbose example for counting the countries
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM users";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
This altogether you can then print out:
printf('<p>So far, <strong>%d</strong> individuals and <strong>%d</strong> '.
'organisations from <strong>%d</strong> countries have registered '.
'their support.</p>', $counts['individual'], $counts['organization'],
$number_of_countries);
The answer is to retrieve the answer by using the COUNT(*) function in SQL:
SELECT COUNT(*) AS individual_count FROM user WHERE type = 'individual';
SELECT COUNT(*) AS organization_count FROM user WHERE type = 'organization';
SELECT COUNT(*) AS country_count FROM user GROUP BY country;
The last will group your query set by the country name, and will result in one row for each country. Using COUNT on this result set will give the count of distinct coutries.
You can then fetch this value by using mysql_fetch_assoc on your $result from mysql_query, and the answer will be contained in 'invididual_count', 'organization_count' and 'country_count' for each query.
Thank you for all of your help with this (especially Cassy).
I think it's worthwhile displaying the full code in case anybody else comes across a similar requirement in the future:
<?php
$link = mysql_connect("localhost", "username", "password");
mysql_select_db("database_name", $link);
$sql = "SELECT type, COUNT(*) as cnt FROM table_name GROUP BY type";
$result = mysql_query($sql);
$counts = array();
while ($row = mysql_fetch_assoc($result)) {
$counts[$row['type']] = $row['cnt'];
}
$sql = "SELECT COUNT(DISTINCT country) AS NumCountries FROM table_name";
$result = mysql_query($sql);
$number_of_countries = 0;
if ($row = mysql_fetch_assoc($result)) {
$number_of_countries = $row['NumCountries'];
}
printf('<p><strong>So far, <em class="count">%d</em> individuals and <em class="count">%d</em> organisations from <em class="count">%d</em> countries have registered their support.', $counts['Individual'], $counts['Organisation'], $number_of_countries); ?>
If you're just looking for the number of rows returned try this:
$result = mysql_db_query($db, $query);
$num_rows = mysql_num_rows($result);
Another option would be to execute a separate query with the mysql count function and use the result from that.
hi
i can rewrite a column's values in a mysql databse based on another columns values, but this time i need to do this with a twist...
there are two tables (and multiple values at once): specifications and products.
products has two columns: specificationids and specificationorderids
specifications has two columns aswell: id and specificationorder
specificationids has multiple values formatted like this: ,31,29,27,18,
these are also the id in the specifications table. each id has a specificationorder value (same row, other column). now what i want to do is, that i want to swap the values of the id with the value of specificationorder and write these to specificationorderids in the products table in the same format.
ofcourse this process has to loop through all the id's in the products table.
i hope i made the problem clear and understandable
thanks for your help!
Swap id and specificationorder, specificationorder writen in specificationorderids if I understand you:
<?php
/* Swap id and specificationorder */
$sql = "SELECT id, specificationorder from specifications";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{
$id = $row[0];
$sporder = $row[1];
$sql = "UPDATE specifications SET id=$id, specificationorder=$sporder WHERE id=$id";
mysql_query($sql);
}
/* specificationorder writen in specificationorderids */
$sql = "SELECT specificationorder from specifications";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{
$sporder = $row[0];
$sql = "INSERT INTO products(specificationorderids) VALUES($sporder)";
mysql_query($sql);
}
?>
for the past couple days i havent been able to come up with a normal code, so heres what ive got so far. ive added comments so you know what i was thinking when experimenting with the code... as in my previous comment i include an image of what i want to achive: img822.imageshack.us/i/specm.png
//get specificationids
$sql = "SELECT specificationids from products";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$spids = $row[0];
//get specifications
$sql2 = "SELECT id from specifications";
$result2 = mysql_query($sql2);
$row2 = mysql_fetch_row($result2);
$spid = $row2[0];
//get specificationorder
$sql3 = "SELECT specificationorder from specifications";
$result3 = mysql_query($sql3);
$row3 = mysql_fetch_row($result3);
$sporder = $row3[0];
//if the value of specificationids matches a specificationid, then....
while(VALUES($spids)==$spid)
{
$spids=$sporder; //...it should be replaced by the specificationorder
//and then update the specificationorderids column accordingly
$sql = "UPDATE products(specificationorderids) VALUES($spids)";
mysql_query($sql);
}