Duplicating result due to loop - php

So my code get a value from previous page, compare it with a table field in the database and display success or failure. Here is the original code:
<?php
if ($_GET['q'] !='')
{
include('config.inc');
$foo = $_GET['q'];
$query= "INSERT INTO register(name) VALUES('$foo')";
$result = mysql_query("SELECT * FROM user_student");
while($row = mysql_fetch_array($result))
{
$id= $row['sid'];
if($id==$foo)
{
$res = mysql_query($query);
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
}
else echo "Invalid Command";
?>
Am having duplicating result e.g Student 1124 does not exist!! 10times. I've modify the code to:
while($row = mysql_fetch_array($result))
{
$id= $row['sid'];
if($id==$foo)
{
$res = mysql_query($query);
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
So i've placed the $res outside the loop to avoid duplication result but now it says: variable cannot be resolved Any suggestions?

A bit of changed version of CaldasGSM:
<?php
if (!empty($_GET['q']))
{
include('config.inc');
$foo = mysql_real_escape_string($_GET['q']);
$result = mysql_query("SELECT * FROM user_student WHERE sid = '{$foo}'");
$num_rows = mysql_num_rows($result);
if($num_rows > 0)
{
$res = mysql_query("INSERT INTO register(name) VALUES('$foo')");
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
else
{
echo "Invalid Command";
}
?>

maybe something like
<?php
if ($_GET['q'] !='')
{
include('config.inc');
$foo = $_GET['q'];
$result = mysql_query("SELECT * FROM user_student");
$bRecordExists = false;
while($row = mysql_fetch_array($result))
{
$id= $row['sid'];
if($id==$foo)
{
$bRecordExists = true;
break;
}
}
if($bRecordExists)
{
$res = mysql_query("INSERT INTO register(name) VALUES('$foo')");
if ($res)
{
echo 'Insertion ok';
}
else
{
echo " ";
echo "Attendance already taken for $foo";
}
}
else
{
echo " ";
echo "Student $foo does not exist!!";
}
}
else
{
echo "Invalid Command";
}
?>

Related

Storing Function value in a variable

My code generates only one result e.g "admin", then generates error. Would you please tell me how can i fix this and show all the result.
while($row = mysqli_fetch_assoc($query)) {
$role = $row['userrole'];
Function RoleFunction($roles){
if ($roles==1) {
echo " Admin";
}
else {
echo " User";
}
}
$test = RoleFunction($role);
echo "<tr>";
echo "<td>".$test."</td>";
echo "</tr>";
}
Result : Admin
Fatal error: Cannot redeclare RoleFunction() (previously declared in E:\xampp\htdocs\meds\delete.php:50) in
E:\xampp\htdocs\meds\delete.php on line 50
Keep your function RoleFunction($roles) outside of loop.
function RoleFunction($roles){
if ($roles == 1) {
return " Admin";
}
else {
return " User";
}
}
while ($row = mysqli_fetch_assoc($query)) {
$role = $row['userrole'];
// Print the role
echo "<tr><td>".RoleFunction($role)."</td></tr>";
}
Try the above code. It should be working.
I thin this will work...
Function RoleFunction($roles){
while($row = mysqli_fetch_assoc($query)) {
$role = $row['userrole'];
if ($roles==1) {
echo " Admin";
}
else {
echo " User";
}
$test = RoleFunction($role);
echo "<tr>";
echo "<td>".$test."</td>";
echo "</tr>";
}
}
your function is in loop, it should be outside loop like this:
function RoleFunction($roles){
if ($roles == 1) {
return "Admin";
} else {
return "User";
}
}
while ($row = mysqli_fetch_assoc($query)) {
$role = $row['userrole'];
// Print the role
echo "<tr><td>".RoleFunction($role)."</td></tr>";
}
It will work for sure

PHP+MySQL Printing query results

I used to print MySQL query results like this:
$query="SELECT fname,lname,email FROM users";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$i=0;
echo '<table BORDERCOLOR=black>';
?>
<tr>
<th>Vardas</th><th>Pavarde</th><th>E-Mail</th>
</tr>
<?php
while ($i < $num) {
$field1=mysql_result($result,$i,"fname");
$field2=mysql_result($result,$i,"lname");
$field3=mysql_result($result,$i,"email");
echo "<td>";
echo $field1;
echo "</td>";
echo "<td>";
echo $field2;
echo "</td>";
echo "<td>";
echo $field3;
echo "</td>";
echo "</tr>";
$i++;
}
echo "</table>";
But this time I have to use something different , and I was wondering how can I print out my results when using the function/query shown below:
Query code (in 'class DB'):
function query($querytext) {
$rs = mysql_query($querytext, $this->_link);
if($this->_debug) {
$this->addDebugMessage("\t<tr>\n\t\t<td class=\"debug_nr\">".$this->_queryCount++."</td>\n\t\t<td class=\"debug_queInfo\"><b>Query: (".#mysql_num_rows($rs).")</b></td>\n\t\t<td>" . htmlspecialchars($querytext) . "</td>\n\t</tr>\n");
if(mysql_error() != '') {
$this->addDebugMessage("\t<tr>\n\t\t<td class=\"debug_nr\">".$this->_queryCount++."</td>\n\t\t<td class=\"debug_queInfo\"><b>Error #".mysql_errno($this->_link)." :</b></td>\n\t\t<td>" . htmlspecialchars(mysql_error($this->_link)) . "</td>\n\t</tr>\n");
}
}
if($rs) {
$num_rows = #mysql_num_rows($rs);
if($num_rows) {
if($num_rows > 0) {
$rsarray = array();
while($line = mysql_fetch_array($rs , MYSQL_ASSOC)) {
array_push($rsarray, $line);
}
mysql_free_result($rs);
return $rsarray;
} else {
return false;
}
} else {
if(mysql_affected_rows($this->_link) > 0) {
return true;
} else {
return false;
}
}
} else {
return false;
}
}
(in 'class User')
function findUser($phrase){
global $DB;
$results=$DB->query("SELECT * FROM users WHERE fname LIKE '%'$phrase'%' OR lname LIKE '%'$phrase'%' OR email LIKE '%'$phrase'%'");
return $results;
}
In index.php (what do I use to print this out?):
$USER->findUser("john");
or maybe it should be
$results= $USER->findUser("john);
OR
$results=DB->findUser("john");
Seems you have a typo
function findUser($phrase){
global $DB;
$DB->query("SELECT * FROM users WHERE fname LIKE '%'$phrase'%' OR lname LIKE '%'$phrase'%' OR email LIKE '%'$phrase'%'");
}
There is extra quotes in your query.
function findUser($phrase){
global $DB;
$DB->query("SELECT * FROM users WHERE fname LIKE '%$phrase%' OR lname LIKE '%$phrase%' OR email LIKE '%$phrase%'");
}

php Deletion from database error

I am trying to delete a user from my simple E-commerce website for a project I am working on. When I click the delete button, the message appears and tells me that it correctly deleted the data from the table. But when I go into my sql database and check the data, its all still there. I cant figure out what I am doing wrong or where my error is. any help would be appreciated. My code is below.
<?php
session_start();
if (isset($_SESSION['shirt_users_id']) && isset($_SESSION['full_name'])) {
require('mysql_connect.php');
$title="List all registered users";
include_once("header_admin.php");
if (isset($_GET['shirt_users_id'])) {
$shirt_users_id = $_GET['shirt_users_id'];
function rollback_die($msg)
{
echo $msg;
global $link;
mysqli_query($link, "ROLLBACK");
mysqli_free_result($exec_select_sui);
mysqli_close($link);
include("footer_admin.php");
die();
}
function delete_records($array_refer)
{
global $link;
foreach ($array_refer as $key => $array_value) {
$table_name = substr($key, 0, -3);
foreach ($array_value as $value) {
$delete = "DELETE from $table_name where $key = $value";
$exec_delete = #mysqli_query($link, $delete);
if (!$exec_delete) {
rollback_die("Records from $table_name could not be deleted because of: ".mysqli_error($link));
}
}
}
return true;
}
#mysqli_query($link, "SET AUTOCOMMIT=0");
$select_sui = "SELECT shirt_users.shirt_users_id, shirt_users_types.shirt_users_types_id, shirt_orders.shirt_orders_id, shirt_shipping_addresses.shirt_shipping_addresses_id, shirt_billing_addresses.shirt_billing_addresses_id, shirt_credit_cards.shirt_credit_cards_id
from
shirt_users, shirt_users_types, shirt_orders, shirt_shipping_addresses, shirt_billing_addresses, shirt_credit_cards
where
shirt_users.shirt_users_id = shirt_users_types.shirt_users_id and
shirt_users_types.shirt_orders_id = shirt_orders.shirt_orders_id and
shirt_orders.shirt_shipping_addresses_id = shirt_shipping_addresses.shirt_shipping_addresses_id and
shirt_orders.shirt_billing_addresses_id = shirt_billing_addresses.shirt_billing_addresses_id and
shirt_orders.shirt_credit_cards_id = shirt_credit_cards.shirt_credit_cards_id and
shirt_users.shirt_users_id = $shirt_users_id";
$exec_select_sui = #mysqli_query($link, $select_sui);
if (!$exec_select_sui) {
rollback_die("A problem when retrieving records from the database for shirt user has occurred: ".mysqli_error($link));
} else {
$users = $gut = $orders = $shipping = $billing = $credit = array();
while ($one_row = mysqli_fetch_assoc($exec_select_sui)) {
$users[] = $one_row['shirt_users_id'];
$gut[] = $one_row['shirt_users_types_id'];
$orders[] = $one_row['shirt_orders_id'];
$shipping[] = $one_row['shirt_shipping_addresses_id'];
$billing[] = $one_row['shirt_billing_addresses_id'];
$credit[] = $one_row['shirt_credit_cards_id'];
}
$multi_array = array('shirt_users_id' => $users, 'shirt_users_types_id' => $gut, 'shirt_orders_id' => $orders, 'shirt_shipping_addresses_id' => $shipping, 'shirt_billing_addresses_id' => $billing, 'shirt_credit_cards_id' => $credit);
delete_records($multi_array);
echo "the record(s) of shirt user have successfully been deleted from the tables";
mysqli_query($link, "COMMIT");
}
}
(isset($_GET['sort']))?$sort = $_GET['sort']:$sort = 'ui';
(isset($_GET['bool']))?$bool = $_GET['bool']:$bool=true;
switch ($sort) {
case 'ui': ($bool)?$sort = "user_id ASC":$sort = "user_id DESC";
break;
case 'fn': ($bool)?$sort = "first_name ASC":$sort = "first_name DESC";
break;
case 'ln': ($bool)?$sort = "last_name ASC":$sort = "last_name DESC";
break;
case 'em': ($bool)?$sort = "email ASC":$sort = "email DESC";
break;
}
$select_users = "SELECT shirt_users_id, user_id, first_name, last_name, email from shirt_users order by $sort";
$exec_select_users = #mysqli_query($link, $select_users);
if (!$exec_select_users) {
echo "The user information could not be retrieved from the shirt_users table because of: ".mysqli_error($link);
mysqli_close($link);
include('footer_admin.php');
die();
} else {
echo "<div id='list_users'><table id='list_user' border='0'>";
echo "<tr>";
echo "<th><a href='".$_SERVER['PHP_SELF']."?sort=ui&bool=".!$bool."'>User ID</a></th>";
echo "<th><a href='".$_SERVER['PHP_SELF']."?sort=fn&bool=".!$bool."'>First Name</a></th>";
echo "<th><a href='".$_SERVER['PHP_SELF']."?sort=ln&bool=".!$bool."'>Last Name</a></th>";
echo "<th><a href='".$_SERVER['PHP_SELF']."?sort=em&bool=".!$bool."'>Email</a></th>";
echo "<th>Delete</th>";
echo "</tr>";
while ($one_row = mysqli_fetch_assoc($exec_select_users)) {
echo "<tr>";
echo "<td class='first'>".$one_row['user_id']."</td>";
echo "<td class='second'>".$one_row['first_name']."</td>";
echo "<td class='third'>".$one_row['last_name']."</td>";
echo "<td class='fourth'>".$one_row['email']."</td>";
echo "<td class='fifth'><a href='".$_SERVER['PHP_SELF']."?shirt_users_id=".$one_row['shirt_users_id']."'>Delete</a></td>";
echo "</tr>";
}
echo "<tr><td colspan = '4' class='footer'>Total number of users: </td><td class='footer'>".mysqli_num_rows($exec_select_users)."</td></tr>";
echo "</table></div>";
}
mysqli_free_result($exec_select_users);
} else {
echo "You are not an authentic administrator. Being directed to the login page...";
header("Refresh: 2; url='login.php'");
}
mysqli_close($link);
include("footer.php");
die();
?>
Also, I know my code is not the most efficient way to do things but im new to the whole html/css/php scene and am trying my best so please dont give me some off the wall answer about a differnt way to do this please!

MySQL Error: Duplicate 'Candidate Name'

I have created a MySQL database along with a front-end to manipulate it using PHP. However, while I can add content to the database manually, I cannot utilize my front-end. When I try to submit the data in my front-end's form fields, I receive the prompt "Duplicate Candidate Name."
The following PHP file is my general script for displaying the front-end:
<?php
if(isset($_POST['sbmtbtn']) && ($_POST['sbmtbtn'] != ""))
{
$desc = strip_tags($_POST['txtdesc']);
$date = glb_func_chkvl($_POST['txtdate']);
$first = glb_func_chkvl($_POST['txtfirst']);
$last = glb_func_chkvl($_POST['txtlast']);
$skill = glb_func_chkvl($_POST['txtskill']);
$sub1 = glb_func_chkvl($_POST['txtsub1']);
$sub2 = glb_func_chkvl($_POST['txtsub2']);
$person = glb_func_chkvl($_POST['txtperson']);
$company = glb_func_chkvl($_POST['txtcompany']);
$location = glb_func_chkvl($_POST['txtlocation']);
$complex = glb_func_chkvl($_POST['complex']);
$sts = glb_func_chkvl($_POST['lststs']);
$dt = date('Y-m-d');
$emp = $_SESSION['sesadmin'];
$sqryquestion_info
= "SELECT candi_first
FROM question_info
WHERE candi_first='$first'";
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "add"))
{
$srsquestion_info =mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
$gmsg = "<font color=red size=2>Duplicate Candidate Name . Record not saved</font>";
}
else
{
$iqryquestion_info="insert into question_info(
candi_first,candi_last,date,
skill,subtype_1,
subtype_2,person_int,
comp_name,loc_int,complex_lvl,
type_int,question_candi,q_crton,
q_crtby)
values('$first','$last','$date','$skill','$sub1','$sub2','$person','$company',
'$location','$complex','$sts','$desc','$dt','$emp')";
$irsquestion_info = mysql_query($iqryquestion_info);
if($irsquestion_info==true)
{
$gmsg = "<font color=green size=2>Record saved successfully</font>";
}
else
{
$gmsg = "<font color=red size=2>Record not saved</font>";
}
}
}
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "edit"))
{
$id = $_REQUEST['hdnedit'];
$pg = $_REQUEST['hdnpg'];
$countstart = $_REQUEST['hdncntstrt'];
$sqryquestion_info .=" and ques_id !=$id";
$srsquestion_info = mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
?>
<script>location.href="view_all_questions.php?sts=d&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";</script>
<?php
}
else
{
$uqryquestion_info="update question_info set
date ='$date',
candi_first ='$first',
candi_last ='$last',
skill ='$skill',
subtype_1 ='$sub1',
subtype_2 ='$sub2',
person_int ='$person',
comp_name ='$company',
loc_int ='$location',
complex_lel ='$complex',
type_int ='$company',
question_candi ='$desc',
q_mdfdon ='$dt',
q_mdfdby ='$emp' ";
$uqryquestion_info .= " where ques_id=$id";
$ursquestion_info = mysql_query($uqryquestion_info);
if($ursquestion_info==true)
{
?>
<script>location.href="view_all_questions.php?sts=y&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
else
{
?>
<script>location.href="view_all_questions.php?sts=n&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
}
}
/*********************************** End Editing ******************************************************/
}
?>
Here begins my "main file" for editing:
<?php
if(isset($_POST['sbmtbtn']) && ($_POST['sbmtbtn'] != ""))
{
$desc = strip_tags($_POST['txtdesc']);
$date = glb_func_chkvl($_POST['txtdate']);
$first = glb_func_chkvl($_POST['txtfirst']);
$last = glb_func_chkvl($_POST['txtlast']);
$skill = glb_func_chkvl($_POST['txtskill']);
$sub1 = glb_func_chkvl($_POST['txtsub1']);
$sub2 = glb_func_chkvl($_POST['txtsub2']);
$person = glb_func_chkvl($_POST['txtperson']);
$company = glb_func_chkvl($_POST['txtcompany']);
$location = glb_func_chkvl($_POST['txtlocation']);
$complex = glb_func_chkvl($_POST['complex']);
$sts = glb_func_chkvl($_POST['lststs']);
$dt = date('Y-m-d');
$emp = $_SESSION['sesadmin'];
$sqryquestion_info="select candi_first
from question_info
where candi_first='$first'";
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "add"))
{
$srsquestion_info =mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
$gmsg = "<font color=red size=2>Duplicate Candidate Name . Record not saved</font>";
}
else
{
$iqryquestion_info="insert into question_info(
candi_first,candi_last,date,
skill,subtype_1,
subtype_2,person_int,
comp_name,loc_int,complex_lvl,
type_int,question_candi,q_crton,
q_crtby)
values('$first','$last','$date','$skill','$sub1','$sub2','$person','$company',
'$location','$complex','$sts','$desc','$dt','$emp')";
$irsquestion_info = mysql_query($iqryquestion_info);
if($irsquestion_info==true)
{
$gmsg = "<font color=green size=2>Record saved successfully</font>";
}
else
{
$gmsg = "<font color=red size=2>Record not saved</font>";
}
}
}
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "edit"))
{
$id = $_REQUEST['hdnedit'];
$pg = $_REQUEST['hdnpg'];
$countstart = $_REQUEST['hdncntstrt'];
$sqryquestion_info .=" and ques_id !=$id";
$srsquestion_info = mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
?>
<script>location.href="view_all_questions.php?sts=d&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";</script>
<?php
}
else
{
$uqryquestion_info="update question_info set
date ='$date',
candi_first ='$first',
candi_last ='$last',
skill ='$skill',
subtype_1 ='$sub1',
subtype_2 ='$sub2',
person_int ='$person',
comp_name ='$company',
loc_int ='$location',
complex_lel ='$complex',
type_int ='$company',
question_candi ='$desc',
q_mdfdon ='$dt',
q_mdfdby ='$emp' ";
$uqryquestion_info .= " where ques_id=$id";
$ursquestion_info = mysql_query($uqryquestion_info);
if($ursquestion_info==true)
{
?>
<script>location.href="view_all_questions.php?sts=y&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
else
{
?>
<script>location.href="view_all_questions.php?sts=n&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
}
}
/*********************************** End Editing ******************************************************/
}
?>

