Im coding in PHP and SQL after finishing the web site I realize that in my bloucles, that take their info from the database I have repeated values,
Here you will understand better:
I have this code:
<?php
$mysqli = new mysqli("localhost","root","","motorsportgeneral") or die("1");
$sql = "SELECT * FROM cars ";
$result = $mysqli->query($sql);
if($result)
{
while($row = $result->fetch_assoc())
{
?>
<?php echo $row['model'] ?>
<?php
}
}
?>
If in the rows of my table I have 2 repeated values the server will show this:
Hello1
Hello2
Hello1
Hello2
How can I eliminate this repeated values in my list, with out touching the table?
Thanks, I hope you can help me!
SELECT DISTINCT model FROM cars
SELECT DISTINCT model FROM cars
That should do the trick, if I understand correctly.
Related
I'm fairly new to this so I am probably missing something very basic, but I am trying to write some PHP script. I want to normalize my main table of data, which is info on used cars, make, model, price, etc. So I have another table with all of the unique car manufacturers in, this stores the makeName with a unique id makeId In my script, I connect to the database, read in all of the data from the main table, run it as an SQL query, then store it as a variable. I do the same with the make table.
Then I try to run through a nested while loop to replace all of the strings in the main table in the Manufacturer column with the makeId from the make table so that I can link these two tables. It works for one iteration then stops, I've tried adding !==FALSE after the fetch_assoc in either and both while loops, but that gives me infinite loops I think. Here is my code...
<?php
include("conn.php");
$sqlAll= "SELECT * FROM carData";
$carDataResult = $conn->query($sqlAll);
if(!$carDataResult){
echo $conn->error;
die();
}
$sqlMake = "SELECT * FROM 000make";
$makeResult = $conn->query($sqlMake);
if(!$makeResult){
echo $conn->error;
die();
}
while ( $make =$makeResult-> fetch_assoc()){
$makeID = $make['makeId'];
$makeName = $make['makeName'];
while ($row = $carDataResult->fetch_assoc()){
$sqlUpdate="UPDATE carData SET Manufacturer = '$makeID'
WHERE Manufacturer='$makeName' AND Manufacturer IS NOT NULL";
$res = $conn->query($sqlUpdate);
if(!$res){
echo $conn->error;
die();
}
}
}
?>
About 10 mins after I posted the question, after staring at this all day, I realised that I didn't need a nested loop at all and wrote the code below, which is clunky but it solved the problem, but I like your solution better #TangentiallyPerpendicular...thanks for your help guys...
while ($make =$makeResult-> fetch_assoc()){
$makeID = $make['makeId'];
$makeName = $make['makeName'];
$sqlUpdate="UPDATE carData SET Manufacturer = '$makeID'
WHERE Manufacturer='$makeName' AND Manufacturer IS NOT NULL";
$res = $conn->query($sqlUpdate);
if(!$res){
echo $conn->error;
die();
}
}
As a general rule, reading a result set and looping through it to run successive queries is the wrong way to deal with this sort of problem. You can do it all in a single query:
update carData set `Manufacturer` = (select `makeId` from `000make` where 000make.makeName=carData.Manufacturer)
Your entire program becomes:
<?php
include("conn.php");
$sqlAll= "update carData set `Manufacturer` = (select `makeId` from `000make` where 000make.makeName=models.Manufacturer) ";
$carDataResult = $conn->query($sqlAll);
if(!$carDataResult){
echo $conn->error;
die();
} else {
echo "Update Successful"
}
As an aside, I'd create a new column (called, perhaps, makeId) in your carData table and insert the data there rather than overwriting the Manufacturer column. That way you retain the Manufacturer column if something goes wrong. You can drop that column later.
ok guys I need a bit of help with this, remaking this to format ir properly.
I have this code:
(this is accessing a table called "students" in database.)
<?php
require_once('connection.php');
$id = $_SESSION['SESS_MEMBER_ID'];
$result3 = mysql_query("SET NAMES UTF8;");
$result3 = mysql_query("SELECT * FROM students where mem_id='$id'");
while($row3 = mysql_fetch_array($result3))
{
$fname = $row3['fname'];
$country = $row3['country'];
$class = $row3['class'];
$headteacher = $row3['headteacher'];
$attendance = $row3['attendance'];
$homework = $row3['homework'];
$messagestudent = $row3['messagestudent'];
}
?>
<?php
if($class=='K1')
echo "teacher 1";
else if($class=='K2')
echo "teacher 2";
else if($class=='K3')
echo "teacher 3";
?>
In another table, i have the teacher names and what i need to do and i cannot find the right way to do it, is to call the teacher's name from the table "teachers" after the query confirms the K1, K2 or K3 data on the "students" table column "class".
Basically what i need is to change the contents of the echo part, switching it from static data needed to be within the code, to a data contained on another table, for example. both tables have a column called "class", so if class column for a student says "K1" i want this to then go check the "teacher" table's column "class" and pick the one that matches "K1" and display it in the result echo, I'm sure it is possible, but not with my current skill level.
The table structure for students is:
mem_id, username, password, fname, country, class, attendance, homework, messagestudent
The table structure for teacher is:
mem_id, class, name, comment
Hope you guys shed some light on me!
Thanks in advance.
PS. I know the query is using the deprecated mysql_, but when I tried to change it to mysqli_ following a guide, it never worked.
If I understood, you can get the desired data through this query (without JOIN or if statement):
SELECT students.*,teachers.name FROM students,teachers WHERE students.id='$id' AND students.class = teachers.class
It returns the teacher name according the student class, at the same row.
You can use left join for this. Try using following query:
SELECT * FROM students as st
LEFT JOIN teachers AS ts
on st.class=ts.class
WHERE st.mem_id = '$id'
You don't need to use if-else statement for this. And it will also work with mysqli.
According to your script, it should work like:
<?php
require_once('connection.php');
$id = $_SESSION['SESS_MEMBER_ID'];
$result3 = mysql_query("SET NAMES UTF8;");
$result3 = mysql_query("SELECT st.*, ts.name AS teacher_name FROM students as st LEFT JOIN teachers AS ts on st.class=ts.class WHERE st.mem_id = ".$id);
while($row3 = mysql_fetch_array($result3))
{
$fname = $row3['fname'];
$country = $row3['country'];
$class = $row3['class'];
$headteacher = $row3['headteacher'];
$attendance = $row3['attendance'];
$homework = $row3['homework'];
$messagestudent = $row3['messagestudent'];
$teachername = $row3['teacher_name'];
}
echo $class. ' - '. $teachername;
?>
How do I echo the latest values in column1? The below code echos the values before the update.
while($line = mysql_fetch_array($result)) {
$Student = $line["calss8"];
$querySf = "SELECT SUM(ABC) AS val1 FROM tbl1 WHERE student = '$Student'";
$resultSf = mysql_query($querySf);
$rSf = mysql_fetch_array($resultSf);
$totalSf = $rSf['val1'];
$totTMonth = $totalSf;
mysql_query("UPDATE tbl4 SET column1 = $totTMonth WHERE student = '$Student' LIMIT 1");
}
echo $line["column1"].",,";
As far as I know, you'll have to make a separate query to see what was just updated. I mean, run your select, perform your update, then do another select. You can get general information like how many rows were updated, but I don't think you can get specific information like the changed values in a column. Phil was right in suggesting that you should just print out the '$totTMonth' value since that is what you are updating your column with. That would be less overhead than doing another query to the database.
I think that problem starts before the code above. This code line will display the select results :echo $line["column1"].",,";. The variable $line is set before the code above. My solution is to do the following:
$result1 = mysql_query("SELECT column1 FROM student ..."); /* I insert the select query here */
While($row= mysql_fetch_array($result)) {
echo $row['column1'].",,";
}
I hope my title says something about what I am trying to do, I'll try to describe it a bit better:
I have a database with two tables, one named "movies" and another one named "directors".
Its a small movie database where we are supposed to be able to display all the movies, their title, year and producer.
In the table "directors" I have a field "id" and in my "movies" table i have a field named "producer" with the matching id. I want the while loop to loop thru all the movies in the "movies" table (working fine) and if i choose to print the "id" from "movies" its correct.
But now i want the loop to display the "title" and "year" from the "movies" table, and go to the "directors" table and get the name for the matching "id".
I'm new to both PHP and mysql queries and my code does this correctly for the first movie, but the rest have their "producer" field empty as for now.
(Right now I'm just trying to display the surname to see that it works).
FYI this is for a school project.
Code:
<?php
$sql = "SELECT * FROM movies ORDER BY title ASC";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$id = $row['id'];
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$title=mysql_result($result,$i,"title");
$year=mysql_result($result,$i,"year");
$producer=mysql_result($result,$i,"producer");
$id=mysql_result($result,$i,"id");
$sqldir = "SELECT * FROM directors WHERE id='$producer'";
$result1 = mysql_query($sqldir);
$row1 = mysql_fetch_assoc($result1);
$iddir = $row['id'];
$producertext = mysql_result($result1,$i,"surname");
?>
<b>Title:</b> <?php echo $title ?>
<br/><b>Year:</b> <?php echo $year ?>
<br/><b>Director:</b> <?php echo $producertext ?>
<br/>
</form> <HR>
<?php
$i++;
}
?>
Assuming that every movie has a single director then you can just create a joined query
SELECT movies.title as title, movies.year as `year` producer.surname as surname
FROM movies, producer where movies.producter = producer.id ORDER BY title ASC
You can then just walk the result set and the surname will be in the result arrays.
Here should be a complete solution assuming the query works as expected
<?php
$sql = "SELECT movies.title as title, movies.year as `year` producer.surname as surname FROM movies, producer where movies.producter = producer.id ORDER BY title ASC";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)): ?>
<b>Title:</b> <?php echo $row['title'] ?>
<br/><b>Year:</b> <?php echo $row['year'] ?>
<br/><b>Director:</b> <?php echo $row['surname]; ?>
<?php
endwhile;
?>
You are using wrong function
$num=mysql_numrows($result);
you should use
$num=mysql_num_rows($result);
You're accessing the producer information as:
$producertext = mysql_result($result1,$i,"surname");
However, $i is the index from the main SQL loop; so on the second run through, you'll be looking for the surname from the second line of your producer result set, which won't necessarily be there. So only the first producer is showing up.
Some other things you might want to look at - you can use PDO or mysqli to access data - they're more secure that mysql, which is in the process of being deprecated. You're also using mysql_fetch_assoc at the moment, but you don't seem to be using the resulting array for anything. It's a lot more common to go through a result set with something like:
while ($row = myssql_fetch_assoc($result)) {
....
}
Which loads the next row into an associative array for you to use, and stops when you run out of rows.
Also, have you considered what your code should do if there's more than one producer for a film? You might want to add a loop for that query, too.
Sorry if it's a stupid question but i really can't find a answer :)
Can i search and echo multiple results out of my database? for example
id|first name|last name|email-adress
1 |matthias |oben |matthiasoben#...
2 |senne |vanhoof |sennevanhoof#...
3 |han |jacobs |hanjacobs#...
4 |matthias |dieltiens|matthiasdieltiens...
5 |jeroen |meys |jeroen.meys#...
and i want to echo the email-adress of the peoples with the
name 'matthias'
Is this possible?
Thanks
Something like ....
$query = "SELECT * FROM People WHERE first_name = 'matthias'";
$results = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo $row['email'] . "<br />";
}
Of course, u should run mysql_query, and then do loop until the mysql_fetch_row is empty:
$result=mysql_query("select * from bla");
while($row=mysql_fetch_row($result))
{
your code here... $row[0]...$row[FIELD NUBMER];
}
for you seconds question, you should use WHERE in ur query
SELECT 'email' FROM YOUR_TABLE WHERE name='matthias'
Yes, you can. Use an SQL statement that returns multiple rows, for example
SELECT `email-address` FROM `table` WHERE `first name` = 'matthias'
(some very bad column names there; stick to letters, numbers and underscores only)