How to avoid repetition in PHP while loop - php

I am trying to edit check box values using more than one while loop but I'm getting repeated values. How to block this repetition? Here is the code:
<tr>
<?php
$qqqq = mysql_query("select * from tbl_color ");
while($rr = mysql_fetch_array($qqqq)) {
$dara = $rr['color'];
$ids = $rr['id'];
$datas = mysql_query("select * from ifix_model_tbl where id='".$g_select_id."'");
while($rw = mysql_fetch_array($datas)) {
$fg = $rw['color'];
$ecolor = unserialize($fg);
foreach($ecolor as $ucolor) {
echo $ucolor = $ucolor['id'];
?>
<td width="130">
<input style="padding-top:100px" name="colo[]" type="checkbox" value="<?php echo $ids?>"
<?php if($ucolor == $ids){ echo 'checked="checked"'; } ?>
/ >
<?php echo $dara;?>
</td>
<?php
}
}
}
?>
</tr>
Now I am getting result like this:
I need the result like this:

Use the DISTINCT operator in MySQL:
$qqqq = mysql_query(" SELECT DISTINCT id, color FROM tbl_color ");
Note:
1) don't use mysql_* THEY ARE DEPRECATED. Use mysqli_* or PDO
2) try using column names in SELECT statement rather than using SELECT *. It will help to improve performance of your query.

Related

Two arrays in foreach loop.

