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)
Related
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.
I need someone to help me with this problem. My head doesn't want to think straight today.
So, i have a table named "recensions", and another named "comments". In each table, i have a column named "amne_id". This would make so i could connect the comments to the correct recension.
Now, on my first page, i simply get all the recensions with the code:
$rec = $this->db->get('recensions');
What i want is to count how many comments each recension has. But i have no idea how. I guess i maybe should use JOIN and num_rows()?
Please ask if you dont understand, so i can explain better.
Have a nice day!
$this->db->select('COUNT(*) as count, recensions.anme_id as recension_id')
->from('recensions')
->join('comments','recensions.anme_id = comments.anme_id','left')
->group_by('anme_id');
$result = $this->db->get();
Should give you the recensions id and the comment count for that id.
then loop:
foreach($result->result() as $row){
echo "Recension id $row->recension_id has $row->count comments<br />";
}
Like this??
$sql = mysql_query("SELECT * FROM recensions");
while($row = mysql_fetch_array($sql)){
$amne_id = $row{"amne_id"};
$sql2 = mysql_query("SELECT * FROM comments WHERE amne_id='$amne_id'");
$total_comments = mysql_num_rows($sql2);
echo $total_comments;
}
I don't know about the database connector you are using, but in pure SQL (assuming the connection recensions.id=comments.anme_id connection), try this:
SELECT COUNT(comments.id), anme_id
FROM recensions
LEFT JOIN comments on comments.anme_id=recensions.id
GROUP BY anme_id
Seems simple but what am I doing wrong here? I just want the max value in a column for a given vendor ID. Can I use the as clause in a recordset?
$query = mysql_query("SELECT max(container_no) as newcontainer
FROM FETE_profiles WHERE vendor_id = '$mvendorid'");
while($rst = mysql_fetch_array($query)) {
print $rst[newcontainer] . "<br/>";
}
Just try like this
$query = "SELECT max(container_no) as newcontainer
FROM FETE_profiles WHERE vendor_id = ".$mvendorid." ";
$result = $mysql->execute_sql_query($query);
while(#$rows = mysql_fetch_array($result))
{
print $rows['newcontainer ']. "<br/>";
}
yes, you can i think...
but when you want to print it just add single quote like this $rst['newcontainer']
got it working everyone thanks for all your answers. It was code above, pushing a vendor id into this sql statement which had no representative rows in the profiles table.
duh! well that happens when you dont have the luxury of peer review :-)
I have a table with 4 record.
Records: 1) arup Sarma
2) Mitali Sarma
3) Nisha
4) haren Sarma
And I used the below SQL statement to get records from a search box.
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%$q' LIMIT 5";
But this retrieve all records from the table. Even if I type a non-existence word (eg.: hgasd or anything), it shows all the 4 record above. Where is the problem ? plz any advice..
This is my full code:
$q = ucwords(addslashes($_POST['q']));
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%".$q."' LIMIT 5";
$rsd = mysql_query($sql);
Your query is fine. Your problem is that $q does not have any value or you are appending the value incorrectly to your query, so you are effectively doing:
"SELECT id,name FROM ".user_table." WHERE name LIKE '%' LIMIT 5";
Use the following code to
A - Prevent SQL-injection
B - Prevent like with an empty $q
//$q = ucwords(addslashes($_POST['q']));
//Addslashes does not work to prevent SQL-injection!
$q = mysql_real_escape_string($_POST['q']);
if (isset($q)) {
$sql = "SELECT id,name FROM user_table WHERE name LIKE '%$q'
ORDER BY id DESC
LIMIT 5 OFFSET 0";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "id: ".htmlentities($row['id']);
echo "name: ".htmlentities($row['name']);
}
} else { //$q is empty, handle the error }
A few comments on the code.
If you are not using PDO, but mysql instead, only mysql_real_escape_string will protect you from SQL-injection, nothing else will.
Always surround any $vars you inject into the code with single ' quotes. If you don't the escaping will not work and syntax error will hit you.
You can test an var with isset to see if it's filled.
Why are you concatenating the tablename? Just put the name of the table in the string as usual.
If you only select a few rows, you really need an order by clause so the outcome will not be random, here I've order the newest id, assuming id is an auto_increment field, newer id's will represent newer users.
If you echo data from the database, you need to escape that using htmlentities to prevent XSS security holes.
In mysql, like operator use '$' regex to represent end of any string.. and '%' is for beginning.. so any string will fall under this regex, that's why it returms all records.
Please refer to http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html once. Hope, this will help you.
Let's put an easy example with two tables:
USERS (Id, Name, City)
PLAYERS (Id_Player, Number, Team)
And I have to do a query with a subselect in a loop, where the subselect is always the same, so I would like to divide it into two queries and put the subselect outside the loop.
I explain. What works but it is not optimize:
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN (SELECT Id FROM USERS WHERE City='London')");
}
What I would like to do but it doesn't work:
$res1=mysql_query("SELECT Id from USERS where City='London'");
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN **$res1**");
}
Thanks!
Something like this should work.
<?
$sql = "SELECT Team from PLAYERS
JOIN USERS on (Id_player=Id)
WHERE Number BETWEEN $minID AND $maxID
AND City='London'
GROUP BY Team";
$results=mysql_query($sql) or die(mysql_error());
// $results contain all the teams from London
// Use like normal..
echo "<ul>\n";
while($team = mysql_fetch_array($results)){
echo "\t<li>{$team['Team']}</li>\n";
}
echo "</ul>";
Placing SQL quires in loops can be very slow and take up a lot of resources, have a look at using JOIN in you SQL. It's not that difficult and once you've got the hang of it you can write some really fast powerful SQL.
Here is a good tutorial worth having a look at about the different types of JOINs:
http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php
SELECT PLAYERS.*, USERS.City FROM PLAYERS, USERS WHERE USERS.City='London' AND PLAYERS.Number = $i
Not the best way to do it; maybe a LEFT JOIN, but it should work. Might have the syntax wrong though.
James
EDIT
WARNING: This is not the most ideal solution. Please give me a more specific query and I can sort out a join query for you.
Taking your comment into account, let's take a look at another example. This will use PHP to make a list we can use with the MySQL IN keyword.
First, make your query:
$res1 = mysql_query("SELECT Id from USERS where City='London'");
Then, loop through your query and put each Id field one after another in a comma seperated list:
$player_ids = "";
while($row = mysql_fetch_array($res1))
{
$player_ids .= $row['Id'] . ",";
}
$player_ids = rtrim($player_ids, ",");
You should now have a list of IDs like this:
12, 14, 6, 4, 3, 15, ...
Now to put it into your second query:
for($i = 0; $i<something; $i++)
{
$res2 = mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN $player_ids");
}
The example given here can be improved for it's specific purpose, however I'm trying to keep it as open as possible.
If you want to make a list of strings, not IDs or other numbers, modify the first while loop, replacing the line inside it with
$player_ids .= "'" . $row['Id'] . "',";
If you could give me your actual query you use, I can come up with something better; as I said above, this is a more generic way of doing things, not necessarily the best.
Running query in a loop is not a great idea. Much better would be to get whole table, and then iterate through table in loop.
So query would be something like that:
"SELECT Team from PLAYERS WHERE Number BETWEEN($id, $something)
AND Id_Player IN (SELECT Id FROM USERS WHERE City='London')"
$res1=mysql_query("SELECT Id from USERS where City='London'");
for($i=0;$i<something;$i++)
{
$res2=mysql_query("SELECT Team from PLAYERS WHERE Number=$i
AND Id_Player IN **$res1**");
}
Would work, but mysql_query() returns a RESULT HANDLE. It does not return the id value. Any select query, no matter how many, or few, rows it returns, returns a result statement, not a value. You first have to fetch the row using one of the mysql_fetch...() calls, which returns that row, from which you can then extract the id value. so...
$stmt = mysql_query("select ID ...");
if ($stmt === FALSE) {
die(msyql_error());
}
if ($stmt->num_rows > 0) {
$ids = array();
while($row = mysql_fetch_assoc($stmt)) {
$ids[] = $row['id']
}
$ids = implode(',', $ids)
$stmt = mysql_query("select TEAM from ... where Id_player IN ($ids)");
.... more fetching/processing here ...
}