PHP Mysql WHILE loop remove the last separator - php

I have this code that get the data from mysql database.
<?php
$sql = mysql_query( "SELECT * FROM users WHERE name = $name" );
while ( $row = mysql_fetch_array( $sql ) ) {
echo $row[id] . '|';
echo $row[name] . '|';
echo $row[add] . ':';
}
OUTPUT : 12|jonathan|philippines:14|John|england:
?>
How can I remove the last separator of : using while?

$sql = mysql_query( "SELECT `id`, `name`, `add` FROM users WHERE name = $name" );
$data = array();
while ( $row = mysql_fetch_array( $sql, MYSQL_NUM ) )
{
$data[] = implode('|', $row);
}
echo implode(':', $data);
If you do it like this its a bit more robust, it doens't matter if you change your query right now... It will just output your fields in your wanted format

$sql = mysql_query( "SELECT * FROM users WHERE name = $name" );
$counter = 0;
while ( $row = mysql_fetch_array( $sql ) ) {
if ($counter > 0) {
echo ":";
}
echo $row[id] . '|' . $row[name] . '|' . $row[add];
$counter++;
}

<?php
$out = '';
$sql = mysql_query( "SELECT * FROM users WHERE name = $name" );
while ( $row = mysql_fetch_array( $sql ) ) {
$out.=$row[id] . '|';
$out.=$row[name] . '|';
$out.=$row[add] . ':';
}
echo substr($out,0,-1);
?>

$sql = mysql_query( "SELECT * FROM users WHERE name = $name" );
$number = mysql_num_rows($sql);
$i = 1;
while ($row = mysql_fetch_assoc($sql)) {
echo $row[id] . '|';
echo $row[name] . '|';
echo $row[add] ;
if($i < $number) {
echo ':';
}
$i++;
}

Related

php pdo loop through row skips 1st row

I am looping my rows from my database and it works except one thing. it skips the 1st id.
it begins from the second record. any idea how to fix this?
this is my code:
<?php
$query = $PDO->prepare('SELECT * FROM pokes');
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC)
?>
<?php
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$n = $row['name'];
$cp = $row['cp'];
echo $id . ' ' . $n . ' ' . $cp . '<br>';
}
?>
<?php
// your first error is here. You are fetching the first row
$row = $query->fetch(PDO::FETCH_ASSOC)
// And here you start from the second, since you already did ones above
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
//...rest of oyur code
}
?>
you have two way to accomplish your task
<?php
// Just add the PDO::FETCH_ASSOC constant while you are looping
while($row = $query->fetch(PDO::FETCH_ASSOC)){
//...Code here
}
// another way is adding the constant before using it
$query->setFetchMode(PDO::FETCH_ASSOC);
while($row = $query->fetch()){
//...Code here
}
?>
Remove
$row = $query->fetch(PDO::FETCH_ASSOC) after $query->execute();
just keep the while($row = $query->fetch(PDO::FETCH_ASSOC)) statement.
Your code should be like this:
<?php
$query = $PDO->prepare('SELECT * FROM pokes');
$query->execute();
?>
<?php
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$n = $row['name'];
$cp = $row['cp'];
echo $id . ' ' . $n . ' ' . $cp . '<br>';
}
?>
Don't fetch twice for a query.
<?php
$query = $PDO->prepare('SELECT * FROM pokes');
$query->execute();
foreach ($query as $row) {
$id = $row['id']; $n = $row['name']; $cp = $row['cp'];
echo $id . ' ' . $n . ' ' . $cp . '<br>';
}
?>

PHP output array into SELECT mysql

Need to find array, and then run a MYSQL SELECT where array values are present (or not present).
$symbol = "abc";
$sql = "SELECT * FROM around";
$results = $conn->query($sql);
foreach($results as $row) {
$stop = preg_replace("/[0-9]/", "", $row['tip']);
if ($stop == $symbol)
{$sword = $row['tip'];
}}
So we need $sword to serve as an array in the event that there are multiple outputs. After we have that array, we need to run a mysql query that shows only those that have $sword array.
$query = "
SELECT * FROM ms WHERE `big` = '$sword'";
$result = mysql_query( $query );
So then we can do something like:
while ( $row = mysql_fetch_assoc( $result ) ) {
echo '"time": "' . $row['time'] . '",'; }
Here's the code, converting $sword to an array and using it in your 2nd query:
$symbol = array("abc", "def", "ghi");
$sword = array();
$sql = "SELECT * FROM around";
$results = $conn->query($sql);
foreach($results as $row) {
$stop = preg_replace("/[0-9]/", "", $row['tip']);
if (in_array($stop, $symbol)) {
$sword[] = $row['tip'];
}
}
if ($sword) {
$in = '';
$sep = '';
foreach ($sword as $s) {
$in .= "$sep '$s'";
$sep = ',';
}
/* $in now contains a string like "'123abc123', '12abc12', '1abc1'" */
$query = "
SELECT * FROM ms WHERE `big` IN ($in)";
$result = mysql_query( $query );
while ( $row = mysql_fetch_assoc( $result ) ) {
echo '"time": "' . $row['time'] . '",';
}
}
Now I'm going to go wash my hands to get all that mysql_query off me... :-)

