One roll number cant be added again [duplicate] - php

This question already exists:
Closed 10 years ago.
Possible Duplicate:
same roll number can not be added
I want my code to behave this way that if once i had added a roll number, it can not be added again in the registration..........same as if once an email adress is registered the error displays that EMAIL ADDRESS ALREADY BEEN TAKEN....
I am creating a function . of roll numbr value is 1 it shall display error and if not 1 it shall not display the error
function selectroll($studentname,$rollnumber)
{
$sql = "SELECT * FROM tblstuden WHERE studentname = 'studentname' and rollnumber = '$rollnumber';";
$obj_db = new DB();
$obj_db->query($sql);
$row = $obj_db->rsset();
if{
$val = 1;
}
else{
$val = 0;
}
$obj_db->db_close();
return $val;
}
$this->_id($row[id]);
$this->_studentname($row[studentname]);
$this->_rollnumber($row[rollnumber]);
$this->_classname($row[classname]);
$obj_db->db_close();
}
}
?>
and the function is called at the page by this method
<?php
if(isset($_POST['btnSubmit']) and $_GET['action'] == "Add")
{
$val = $Tblstuden->selectroll($_POST['studentname'],$_POST['rollnumber']);
if ($val =='1')
{
$Tblstuden->copyPostData();
$Tblstuden->insert();
echo"asdf";
}
redirect("index.php?page=studentlist");
}
else
{
echo"abc";
}
?>

