in my query i want only from id 1-3 to appear in the result, not 4-6. is there any other way to do it?
beautician database table:
id_beautician name
1 a
2 b
3 c
4 d
5 e
6 f
i tried to put the code below in mysql query
for($i=4; $i<=6; $i++) :
$q.$i = $db->query("SELECT * FROM beautician WHERE id_beautician='$i'");
$r.$i = $q.$i->fetch_assoc();
//echo $i;
endfor;
but it gives me an error:
Object of class mysqli_result could
not be converted to string
Instead of doing n queries, modify SQL query to match only data you need - for example:
$query = $db->query("SELECT * FROM beautician WHERE id_beautician <= 3");
while ( $row = $query->fetch_assoc() ) {
echo $row['id'] . ' = ' . $row['name'] . '<br/>';
}
If ids are not in sequence, you can also use as below.
$query = $db->query("SELECT * FROM beautician WHERE id_beautician in (1,2,3)");
while ( $row = $query->fetch_assoc() )
{
echo $row['id'] . ' = ' . $row['name'] . '<br/>';
}
using IN in query sometimes slow down the execution, but can be used efficiently for small-size database.
Related
I have three tables: - food - toys - animals
Each table has the columns - id, color, item
Table toys has additional columns - sn, date and more
Need to select all items from all tables with color = red and get them separately on client side
Something like:
$color = 'red';
$sql = "select * from food, toys, animals where color = :acolor";
$st = $db->prepare($sql);
$st->execute([":acolor" => $color]);
$food = $toys = $animals = '';
while($row = $st->fetch()){
$food .= "<div class='food' data-id = " . $row['food.id'] . ">" . $row['food.item'] . "</div>\n";
$toys .= "<div class='toys' data-id = " . $row['toys.id'] . " data-serial = " . $row['toys.sn'] . " data-date = '" . $row['toys.date'] . "'>" . $row['toys.item'] . "</div>\n";
}
$animals .= "<div class='animals' data-id = " . $row['animals.id'] . ">" . $row['animals.item'] . "</div>\n";
}
$arr = [];
array_push($arr, $food, $toys, $animals);
echo json_encode($arr);
client side
...
data = JSON.parse(data);
$('#wrapfood').html(data[0]);
$('#wraptoys').html(data[1]);
$('#wrapanimals').html(data[2]);
As the final result:
wrapfood should have 5 divs with class food
wraptoys should have 9 divs with class toys
wrapanimals should have 21 divs with class animals
I tried various versions of the above code without success - getting errors on server side.
Any help?
You can use this
$data = array('food' => array(),'toys' => array(),'animals' => array());
$color = 'red';
$foodSql = "select * from food where color = :acolor";
$toySql = "select * from toys where color = :acolor";
$animalSql = "select * from animals where color = :acolor";
$ft = $db->prepare($foodSql);
$tt = $db->prepare($toySql);
$at = $db->prepare($animalSql);
$ft->execute([":acolor" => $color]);
$tt->execute([":acolor" => $color]);
$at->execute([":acolor" => $color]);
$food, $toys, $animals = '';
while($row = $ft->fetch()){
$food .= "<div class='food' data-id = " . $row['food.id'] . ">" . $row['food.item'] . "</div>\n";
}
array_push($data['food'], $food);
while($row = $tt->fetch()){
$toys .= "<div class='toys' data-id = " . $row['toys.id'] . " data-serial = " . $row['toys.sn'] . " data-date = '" . $row['toys.date'] . "'>" . $row['toys.item'] . "</div>\n";
}
array_push($data['toys'],$toys);
while($row = $at->fetch()){
$animals .= "<div class='animals' data-id = " . $row['animals.id'] . ">" . $row['animals.item'] . "</div>\n";
}
array_push($data['animals'],$animals);
echo json_encode($data);
Then on client side you can access the data as
data = JSON.parse(data);
$('#wrapfood').html(data.food);
$('#wraptoys').html(data.toys);
$('#wrapanimals').html(data.animals);
if you want to use a single select statement here is the solution... if you just want a color item and id
SELECT f.* from food f
UNION
SELECT a.* from animals a
UNION
SELECT t.id, t.color,t.item from toys t
WHERE t.color ="red" AND f.color="red" AND a.color="red"
if you want sn and date also
SELECT f.*,null,null from food f
UNION
SELECT a.*,null,null from animals a
UNION
SELECT t.* from toys t
WHERE t.color ="red" AND f.color="red" AND a.color="red"
if your columns of the tales are in the same order as you specified id, color, and item then no problem with the above queries otherwise if the order is different arrange the column names in select statement accordingly...
now you can still use the above query if you want to separate it only client site in the single loop... just concatenate in the select statement.
here is what you can do...
SELECT CONCAT("#food",f.id), CONCAT("#food",f.color),CONCAT("#food",f.item),null,null from food f
UNION
SELECT CONCAT("#animals",a.id),CONCAT("#animals",a.color),CONCAT("#animals",a.item),null,null from animals a
UNION
SELECT CONCAT("#toys",t.id),CONCAT("#toys",t.color),CONCAT("#toys",t.item),CONCAT("#toys",t.sn),CONCAT("#toys",t.date) from toys t
WHERE t.color ="red" AND f.color="red" AND a.color="red"
now we have concatenated the names of the tables with the column now when we display it we can easily filter them with their names...
this is how you filter them later on...
if(substr( $row['id'], 0, 5 ) === "#food"){
echo substr($row['id'],4);
}
I'm having this problem on how I can access a specific table cell when I get the column from a mysqli_fetch_array result and storing it in a variable.
$sql5 = "SELECT e.*, #curRow := #curRow + 1 AS row_number FROM employee e JOIN (SELECT #curRow := 0) r WHERE e.team_team_id = '$team_id' AND (position_pos_id = 3 or position_pos_id = 4 or position_pos_id = 5 or position_pos_id = 6 or position_pos_id = 7 or position_pos_id = 8 or position_pos_id = 9 or position_pos_id = 10 or position_pos_id = 11 or position_pos_id = 13 or position_pos_id = 14 or position_pos_id = 15 or position_pos_id = 16)";
$result5 = mysqli_query($connect, $sql5);
$row5 = mysqli_fetch_array($result5);
for($i=0;$i<$number;$i++){
echo "<select id='testingDiv".$i."' name='employee[]' class='clonedInput'>
<option value='".$row5['row_number'][$i]."'>" .$row5['emp_fname']. " " .$row5['emp_lname'] ."</option>";
while ($row3 = mysqli_fetch_array($result3)) {
echo "<option value='" . $row3['emp_id'] ."'>" .$row3['emp_fname']. " " .$row3['emp_lname'] ."</option>";
}
echo "</select><br>";
As you can see I was planning to iterate it through a counter and treat it like a 3d array but I found out that it wasn't possible. Now I'm at a lost as I don't know how to access the specific cell of the column.
To do what you want, you should use the structure of the inner loop in the outer one too
$result5 = mysqli_query($connect, $sql5);
$i = 0;
while ($row5 = mysqli_fetch_array($result5)) {
echo "<select id='testingDiv" . $i . "' name='employee[]' class='clonedInput'>
<option value='" . $i . "'>" .
$row5['emp_fname'] . " " . $row5['emp_lname'] .
"</option>";
while ($row3 = mysqli_fetch_array($result3)) {
echo "<option value='" . $row3['emp_id'] . "'>" .
$row3['emp_fname'] . " " . $row3['emp_lname'] .
"</option>";
}
echo "</select><br>";
$i++;
}
Edit (explaination of what's going on)
The main problem with your code is that mysqli_fetch_array returns a single row of the resultset, so you cannot use that result as a bidimensional array and access all the rows with the for loop you were using.
What you have to do is translate that outer for into a while loop, so that on each iteration you fetch a new row into that $row5 variable. By doing that, you need to handle the counter value manually, hence that $i++ at the end.
Regarding the translation of $row5['row_number'][$i] into $i, I guess you wanted to get the current row index. For the same reason I explained above, that instruction is wrong, because the $row5 variable contains a single row, which most likely won't have a 'row_number' column and definitely won't have a second dimension you can access with $i. The current row index however is already available in $i itself, so I used that counter instead.
I'm new to php and I want to separate the records with a comma.
Database:
the table in sql
I use this code to get the data:
<?php
$id = get_the_ID();
$sql = "SELECT *
FROM tablename
WHERE parent_id=$id";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result))
{
echo "Test: " . $row["value"]. "<br>";
}
mysqli_close($con);
?>
It return twice as:
Test: Test
Test: Test1
I want to separate the records with a ',' like this:
Test: Test, Test1
Store your values in an array and than implode with ",". You will get the result:
$id = get_the_ID();
$sql = "SELECT *
FROM tablename
WHERE parent_id=$id";
$result = $conn->query($sql);
$yourArr = array();
while($row = mysqli_fetch_array($result))
{
$yourArr[] = $row["value"];
//echo "Test: " . $row["value"]. "<br>";
}
echo "Test: ". implode(",",$yourArr);
You can do this entirely in MySQL using GROUP_CONCAT:
<?php
$id = get_the_ID();
$sql = "SELECT `parent_id`, GROUP_CONCAT(`value` SEPARATOR ', ') AS comma_separated_values
FROM tablename
WHERE `parent_id` = '$id'
GROUP BY `parent_id`";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result))
{
echo 'Test: ' . $row["comma_separated_values"]; // Test: test, test2
}
mysqli_close($con);
?>
You should change the "comma_separated_values" name to something more appropriate for your data.
In your particular case, you would not need the while() loop either as we're limiting the MySQL to a single row.
If you were to remove the WHEREparent_id= '$id' from the SQL query, then you could return the results of multiple parent_id values. For example:
while ($row = mysqli_fetch_array($result))
{
echo 'Parent ' . $row['parent_id'] .': ' . $row["comma_separated_values"] . '<br>';
}
Would return:
Parent 292: Test1, Test2
Parent 293: Test3, Test4
Parent 294: Test5, Test10, Test50
etc...
you can use update query for this
$query="Update tablename set value=CONCAT(value,',test1') where parentid='295'";
$result=mysqli_query($conn,$query);
I have two databases and tables in each. Am reading the renewal_date of DB1 table 1 and taking the renewal_date of the current month and domain_name for that record.
then am trying to retrieve the d_due_date from DB2 table2 for the domain_name selected from DB1 table1.
then i need to display domain_name, renewal_date,d_due_date in one table.
I can do this by joining the database with INNER JOIN.
what i need is to write separate select queries and display.
$sql = "select domain_name from table1 where MONTH(renewal_date) = '06'";
$result = mysqli_query($link_id,$sql);
if(!$result) die(sql_error());
$DoNM= Array();
$sql1= "select d_due_date from domains where d_domain IN ('abc.com','akaaasa.com')";
$result1 = mysqli_query($link_id1,$sql1);
if(!$result1) die(sql_error());
$DoNM1= Array();
echo '<table>';
while(($row1 = mysqli_fetch_array($result1,MYSQL_ASSOC))&&($row = mysqli_fetch_array($result,MYSQL_ASSOC))){
echo "<tr>";
echo "<td>" .$DoNM[]= $row['domain_name'] . "</td>";
echo "<td>" .$DoNM[]= $row['renewal_date'] . "</td>";
echo "<td>" .$DoNM1[]= $row1['d_due_date'] . "</td>";
echo "</tr>";
}
echo '</table><br />';
I have hardcoded the domain name in $sql1. what I want is to get that from $sql. how can I do that.
So all you need to do is process through the first query results and build the array, then convert the contents of the array to a comma delimited list
$sql = "select domain_name, renewal_date
from table1
where MONTH(renewal_date) = '06'";
$result = mysqli_query($link_id,$sql);
if(!$result) die(sql_error());
$db1= Array();
$InList = '';
while( $row = mysqli_fetch_array($result,MYSQL_ASSOC) ) {
$InList .= sprintf("'%s',", $row['domain_name']);
$db1[$row['domain_name']] = $row['renewal_date'];
}
$InList = rtrim($InList, ',');
$sql = "select d_due_date, d_name
from domains
where d_domain IN ($InList)";
$result = mysqli_query($link_id1,$sql);
if(!$result) die(sql_error());
echo '<table>';
while( $row = mysqli_fetch_array($result,MYSQL_ASSOC ){
echo '<tr>';
echo '<td>' . $row['d_name'] . '</td>';
// find the db1.renewal_date matching d_name from db1 array
echo '<td>' . $db1[$row['d_name']] . "</td>";
echo '<td>' . $row['d_due_date'] . '</td>';
echo "</tr>";
}
echo '</table><br />';
RE: Your comment
So now I have saved the data from db1 into an array you can use the get the db1.renewal_date from in the output phase. Also I added the db1.d_name to the second query so you have the key to the array containing the db1.renewal_date
RE: Using more fields from table1:
Sure, thats not a problem. This will mean that you have to store an array i.e. the $row as the data so you have the complete set of columns saved in the $db1 array.
$sql = "select domain_name, renewal_date, f3, f4
from table1
where MONTH(renewal_date) = '06'";
$result = mysqli_query($link_id,$sql);
if(!$result) die(sql_error());
$db1= Array();
$InList = '';
while( $row = mysqli_fetch_array($result,MYSQL_ASSOC) ) {
$InList .= sprintf("'%s',", $row['domain_name']);
$db1[$row['domain_name']] = $row;
}
$InList = rtrim($InList, ',');
The $db1 array will now look like this:
Array
(
[abc.com] => Array
(
[domain_name] => abc.com
[renewal_date] => 2015-06-06
[f3] => aaa
[f4] => bbb
)
[xyz.com] => Array
(
[domain_name] => xyz.com
[renewal_date] => 2015-06-07
[f3] => ccc
[f4] => ddd
)
)
So the domain name is still the KEY to each occurance of the array, but you have another array associated with the key rather than just a single string.
So to access this array you do this to use a domains specific columns.
echo '<td>' . $db1[ $row['d_name'] ] ['renewal_date'] . "</td>";
echo '<td>' . $db1[ $row['d_name'] ] ['f3'] . "</td>";
echo '<td>' . $db1[ $row['d_name'] ] ['f4'] . "</td>";
I hope that is explained well enough to help you.
First of all, you can do this in just one database with multiple tables which would be nicer and easier to use than you should be able to do something like:
SELECT domain_name,renewal_date,d_due_date
FROM table1 INNER JOIN table2
ON table2.d_name = table1.domain_name
WHERE MONTH(table1.renewal_date) = '06'";
Something like this(also see this as referance)
using where and inner join in mysql
I think that due to use of && operator in while loop. There may be one of the table's result is empty and that's why the result set may be empty.
So What I want to do is to echo 1 for the first row that is returned and two for the 2nd one and so one, Please I just don't know how to phrase this, I don't want to just count rows from mysql table, I want to give each row a number automatically and echo that number.
Please forgive my deprecated code.
$log = mysql_query("SELECT * FROM $table WHERE $columnid = '$id'") or die (mysql_error());
while($row = mysql_fetch_array($log)){
echo row['name'];
}
Lets assume that the above returns some names. so I want this.
1 : John
2 : Nancy
3 : Dave
I don't want to write those number.
Please take into account ORDER by rate DESC since I'm using that to descent the number by the biggest number of rate.
You could do:
$count = 1;
while($row = mysql_fetch_array($log)){
echo $count . ' ' . row['name'];
$count++;
}
Or:
echo '<ol>';
while($row = mysql_fetch_array($log)){
echo '<li>' . row['name'] . '</li>';
}
echo '</ol>';
$log = mysql_query("SELECT * FROM $table WHERE $columnid = '$id'") or die (mysql_error());
$c = 0
while($row = mysql_fetch_array($log)){
echo row['name'];
$c = $c + 1;
}
echo "Raw Count = ".$c