Php search query with range filter

I am trying to do a search query, but not sure how to put everything together. I am having problem with the range filter part.
What i am trying to achieve:
A search form that
1.) If field A,B(not empty) then put in the search query
2.) search through price column with (price lower range, price higher range)
include the results if it matches Field A,B(if it is not empty) and price(if it is in range).
(if search Fields A, B are empty then display all results that exist between range).
Thanks for your time.
The codes that i have now.
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
session_start();
include 'connect.php';
if($_POST)
{
$A = ($_POST['A']);
$B = ($_POST['B']);
$C = ($_POST['C']);
$pricelow = ($_POST['pricelow']);
$pricehigh = ($_POST['pricehigh']);
$sql = array();
if (!empty($A)) {
$sql[] = "A='$A'";
}
if (!empty($B)) {
$sql[] = "B='$B'";
}
if (!empty($C)) {
$sql[] = "C='$C'";
}
if (!empty($price)) {
for($i = pricelow; $i<pricehigh; $i++){
$price = $i;
}
$sql[] = "price='$price'";
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . $sql: '');
$result = mysqli_query($con,$sql);
$output = array();
// fetch your results
while( $row = mysqli_fetch_assoc($result) )
{
// add result row to your output's next index
$output[] = $row;
}
// echo the json encoded object
echo json_encode( $output );
}
?>
Edit:
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . $sql: '') . ("AND" 'price' BETWEEN "$pricelow" AND "$pricehigh");
Edit:
if (!empty($pricelow) || !empty($pricehigh)) {
$sql[] = $pricehigh>= 'price' and 'price'>=$pricelow ;
}
$sql = array();
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
session_start();
include 'connect.php';
if($_POST)
{
$A = ($_POST['A']);
$B = ($_POST['B']);
$C = ($_POST['C']);
$pricelow = ($_POST['pricelow']);
$pricehigh = ($_POST['pricehigh']);
$query = "SELECT * FROM Listing WHERE ";
$flag = 0;
if (!empty($A)) {
$query .= $flag==0?" A='$A' ":" AND A = '$A'";
$flag = 1;
}
if (!empty($B)) {
$query .= $flag==0?" B = '$B' ":" AND B = '$B'";
$flag = 1;
}
if (!empty($C)) {
$query .= $flag==0?" C='$C' ":" AND C= '$C'";
$flag = 1;
}
if ($flag == 0) {
$query .= " price > $pricelow AND price > $pricehigh"
}
$result = mysqli_query($con,$query);
$output = array();
// fetch your results
while( $row = mysqli_fetch_assoc($result) )
{
// add result row to your output's next index
$output[] = $row;
}
//your rest of the code
>?
I can't test it so, try and report the result!
You are creating an array of conditions and later you try to use that array as a string. This will not work, as the generated query is invalid. Take a look here, implode is a function which implodes an array using a separator. If you use " AND " as separator, then you will get the string you have desired. So, instead of:
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . $sql: '');
do the following:
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');
and your problem should be solved.
EDIT:
I have read your edit and I mean this code in particular:
if (!empty($pricelow) || !empty($pricehigh)) {
$sql[] = $pricehigh>= 'price' and 'price'>=$pricelow ;
}
$sql = array();
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');
After you build your array you are initializing it again, thus you lose all information you have processed earlier. Then you implode it twice, which is not needed. Try this way:
if (!empty($pricelow) || !empty($pricehigh)) {
$sql[] = $pricehigh>= 'price' and 'price'>=$pricelow ;
}
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');

how to print out two arrays in php concatenating them

I have two arrays in my php that I want to print. I want them to be concatenated but I don't know how. The array for the $names prints but the description array "$desc" does not. is there any way to print both together?
$query = "SELECT eName FROM Events";
$query2 = "SELECT eDescription FROM Events";
$result = mysql_query($query);
$result2 = mysql_query($query2);
$names = array();
$desc = array();
echo "hello there people!" . $query . " ".$result;
for($i=0; $i<sizeof($result); $i++){
echo $result[$i] ."\n" . $result2[$i];
}
while($entry = mysql_fetch_row($result)){
$names[] = $entry[0];
}
while($entry2 = mysql_fetch_row($result2)){
$desc[] = $entry2[0];
}
echo "Which Event would you like to see?<br>";
$stop = count($names);
//echo $stop . "\n";
$i = 0;
print_r($names);
print_r($desc);
foreach($names as $value){
echo $value . " " . $desc[i] ."<br>";
$i++;
}
Why are you doing two queries to get data from the same source?
$sql = mysql_query("select `eName`, `eDescription` from `Events`");
while($row = mysql_fetch_assoc($sql)) {
echo $row['eName']." ".$row['eDescription']."<br />";
}
Much simpler.
Try this:
foreach($names as $key => $value){
echo $value . " " . $desc[$key] ."<br />";
}
As long as the array $key match, the information will be printed together.