You probably want
function selectroll($studentname,$rollnumber)
{
$sql = "SELECT * FROM tblstuden WHERE studentname = 'studentname' and rollnumber = '$rollnumber';";
$obj_db = new DB();
$obj_db->query($sql);
$row = $obj_db->rsset();
if ($row){
$val = 1;
$this->_id($row[id]);
$this->_studentname($row[studentname]);
$this->_rollnumber($row[rollnumber]);
$this->_classname($row[classname]);
}
else{
$val = 0;
}
$obj_db->db_close();
return $val;
}
}
?>
in line 8 of the top function - as otherwise the code won't compile.
Sub-note, your code is subject to mysql injection, you should look at using PDO (http://php.net/manual/en/book.pdo.php) for your database functions before you get used to the old method. Please. Do it now ;)

Related

Problem during creating Pyramid Star Patterns in PHP [duplicate]

This question already has answers here:
PHP Displaying a number of asterisks depending on the number given in the input field
(4 answers)
Closed 11 months ago.
Question :
My Code :
<html\>
Enter the number of rows:
<?php
if($_POST)
{
$row = $_POST['row'];
if(!is_numeric($row))
{
echo "Make sure you enter a NUMBER";
return;
}
else
{
for($row=0;$row<=1;$row++){
for($j=0;$j<=$row;$j++){ echo "#"; } echo ""; }}}?>
The problem is it's showing only two rows
I expected as shown in the photo
$row = 10;
for($i=0;$i<=$row;$i++){
for($j=0;$j<=$i;$j++){ echo "#"; } echo "<br>"; }
You are overriding the $row variable.
Also, you don't need the else since you are returning in case the if(!is_numeric) is true;
This should do it.
if(isset($_POST['row'])) {
$rows = $_POST['row'];
if(!is_numeric($rows))
{
echo "Make sure you enter a NUMBER";
return;
}
for($row=0;$row<=$rows;$row++){
for($j=0;$j<=$row;$j++){
echo "#";
}
echo "\n";
}
}
You can make use of the PHP function str_repeat to simplify the script.
This would only take 1 loop, so you don't get confused with the variable names.
$row = 10;
$i = 1;
while ($i <= $row)
{
echo str_repeat("#", $i); echo "\n";
$i ++;
}
Working Example here.

Header may not contain more than a single header, new line detected error [duplicate]

This question already has answers here:
getting warning "Header may not contain more than a single header, new line detected"
(9 answers)
Closed 9 months ago.
I managed to get every other error ironed out, but I am stuck with this error! For the life of me, I cannot seem to diagnose where I went wrong. Any help from you brilliant people out there would be amazing!
I made a form editing php where it is supposed to edit a submission made into the system. This is then processed by my processing php but for some reason I am getting a "header may not contain more than a single header" error in my form submission. I changed the header code multiple times but I do not know why I am still getting it: https://imgur.com/reX4Yyb
Edit:
Also wanted to add that this code was working fine for about a month. The only thing I changed was updating the hosting service platform from PHP 7.3 -> PHP 7.4. I tried reverting and it exactly the same error.
if($_POST['form_submitted'] == 'editgroupreferral'){
include("../../inc/inc.con.php");
/* assign values to checkboxes */
if(isset($_POST['OtherServices'])){
$otherservices = 1;
} else {
$otherservices = 0;
}
if(isset($_POST['Medication'])){
$medication = 1;
} else {
$medication = 0;
}
if(isset($_POST['HaveAllergies'])){
$allergies = 1;
} else {
$allergies = 0;
}
if(isset($_POST['Device'])){
$device = 1;
} else {
$device = 0;
}
if(isset($_POST['Share'])){
$share = 1;
} else {
$share = 0;
}
if(isset($_POST['TakeTurns'])){
$taketurns = 1;
} else {
$taketurns = 0;
}
if(isset($_POST['Wait'])){
$wait = 1;
} else {
$wait = 0;
}
if(isset($_POST['MultInstructions'])){
$multinstr = 1;
} else {
$multinstr = 0;
}
if(isset($_POST['SitChair'])){
$sitchair = 1;
} else {
$sitchair = 0;
}
if(isset($_POST['Routine'])){
$routine = 1;
} else {
$routine = 0;
}
/* insert vars from form into ReferralSC table */
$sql = "UPDATE ReferralGR SET
ReferrerName = :refname,
ReferrerRelationship = :refrelationship,
ReferrerPhone = :refphone,
ReferrerEmail = :refemail,
ReferMethod = :refmethod,
RefSupport = :refsupp,
OtherServices = :otherservices,
School = :school,
Diagnosis = :diagnosis,
Medication = :medication,
MedicationList = :medicationlist,
HaveAllergies = :allergies,
AllergiesList = :allergieslist,
Device = :device,
Share = :share,
TakeTurns = :taketurns,
Wait = :wait,
MultInstructions = :multinstr,
SitChair = :sitchair,
Routine = :routine,
ExplainFurther = :explain,
HeardAbout = :heardabout,
RefNotes = :notes
WHERE ref_id = :grid";
$s = $pdo->prepare($sql);
$s->bindvalue(':refname', $_POST['ReferrerName']);
$s->bindvalue(':refrelationship', $_POST['ReferrerRelationship']);
$s->bindvalue(':refphone', $_POST['ReferrerPhone']);
$s->bindvalue(':refemail', $_POST['ReferrerEmail']);
$s->bindvalue(':refmethod', $_POST['ReferMethod']);
$s->bindvalue(':refsupp', $_POST['RefSupport']);
$s->bindvalue(':otherservices', $otherservices);
$s->bindvalue(':school', $_POST['School']);
$s->bindvalue(':diagnosis', $_POST['Diagnosis']);
$s->bindvalue(':medication', $medication);
$s->bindvalue(':medicationlist', $_POST['MedicationList']);
$s->bindvalue(':allergies', $allergies);
$s->bindvalue(':allergieslist', $_POST['AllergiesList']);
$s->bindvalue(':device', $device);
$s->bindvalue(':share', $share);
$s->bindvalue(':taketurns', $taketurns);
$s->bindvalue(':wait', $wait);
$s->bindvalue(':multinstr', $multinstr);
$s->bindvalue(':sitchair', $sitchair);
$s->bindvalue(':routine', $routine);
$s->bindvalue(':explain', $_POST['ExplainFurther']);
$s->bindvalue(':heardabout', $_POST['HeardAbout']);
$s->bindvalue(':notes', $_POST['RefNotes']);
$s->bindvalue(':grid', $_POST['ref_id']);
$s->execute();
header('location:../refer_gr/referral-view.php?rid=' . $_POST['ref_id'] );
}
This warning occurs to indicate that you might have a new line [/n] in the string content of your variables. The solution is to strip out the passable new line contents of the variable Like this
$val=$_POST['ref_id'];
$url="../refer_gr/referral-view.php?rid='$val'";
$url=str_replace(PHP_EOL, '', $url);
header("Location: $url");
Okay, this one was a toughie but I figured it out. Here is my method:
So the clue lies in the error itself. It was pointing me from my processing php. But it was only because the data being asked in the header (requires a reference ID) is wrong.
The problem was in the reference ID (after much debugging). It was taking the wrong value from the wrong variable. This was in the php form page not the php processing page.
So here is the solution:
$s->bindvalue(':refid', $refid);
Rest of the code:
<input type="hidden" name="ref_id" value="<?php echo $rid; ?>" >
The variable $rid is not the same as the variable $refid.
Here is the fix:
<input type="hidden" name="ref_id" value="<?php echo $refid; ?>" >
This means that with this type of error, it might be worth looking at which part of the code it is trying to get the value from and start debugging from there.
Thanks for the help everyone!

php error insert data with value including addition sign (+) to database

There is an error while i insert "3 + 1 room" or update description area with "3 + 1 room" in MySQL database.
I saw there is no addition sign "+" in MySQL log (data inserted in database)
UPDATE testtable set status='0',title='3 1 room',
description='3 1 Daire. 1 Balkon kapalı.' WHERE id='60';
create table testtable ( id int(11), status tinyint(4), title varchar(20),
description text) ENGINE=InnoDB DEFAULT CHARSET=utf8
php file
$baglanti=new PDO("mysql:host="localhost";dbname="test";charset=utf8",$us
ername,$passwd) or die("error");
$val=$baglanti->exec("UPDATE testtable set status='0',title='$title',
description='$dest' WHERE ad_no='$ad_no' ");
return $val;
What should I do?
EDIT
update.php
<?php
include("database.php");
$fields = array();
$values=array();
$fvalue=$_POST['id'];
$table=$_POST['table'];
foreach ($_POST as $key => $value) {
if( $key!='table' && $key!='id' && $key!='alan'){
if( strpos($key,"date")){
$datet=new DateTime($value);
$value=$datet->format('Y-m-d');
}
array_push($fields,$key);
array_push($values,$value);
}
}
$alan=$_POST['alan'];
$ID=Updt($table,$fields,$values,$alan,$fvalue);
if($ID!=0){
echo $ID;
}
?>
database.php
<?php
$baglanti=new PDO("mysql:host="localhost";dbname="test";charset=utf8",$us
ername,$passwd) or die("error");
#UPDATE
function Updt($table,$set,$value,$field,$fvalue){
$bag=$GLOBALS['baglanti'];
$sts='';
if(is_array($set)){
for ($i=0; $i < count($set); $i++) {
$sts.=$set[$i]."='".$value[$i]."',";
}
$sts=rtrim($sts,",");
}else{
$sts=$set."='".$value."'";
}
$val=$bag->exec("UPDATE $table set $sts WHERE $field='$fvalue'");
return $val;
}
?>
this one, programmers wrote code. I try to take question parts from all code. There were lots of codes in file.
My guess is that you are not generating the query you think you are.
This should allow you to see the query.
I have also added some error checking, that really should be used in this code.
I have amended the connection line as I am sure a newline in the middle of the $username variable will cause an error.
database.php
<?php
try {
$baglanti = new PDO("mysql:host=localhost;dbname=test;charset=utf8",
$username,$passwd);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
#UPDATE
function Updt($table,$set,$value,$field,$fvalue){
$bag = $GLOBALS['baglanti'];
$sts='';
if(is_array($set)){
for ($i=0; $i < count($set); $i++) {
$sts.=$set[$i]."='".$value[$i]."',";
}
$sts=rtrim($sts,",");
}else{
$sts=$set."='".$value."'";
}
$sql = "UPDATE $table set $sts WHERE $field='$fvalue'";
echo $sql; // you can comment this line out when you are sure the SQL is good
$val = $bag->exec($sql);
return $val;
}
?>
update.php
Small amendment here just so you know whats actually being returned from the function is a count and not a row ID. It could also be FALSE, indicating an error occured in the Updt() function in the query.
<?php
include("database.php");
$fields = array();
$values=array();
$fvalue=$_POST['id'];
$table=$_POST['table'];
foreach ($_POST as $key => $value) {
if( $key!='table' && $key!='id' && $key!='alan'){
if( strpos($key,"date")){
$datet=new DateTime($value);
$value=$datet->format('Y-m-d');
}
array_push($fields,$key);
array_push($values,$value);
}
}
$alan=$_POST['alan'];
//$ID=Updt($table,$fields,$values,$alan,$fvalue);
// this is not an ID it is a coumt of the number or rows
// updated by the Updt() function
$cnt = Updt($table,$fields,$values,$alan,$fvalue);
if ( $cnt === FALSE ) {
// then we had an error in Updt()
print_r($baglanti->errorInfo(), true);
exit;
}
if($cnt != 0){
echo 'Rows updated = ' . $cnt;
}
?>
I have to mention this as others will if I dont. Your code is open to SQL Injection you should really be using prepared statements. Maybe you should mention this to the Programmers you mentioned. Maybe you should also not assume everything they wrote was done correctly.

Users get pass simple If check

I have a browser game where you can upgrade your attack,defence,spies and patrol by clicking on submit button. every upgrade cost X gold and X food.
this is the address to the game (it's in hebrew):
http://www.mafia.co.il
In the last few days some users found a way to upgrade it without having enough gold/food. The result is that they have minus in that resource of the game. ofcourse I thought I blocked this option.
also, for some reason they are able to upgrade it more then 10 times - when you'll read the code you'll see that I at least try to block that option.
Please does someone have any idea where is the problem?
This is the upgrade code (I translate the hebrew parts to english, I also added notes):
the reason for the foreach loop is to get the name of the $_POST.
elseif (isset($_POST['attack']) || isset($_POST['defence']) || isset($_POST['spies']) || isset($_POST['patrols'])) {
// Get user details
$ud = details($user_id);
foreach($_POST as $name => $val) {
// Number came with ','. So here i'm removing it.
$pr['gold'] = str_replace(',','',get_upg_price($ud['cvl'][$name]));
$pr['food'] = str_replace(',','',get_upg_price($ud['cvl'][$name]));
// Check if the user has enough food and gold.
if (check_rsc($pr,$ud)) {
// Check if user has maximum upgrade possible.
if ($ud['cvl'][$name] < 10) {
mysql_query("UPDATE `civ_level` SET ".$name."=".$name."+1 WHERE ID='".$user_id."'");
mysql_query("UPDATE `resources` SET gold=gold-'".$pr['gold']."', food=food-'".$pr['food']."' WHERE ID='".$user_id."'");
update_power($user_id);
} else {
$error = "<tr><td colspan='8' style='color:black; background: #CC3333; border:1px solid white;'>you are at maximum possible upgrade.</td></tr>";
}
} else {
$error = "<tr><td colspan='8' style='color:black; background: #CC3333; border:1px solid white;'>You dont have enough resources.</td></tr>";
}
}
}
Function details:
function details($id) {
$select1 = mysql_query("SELECT * FROM `users` WHERE ID='".$id."'");
$sel = mysql_fetch_array($select1);
$array['usr'] = $sel;
$select2 = mysql_query("SELECT * FROM `user_d` WHERE ID='".$id."'");
$sel2 = mysql_fetch_array($select2);
$array['usd'] = $sel2;
$select3 = mysql_query("SELECT * FROM `resources` WHERE ID='".$id."'");
$sel3 = mysql_fetch_assoc($select3);
$array['rsc'] = $sel3;
$select4 = mysql_query("SELECT * FROM `train_price`");
$sel4 = mysql_fetch_assoc($select4);
$array['trp'] = $sel4;
$select5 = mysql_query("SELECT * FROM `civ_level` WHERE ID='".$id."'");
$sel5 = mysql_fetch_array($select5);
$array['cvl'] = $sel5;
if (empty($array['usd'])) {
return false;
} else {
return $array;
}
}
Function get_upg_price:
function get_upg_price($level) {
$a = 0;
$price = 100;
while ($a<$level) {
$price = $price*3;
$a++;
}
return number_format($price);
}
Function check_rsc:
function check_rsc($array,$ud) {
foreach ($array as $name => $val) {
if ($ud['rsc'][$name] < $val) {
return false;
}
}
return true;
}
Example of an input:
<form method='post'><input type='submit' name='attack' value='train' />
Thank you!
Always but always Use addslashes($userInput),
The addslashes function will keep you safe from the sql injection and preventing you from users to cheat on the game.
Never let the variable go directly on the database
That is your error

GET Multiple MySQL Rows, Form PHP Variables, and Put Into Json Encoded Array

I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}

Categories