PHP Query + IF ELSE

I Have a PHP file doing a query
function getFiles()
{
$solnid = $_GET[id];
$query = mysql_query("SELECT * FROM library WHERE libr_solutionId = '$solnid' AND libr_deleted IS NULL") or die(mysql_error());
$result = mysql_query($query);
if (mysql_num_rows($result)==0) {
echo "<br>No Related Links";
} else {
while($library = mysql_fetch_assoc($query)) {
echo "<span style=\"margin-bottom: 5px;\"><img src=\"images/icon-download-02.png\" align=\"absmiddle\" style=\"margin-right: 5px;\"><span>".$library[libr_c_title]."</span></span><br>";
echo "<br>";
}
}
}
I have tested the query in PHPMyAdmin and I get a result however when running the function in my page it only displays the 'No Related Links' statement any ideas anyone?
Here's the fixed code. :) The problem was that you used mysql_query on a Resource (the first mysql_query), and that will give 0 rows, or an exception..
function getFiles()
{
$solnid = $_GET['id'];
$result = mysql_query("SELECT * FROM library WHERE libr_solutionId = '$solnid' AND libr_deleted IS NULL") or die(mysql_error());
if (mysql_num_rows($result)==0) {
echo "<br>No Related Links";
} else {
while($library = mysql_fetch_assoc($result)) {
echo "<span style=\"margin-bottom: 5px;\"><img src=\"images/icon-download-02.png\" align=\"absmiddle\" style=\"margin-right: 5px;\"><span>".$library['libr_c_title']."</span></span><br>";
echo "<br>";
}
}
}
change your function to (change to lines)
function getFiles()
{
$solnid = $_GET[id];
$result = mysql_query("SELECT * FROM library WHERE libr_solutionId = '$solnid' AND libr_deleted IS NULL") or die(mysql_error());
if (mysql_num_rows($result)==0) {
echo "<br>No Related Links";
} else {
while($library = mysql_fetch_assoc($query)) {
echo "<span style=\"margin-bottom: 5px;\"><img src=\"images/icon-download-02.png\" align=\"absmiddle\" style=\"margin-right: 5px;\"><span>".$library[libr_c_title]."</span></span><br>";
echo "<br>";
}
}
}

Categories