Can't figure out duplicate entries for data in SQL field, and random cell deletion (PHP/MYSQL)

I have an attendance page which outputs a list of students in a class through the following loop:
$sql10 = "SELECT class.name, student_to_class.class_id, student_to_class.student_id
FROM
student_to_class
INNER JOIN
class
ON class.id=student_to_class.class_id
WHERE
class.name = '$classid'";
$result10 = mysql_query($sql10) or die(mysql_error());
while ($row = mysql_fetch_array($result10)) {
$student = $row['student_id'];
$classid = $row['class_id'];
$sql3 = "select * from student where id = '$student'";
$result3 = mysql_query($sql3) or die(mysql_error());
$row3 = mysql_fetch_assoc($result3);
$studentfname = $row3['first_name'];
$studentlname = $row3['last_name'];
$sql4 = "select * from student where first_name = '$studentfname' AND last_name = '$studentlname'";
$result4 = mysql_query($sql4) or die(mysql_error());
$row4 = mysql_fetch_assoc($result4);
$studentrfid = $row4['rfid'];
$sql5 = "select * from class where id = '$classid'";
$result5 = mysql_query($sql5) or die(mysql_error());
$row5 = mysql_fetch_assoc($result5);
$class_name = $row5['name'];
//Define the default variables assuming attendance hasn't been taken.
$david = "select * from student where rfid='$studentrfid'";
$davidresult = mysql_query($david) or die(mysql_error());
$drow = mysql_fetch_assoc($davidresult);
if (($drow['excused'] == '1') && ($drow['excuseddate'] == $date)) {
//if($drow['excuseddate'] == $date;
$excusedabsense = '<option value="Excused Absense" label="Excused Absense" selected="selected">Excused Absense</option>';
} else {
$excusedabsense = '';
}
$presentpunctual = '<option value="Present" label="Present">Present</option>';
$presenttardy = '<option value="Tardy" label="Tardy">Tardy</option>';
$unexcusedabsense = '<option value="Absent" label="Absent">Absent</option>';
if (isset($_POST['editdate'])) {
$date = $_POST['date'];
}
$realfname = $studentfname;
$reallname = $studentlname;
$sql4 = "select * from attendance_main where StudentID = '$studentrfid' AND date = '$date' AND classID = '$class_name'";
$result4 = mysql_query($sql4) or die(mysql_error());
$row4 = mysql_fetch_assoc($result4);
if ($row4['status'] == "Present") {
$presentpunctual = '<option value="Present" label="Present" selected="selected">Present</option>';
} else {
$presentpunctual = '<option value="Present" label="Present">Present</option>';
}
if ($row4['status'] == "Tardy") {
$presenttardy = '<option value="Tardy" label="Tardy" selected="selected">Tardy</option>';
} else {
$presenttardy = '<option value="Tardy" label="Tardy">Tardy</option>';
}
if ($row4['status'] == "Absent") {
$unexcusedabsense = '<option value="Absent" label="Absent" selected="selected">Absent</option>';
} else {
$unexcusedabsense = '<option value="Absent" label="Absent">Absent</option>';
}
$b++;
echo "<tr>";
if (!isset($dateform)) {
$dateform = date('m/d/Y');
}
$date = date('m/d/Y');
echo '<td><iframe src="flag.php?&flagdate=' . $dateform . '&curdate=' . $date . '&class=' . $classid . '&flag=1&user=' . $studentrfid . '&curflag=' . $realrfid['flag'] . '&flagclass=' . $classname . '" width="50" height="30" frameborder="0" scrolling="no"> </iframe></td>';
//Yesterday
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$yesterdaysql' AND classID = '$class_name'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_yesterday = "N/A";
} else {
$tooltipresult_yesterday = $tooltiprow['status'];
}
//2 days
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$days2sql' AND classID = '$classid'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_2days = "N/A";
} else {
$tooltipresult_2days = $tooltiprow['status'];
}
//3 days
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$days3sql' AND classID = '$class_name'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_3days = "N/A";
} else {
$tooltipresult_3days = $tooltiprow['status'];
}
$tooltip = "<b>" . $yesterday . ":</b> " . $tooltipresult_yesterday . " - <b>" . $days2 . ":</b> " . $tooltipresult_2days . " - <b>" . $days3 . ":</b> " . $tooltipresult_3days;
echo "
<!-- Loop #" . $b . " --> <td><a href='#'";
?> onMouseover="ddrivetip('<?php
echo $tooltip;
?>')"; onMouseout="hideddrivetip()"> <?php
echo $realfname . " " . $reallname . "</a></td>";
echo '<td>
<select name="status' . $b . '">
' . $presentpunctual . '
' . $presenttardy . '
' . $excusedabsense . '
' . $unexcusedabsense . '
</select>
' . $hiddenfield . '
<input type="hidden" name="i" value="' . $b . '" />
<input type="hidden" name="studentid' . $b . '" value="' . $studentrfid . '">
<input type="hidden" name="classid" value="' . $class_name . '"></td>
<td><input type="text" name="comments' . $b . '" size="40" /></td></tr>
<!-- End Loop -->';
}
}
}
It essentially prints out student name and a drop down of statuses (if attendance was taken that day, the status will be whatever is set in the database). The date, flag, and tooltip functions are extra additions. (Date is for previous days, tooltip shows previous attendance on hover)
This data is being executed through the following loop:
if (isset($_GET['update'])) {
mysql_query("UPDATE teacher_accounts SET attendance = '1' WHERE username = '$username'") or die(mysql_error());
$error = 0;
$limit = $_GET['i'];
$starter = 0;
$num = 0;
while ($starter < $limit) {
$num++;
$statusinc = "status" . $num;
$studentinc = "studentid" . $num;
$commentsinc = "comments" . $num;
$starter++;
$studentID = $_GET[$studentinc];
$status = $_GET[$statusinc];
$comments = $_GET[$commentsinc];
$date = date("m/d/Y");
$sql = "select * from student where id = '$studentID'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$classid = $_GET['classid'];
if (isset($_GET['dateedit'])) {
$date = $_GET['dateedit'];
$count = "select * from attendance_main where StudentID = '$studentID' AND date = '$date' AND classID='$classid'";
$cresult = mysql_query($count) or die(mysql_error());
if (mysql_num_rows($cresult) > 0) {
$sql = "UPDATE attendance_main SET status='$status',comments='$comments',date='$date',classID='$classid' where StudentID = '$studentID'";
} else {
$sql = "INSERT INTO attendance_main (StudentID,status,comments,date,classID) VALUES ('$studentID','$status','$comments','$date','$classid')";
}
if (mysql_query($sql)) {
$return = "<h3>Successfully updated the attendance.</h3>";
}
} else {
$count = "select * from attendance_main where StudentID = '$studentID' AND date = '$date' AND classID='$classid'";
$cresult = mysql_query($count) or die(mysql_error());
if (mysql_num_rows($cresult) > 0) {
$sql = "UPDATE attendance_main SET status='$status',comments='$comments',date='$date',classID='$classid' where StudentID = '$studentID'";
if (mysql_query($sql)) {
$return = "<h3>Successfully updated the attendance for " . $num . " students.</h3>";
}
} else {
$sql = "INSERT INTO attendance_main (StudentID,status,comments,date,classID) VALUES ('$studentID','$status','$comments','$date','$classid')";
if (mysql_query($sql)) {
$return = "<h3>Successfully inserted today's attendance for " . $num . " students.";
}
}
}
}
echo $return;
For some reason, data is sometimes not being inserted properly. For example, a teacher might submit attendance on 02/08/2011, for a specific class, and certain students might appear twice under that attendance. This shouldn't be the case according to the code, because it should first check if they exist and, if they do, update the record rather than insert.
I've also seen cases where records are randomly deleted altogether. When a teacher takes attendance, all statuses are automatically set to Present. However, when I searched records on a certain date in the database, 2 students were missing records (which isn't even possible unless its being deleted)
Anyone have any idea why this might happen? I've tried replicating it myself (by repeatedly submitting the form, refreshing the page after it's processed, etc, to no avail.)
Thank you for the help!
Your query that check if a record exists is looking for all 3. 1) $studentID, 2) $classid and 3) $classid However the UPDATE statement is just looking for $studentID.
I would suggest you create a PRIMARY KEY (or UNIQUE INDEX) on StudentID,date,classID, then use the MySql INSERT ON DUPLICATE KEY UPDATE...
INSERT INTO attendance_main (StudentID,status,comments,date,classID)
VALUES ('$studentID','$status','$comments','$date','$classid')
ON DUPLICATE KEY UPDATE
status = VALUES(status),
comments = VALUES(comments)
Don't forget to sanitize the database input by using mysql_real_escape_string for example $status = mysql_real_escape_string($_GET[$statusinc]);.

Categories