I want to fill in the table. The database is filling the array, but this method didn't work. What is the problem? How to use foreach loop?
<?php
$a = $db->prepare("select *
from sabit_sayfalar
inner join alt_sayfa on sabit_sayfalar.sayfa_id = alt_sayfa.ustsayfaid");
$a->execute(array());
$b = $a->fetchALL(PDO::FETCH_ASSOC);
$c = $a->rowCount();
$q = $db->prepare("select *
from sabit_sayfalar
inner join alt_sayfa on sabit_sayfalar.sayfa_id = alt_sayfa.altsayfaid");
$q->execute(array());
$w = $q->fetchALL(PDO::FETCH_ASSOC);
$e = $q->rowCount();
if($c){
foreach($b as $w and $m as $n){
?>
<tbody>
<tr>
<td>
<?php echo $m["sayfa_adi"];?>
</td>
<td>
<?php echo ($n["sayfa_adi"]);?>
</td>
</tr>
<?php
}
}
?>
</tbody>
Here's what I came out with.
<?php
$firstQuery = $db->prepare("select *
from sabit_sayfalar
inner join alt_sayfa on sabit_sayfalar.sayfa_id = alt_sayfa.ustsayfaid");
$firstQuery->execute(array());
$firstQueryResults = $firstQuery->fetchALL(PDO::FETCH_ASSOC);
$firstQueryCount = $firstQuery->rowCount();
$secondQuery = $db->prepare("select *
from sabit_sayfalar
inner join alt_sayfa on sabit_sayfalar.sayfa_id = alt_sayfa.altsayfaid");
$secondQuery->execute(array());
$secondQueryResults = $secondQuery->fetchALL(PDO::FETCH_ASSOC);
$secondQueryCount = $secondQuery->rowCount();
if ($firstQueryCount > 0 && $secondQueryCount > 0) {
?>
<tbody>
<?php foreach ($firstQueryResults as $firstQueryKey => $firstQueryRow) { ?>
<tr>
<td>
<?php echo $firstQueryRow["sayfa_adi"];?>
</td>
<td>
<?php echo ($secondQueryResults[$firstQueryKey]["sayfa_adi"]);?>
</td>
</tr>
<?php
}
}
?>
</tbody>
I changed the names of the variables for readability, and I adapted the table for using the information you provided... there are still some flaws connected with indexes that might be different for each SELECT, but that is another problem.
I also interpreted some variables that were missing as the variables you had but, for some reason, wrote wrong.
you cannot be used and in a foreach i think you want to use 2 foreach here and your <tbody> should be out of the loop

PHP passing Array

I have two php page.
In the first I have looping checkbox array :
<td><input type="checkbox" name="cek[]" value=" <?php echo "$kodeinventarisit" ?>"></td>`
Then i submit form from page one to page two :
<?php
include 'koneksi.php';
$cek = $_POST['cek'];
$jumlah_dipilih = count($cek);
for($x=0;$x<$jumlah_dipilih;$x++){
$jojo = $cek[$x];
$coba = "select * from msstok where kodeinventarisit = '$jojo' ";
$cobaquery = mysql_query($coba);
$hasil = mysql_fetch_array($cobaquery);
$jenis = $hasil['jenis'];
?>
<input name="kode" type="text" id="license" value="<?php echo htmlentities($jenis) ; ?>" readonly="readonly" />
<?php
echo "$jojo";
}
?>
The problem is in the sql query return nothing, I try echo "$jojo" and it's print the value but in the text field is empty..
Does anyone have suggestions on how to fix this?
Thank You Very Much
1
What you are doing is bad.
Load your data before your loop and loop every result to print them.
2
Protect your sql request from injection.
Connect
$db = new mysqli("","root","","");
Prepare your request
$sql = "select * from msstok where kodeinventarisit = ? ";
$res = $db->prepare($sql);
$res->bind_param("sssd",$jojo);
Get results
$res->execute();
Documentation : http://php.net/manual/fr/book.mysql.php
If you want to pass the array you need to check if arrive in you second page.
<pre>
print_r($_POST['cek']);
</pre>
Now, if arrive here, you can read the values like this:
<?php
// If is array(), then you can go to loop
if(is_array($_POST['cek']))
{
// Run the loop
foreach($_POST['cek'] as $value)
{
// Show values per line
echo $value. "<br/>";
}
}
?>
You can read only 1 value of your array
<?php echo $_POST['cek'][0]; ?>
<?php echo $_POST['cek'][1]; ?>
<?php echo $_POST['cek'][2]; ?>
Conclusion
You can't pass array to SQL in query. If you want to use it, this is the only way with implode.
$coba = "SELECT * FROM msstok WHERE kodeinventarisit IN (".implode(',', $jojo).")";
$records = mysql_query($coba, $connection);
while ($row = mysql_fetch_array($records)) {
echo "Name: " . $rows['name'] . "<br />"; // replace the name for column you want
}

Search MySQL database with LIKE statement

I need to return search results of users in my database.
At the moment, I have managed to use the LIKE function in the MySQL query to return a results count, but I need it to echo the usernames of all the results, not just the first result:
<?php
// mysql details
$host="localhost"; // Host name
$username="classified"; // Mysql username
$password="classified"; // Mysql password
$db_name="jaycraftcommunity"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// form variable to local
$search = $_POST['username'];
// make query
//$sql = "SELECT * FROM $tbl_name WHERE (username='$search' OR verified='$search')"; // sql query
$sql = "SELECT username FROM $tbl_name WHERE username LIKE '%$search%'"; // sql query
$result = mysql_query($sql); // do query
// handle query data
$count = mysql_num_rows($result);
$row = mysql_fetch_row($result);
$array = mysql_fetch_array($result);
echo $count;
foreach( $row as $arrays ): ?>
<tr>
<td><?php echo htmlspecialchars( $arrays ); ?></td>
<br />
</tr>
<?php
endforeach;
?>
The HTML form looks like this:
<h2>Search</h2>
<form method="post" action="search_engine.php">
Search for:
<input type="text" name="username">
<input type="submit" value="Search for username">
</form>
At the moment, if you go to http://dev.jaycraft.co/player/dupe/search.php you can see it in action. Search for individual letters, it show how many results there are with echo $count, but only echos the first result.
Thanks
Every call of mysql_fetch_row($result) will return another row and advance the cursor. You simply need to use a while() to loop over all rows in the result:
while($row = mysql_fetch_row($result)) {
echo $row[0];
}}
For ease of use, it's better to use mysql_fetch_assoc($result); which will return an associative array:
while($row = mysql_fetch_assoc($result)) {
echo $row['username'];
}}
You can
<?php
$sql = mysql_query($sql);
while($row = mysql_fetch_assoc($sql)){
echo $row['username'].'<br />';
}
?>
But please use mysqli instead of mysql! http://www.php.net/manual/en/book.mysqli.php
When you are using the prepare line, the above solutions do not work, given the substitution symbol is the same as the like symbol. Try making the search parameter within the prepare, by preformating it as a string. Then just loop through the available rows by the foreach or for loop.
$Table_Name = $wpdb->prefix.'tablename';
$SearchField = '%'. $YourVariable . '%';
$sql_query = $wpdb->prepare("SELECT * FROM $Table_Name WHERE ColumnName LIKE %s", $SearchField) ;
$rows = $wpdb->get_results($sql_query, ARRAY_A);
if(!empty($rows))
{
$TotalRows = $wpdb->num_rows;
foreach($rows as $row)
{
echo $row['field name'];
}
}
you need a while loop through your rows:
while($row = mysql_fetch_array($result){
foreach( $row as $cell): ?>
<tr>
<td><?php echo htmlspecialchars( $cell); ?></td>
<br />
</tr>
<?php
endforeach;
?>
}
mysql_fetch_row and mysql_fetch_array are almost unique functions, they both get the next row from the result set. you could use mysql_fetch_assoc to fetch the values with as key the database column name. (this is recommended)

Creating a table with PHP foreach function

I'm in a class called database programming. We got a data set and and put it into our servers. Now I have to use a jquery plugin to help visualize that data. I am using Graph Us plugin and trying to use the "Fill In" option.
My professor helped me create this function:
<?php
include 'connect.php';
$country_query = "SELECT DISTINCT Country FROM FemaleMaleRatioNew";
$result = mysqli_query($sql_link, $country_query);
$new_row = array();
while ($row = mysqli_fetch_assoc($result)) {
$country = $row['Country'];
$query = sprintf("SELECT Year, Value FROM FemaleMaleRatioNew WHERE Country = '%s'", $country);
$country_result = mysqli_query($sql_link, $query);
while ($country_row = mysqli_fetch_assoc($country_result) ) {
$new_row[$country][] = array('year' => $country_row['Year'],
'value'=> $country_row['Value']
);
}
}
//print_r($new_row);
?>
the print_r($new_row); is only there to make sure it works and it does, it prints out the array when activated.
He then guided me to create the table like this:
<body>
<table id="demo">
<?php foreach($new_row as $row):?>
<tr>
<td><?=$row['year'];?></td>
<td><?=$row['country'];?></td>
</tr>
<?php endforeach;?>
</table>
<script type="text/javascript">
$(document).ready(function() {
// Here we're "graphing up" only the cells with the "data" class
$('#demo td').graphup({
// Define any options here
colorMap: 'heatmap',
painter: 'fill',
// ...
});
});
</script>
</body>
What else do I need to do to get the table to work? I can't seem to figure it out. All it does is come out blank.
I'm sorry if this question isn't worded correctly or if I have not been clear on anything please let me know.
You have multiple rows for each country in your $new_row variable. You have to iterate over countries first and then over the individual rows of data:
<?php foreach($new_row as $country => $rows): ?>
<?php foreach($rows as $row): ?>
<tr>
<td><?=$country;?></td>
<td><?=$row['Year'];?></td>
<td><?=$row['Value'];?></td>
</tr>
<?php endforeach;?>
<?php endforeach;?>
Also please note that you need colon ':' not semicolon ';' after the foreach statement. This syntax (which is less known) is described here: http://php.net/manual/en/control-structures.alternative-syntax.php
If you want to display some sort of aggregate (for example sum) per country and you want to calculate it in PHP (as opposed to MySQL) you can do it like this:
<?php foreach($new_row as $country => $rows):
$sum = 0;
foreach($rows as $row):
$sum += $row['Value'];
endforeach;
?>
<tr>
<td><?=$country;?></td>
<td><?=$sum;?></td>
</tr>
<?php endforeach;?>
You should be using a single JOINed query to do this stuff, but you may not have gotten that in class yet. Since it's homework, I won't give you the flat-out answer, but here's the pseudo-code:
$countries = SELECT DISTINCT Country FROM YourTable;
while($country_row = fetch_row($countries)) {
echo $country_row['Country'];
echo <table>;
$status = SELECT Year, Value FROM YourTable WHERE Country=$country_row['Country'];
while($stats_row = fetch_row($status) {
echo <tr><td>$stats_row['Year']</td><td>$stats_row['Value']}</td>
}
echo </table>
}

msql fetch array no longer listing all results

I have a code that I have used over and over again before and now it's messing up. All I want to do is list information from the database into the table on the page, but now it will only show one result, instead of all the results it has found.
<table>
<tr><td style="background-color:#009745; color:#FFFFFF"><center><strong>Address Book</strong></center></td></tr>
<tr>
<?php
$getids = mysql_query("SELECT id, first_name, last_name FROM accounts WHERE s1='$id' ORDER BY id DESC", $db);
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
?>
<td><?= $ab_id ?> - <?= $ab_fn . " " . $ab_ln ?></td>
<?php
} else {
?>
<td><center>No Contacts</center></td>
<?php
}
?>
</tr>
</table>
please help me with this.
Thank You for your help :)
I love this site!! I can always get answers when I need them.
I saw two thing wrong
you are using mysql_fetch_array and later you are using string indexes to print the result
print the things in loop it is overriding values and just storing last row
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_assoc($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
echo '<td>'.$ab_id.' -'. $ab_fn.''.$ab_ln.' </td>';
}
In this messy code you're closing the while loop too early:
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
Only the last retrieved row is used later on. Also, don't use mysql_fetch_array if you're not accessing the numeric indeces of your result. Use mysql_fetch_assoc instead.

Categories