PHP NOTICE:Undefined offset 1 - php

I am facing a problem that undefined offset :1. I can't understand that what type of error it is. Can anyone tell me that why such error occurs in php
<?php
$host="localhost";
$dbusername="root";
$dbpassword="";
$dbname="school";
$conn=mysql_connect($host,$dbusername,$dbpassword) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
if(isset($_POST['submit']))
{
$cls=$_POST['hhcls'];
{
{
{
$query=mysql_query("select * from stu_class where class='$cls'",$conn);
while($data=mysql_fetch_row($query))
{
$r1=$data[0];
$r=$_POST[$r1]; //THIS LNE ERROR
echo $r;
$query1="update stu_class set rollno=".$r." where ad_no=".$r;
$sql_query1=mysql_query($query1) or die(mysql_error());
if($sql_query1)
{
echo "<script type='text/javascript'>alert('Students Details Updated Successfully');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Updation Failed');</script>";
}
}
}
}
}
}
?>
I am getting error while passing data to another query

Of course )
Look:
$query = mysql_query("select * from stu_class where class='$cls'", $conn);
// Now we got not query, but result of this query in $query
while ($data = mysql_fetch_row($query)) {
// Every iteration we will have in $data array (not associated)
// of fields (next row from database)
$r1 = $data[0];
// After this line we have value of first column of current line in $r1
// usually this is integer ID field and if first ID in database is 1,
// then $r1 = 1
$r = $_POST[$r1]; //THIS LNE ERROR
// here you trying to set $r = $_POST[1] because $r1 = 1
// but you have no any POST variable with key 1.
When you trying to get some array member that doesn't exist, you will get notice "Undefined offset %key%". In strict mode you will get exception.

Related

Notice: Undefined index: SESS_NAME in student_vote.php on line 9

<?php
include "connection.php";
if(!isset($_SESSION))
{
session_start();
}
$cand1 = $_POST['cand1'];
$cand2 = $_POST['vice1'];
$sess = $_SESSION['SESS_NAME'];
if(!$cand1){
$error="<center><h4><font color='#FF0000'>Please fill empty fields</h4></center></font>";
include"student.php";
exit();
}
$cand1 = addslashes($cand1);
$cand1 = mysqli_real_escape_string($con,$cand1);
$sql = 'SELECT * FROM student WHERE username="'.$_SESSION['SESS_NAME'].'" AND status="VOTED"';
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result)==1){
$msg="<center><h4><font color='#FF0000'>You have already been voted, No need to vote again</h4></center></font>";
include 'student.php';
exit();
}
else{
$sql = 'UPDATE candidate SET votecount = votecount + 1 WHERE cand_id = "'.$_POST['cand1'].'" OR cand_id = "'.$_POST['vice1'].'"';
$sql2 = 'UPDATE student SET status="VOTED" WHERE username="'.$_SESSION['SESS_NAME'].'"';
$result = mysqli_query($con,$sql);
$result2 = mysqli_query($con,$sql2);
if(!$result && !$result2){
die("Error on mysql query".mysqli_error());
}
else{
$msg="<center><h4><font color='#FF0000'>Congratulation, you have made your vote.</h4></center></font>";
include 'student.php';
exit();
}
}
?>
the errors are at code including
$sess= $_SESSION['SESS_NAME']; and at username="'.$_SESSION['SESS_NAME'].'"
i have tried every possibility so can you check my code?
mainly the error is undefined index at $session[session_name]?
Are you sure the session 'SESS_NAME' is getting set? In the code above you are only trying to access its value. Undefined index is the error thrown when there is no session with that name.
Looks like to me you haven't declared the variable $_SESSION['SESS_NAME']. Try doing the following
var_dump($_SESSION);
This will show you all the defined variables in the session, if SESS_NAME isn't there then it hasn't been defined. Maybe you have failed to define it somewhere else?

PHP MySQL - Function

i wrote a PHP Function but it does nothing at a specific point.. im new to php and my english is bad, sorry for that.
<?php
function SQLwriteRecent($id, $title, $link) {
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$count = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
if(!isset($count)) {
try {
mysqli_query($con,"INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id',$count)");
mysqli_close($con);
return 1;
} catch(Exception $e) {
return 0;
}
} else {
try {
// ------ SHOW HERE!!!! ------------ //
mysqli_query($con,"UPDATE recent SET count=$count WHERE sc_stream='$id'");
mysqli_close($con);
return 2;
} catch(Exception $e) {
return 0;
}
}
}
?>
the code runs every time until a specific point (i marked it in the code with // ------ SHOW HERE!!!! ------------ //)
in the sql table, currently there is no entry. so i should create a new row
whats wrong with that code?! :(
Your script wont insert a new row, because you have defined $count, it is a mysqli_result object. You have to check if there is a row, something you could do like this;
Instead of
if(!isset($count))
use
if(mysqli_num_rows($count) == 0)
Some explanation:
You have this in your code:
if(!isset($count)) {
This checks that your variable has been set, nor is empty, false, or 0. This condition ALWAYS return true because the variable is setted in line before, use mysqli_nuw_rows instead
Combining what other people have said, and looking at the logic of what you're doing, it looks like you have a few fundamental issues:
I've tweaked some variable names to make it clearer what you're getting an peppered the code with comments that describe the issues.
I've ignored the SQL injection issues.
<?php
function SQLwriteRecent($id, $title, $link) {
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$countQuery = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
$numberOfRowsReturnedByQuery = mysqli_num_rows($count);
if ( $numberOfRowsReturnedByQuery > 0 ) {
$valueOfCountInQuery = $countQuery [0]['count'];
}
if( $numberOfRowsReturnedByQuery == 0) {
try {
// In this situation it looks like you want to set up a value in "recent" - I.E. you didn't have a record.
// But think about it for a second - if you had no record in "recent" then how could "$valueOfCountInQuery" possibly be set?
mysqli_query($con,"INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id',$valueOfCountInQuery )"); // makes no sense to use "$valueOfCountInQuery" - maybe you mean "0" (zero)
mysqli_close($con);
return 1;
} catch(Exception $e) {
return 0;
}
} else {
try {
// In this situation it looks like you want to update the value in "recent" - I.E. you DID have a record and you want to change it.
// But think about it for a second - the value of "$valueOfCountInQuery" is the value that you got from "count" on "recent". You are setting it to the same value that's already in there!
// ------ SHOW HERE!!!! ------------ //
mysqli_query($con,"UPDATE recent SET count=$valueOfCountInQuery WHERE sc_stream='$id'"); // redundant
mysqli_close($con);
return 2;
} catch(Exception $e) {
return 0;
}
}
}
?>
You did a mistake here, query returns array
try this
mysqli_query($con,"UPDATE recent SET count=$count[0]['count'] WHERE sc_stream='$id'");
You have set:
count=$count
but
$count = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
Specify a proper value for count not a resource
to retrieve the actual result of the query you have to do something like
if ( $result = $con->query($sql)){ //perform the query
if ($result->num_rows == 1){
if ($row = $result->fetch_assoc()){
$count = $row['count'];
}
else{
echo "couldn't fetch result row";
}
else {
echo "expected one result row, got ".$result->num_rows;
}
}
else {
echo "query failed:".$sql;
echo $con->errno.' '.$con->error;
}
// if you have more than one result row
if ( $result = $con->query($sql))
while ($row = $result->fetch_assoc()){ //loop through the result(s)
$count = $row['count']
}
// procedural style
if ( $result = mysqli_query($con,$sql))
while($row = mysqli_fetch_assoc($result)){

How to use mysql_errno() inside own error handling function?

I want to use my own error handling and my first thought was this:
// db connection
$conn = conn();
if(!$conn)
$aErrors[] = 'Fout: Geen database verbinding!';
function db_error($conn)
{
if(mysql_errno($conn) == 0)
return true;
else
{
// log! and global $aErrors[] = mysql_errno($conn)
return false;
}
}
$q = "SELECT
xusername, email
FROM
terra_user
WHERE
ID = '".$_GET['ID']."'
LIMIT 1";
$exec = mysql_query($q);
// error check
if(db_error($exec))
{
echo'teeeeeest!';
}
else
{
$aRow = mysql_fetch_assoc($exec);
$uitgever = $aRow['username'];
$uitgever_email = $aRow['email'];
echo'Xteeeeeest!';
}
But I get the next error:
Warning: mysql_errno(): supplied argument is not a valid MySQL-Link resource in xxxx
In this case, mysql_erro() returns a number > 0, so it looks OK, except that the link source is not OK?
If I use mysql_errno($conn) I get :
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in xxxxxx
In this case, mysql_erro() returns 0!
For this code I have changed one field with a wrong name. Put an extra x for username:)
$_GET['ID'] is already tested with ctype_digit($_GET['ID'])
What am I doing wrong here?
I see no point in such a function at all. You have $exec for your error "handling", that's enough.
// db connection
$conn = conn();
if(!$conn) {
$aErrors[] = 'Fout: Geen database verbinding!';
}
$q = "SELECT xusername, email FROM terra_user WHERE ID = ".(int)$_GET['ID']." LIMIT 1";
$exec = mysql_query($q) or trigger_error(mysql_error());
// error check
if(!$exec))
{
$aErrors[] = 'Fout: Geen database verbinding!';
}
else
{
$aRow = mysql_fetch_assoc($exec);
$uitgever = $aRow['username'];
$uitgever_email = $aRow['email'];
echo'Xteeeeeest!';
}
Though I see no point in collecting errors into array. if it's critical error, no need to wait for the other - only one is enough. if it's not a critical error - why disturb a user with it?

php mysql check previous row

I have output from a select query as below
id price valid
1000368 69.95 1
1000369 69.94 0
1000370 69.95 0
now in php I am trying to pass the id 1000369 in function. the funciton can execute only if the valid =1 for id 1000368. if it's not 1 then it will throw error. so if the id passed is 1000370, it will check if valid =1 for 1000369.
how can i check this? I think it is logically possible to do but I am not able to code it i tried using foreach but at the end it always checks the last record 1000370 and so it throws error.
regards
Use a boolean variable:
<?php
$lastValid=false;
while($row = mysql_fetch_array($result))
{
if ($lastValid) {
myFunction();
}
$lastValid = $row['valid'];
}
?>
(Excuse possible errors, have no access to a console at the moment.)
If I understand correctly you want to check the if the previous id is valid.
$prev['valid'] = 0;
foreach($input as $i){
if($prev['valid']){
// Execute function
}
$prev = $i;
}
<?php
$sql = "SELECT * FROM tablename";
$qry = mysql_query($sql);
while($row = mysql_fetch_array($qry))
{
if ($row['valid'] == 1)
{
// do some actions
}
}
?>
I really really recommend walking through some tutorials. This is basic stuff man.
Here is how to request a specific record:
//This is to inspect a specific record
$id = '1000369'; //**some specified value**
$sql = "SELECT * FROM data_tbl WHERE id = $id";
$data = mysql_fetch_assoc(mysql_query($sql));
$valid = $data['valid'];
if ($valid == 1)
//Do this
else
//Do that
And here is how to loop through all the records and check each.
//This is to loop through all of it.
$sql = "SELECT * FROM data_tbl";
$res = mysql_query($sql);
$previous_row = null;
while ($row = mysql_fetch_assoc($res))
{
some_action($row, $previous_row);
$previous_row = $row; //At the end of the call the current row becomes the previous one. This way you can refer to it in the next iteration through the loop
}
function some_action($data, $previous_data)
{
if (!empty($previous_data) && $condition_is_met)
{
//Use previous data
$valid = $previous_data['valid'];
}
else
{
//Use data
$valid = $data['valid'];
}
if ($valid == 1)
{
//Do the valid thing
}
else
{
//Do the not valid thing
}
//Do whatever
}
Here are some links to some good tutorials:
http://www.phpfreaks.com/tutorials
http://php.net/manual/en/tutorial.php

function and class to show image not working in php

i am trying to get get the following working nothing is happen when i use the function i am trying to get it to display images
class ItemRes {
//items DB
var $img="";
}
function ShowItemImage($index,$res_a){
if(sizeof($res_a) > $index){
if($res_a[$index] != NULL) {
$cimg = $res_a[$index]->img;
return "<img src='$cimg' width='70' height='70' style='cursor:pointer'></img>";
}
}else{
return "<center class='whitetxt'><strong>Empty</strong></center>";
}
}
$res_array = array();
$idx=0;
$result21 = mysql_query("SELECT * FROM photos WHERE eid='$eid' ORDER BY id DESC") or die (mysql_error());
while ($row21 = mysql_fetch_array($result21)) {
$img_path = $row21['path'];
$obj = new ItemRes();
$obj->img = $img_path;
$res_array[$idx] = $obj;
$idx++;
}
ShowItemImage(0,$res_array)
ShowItemImage(1,$res_array)
Thhere are many issues with this code, so I'll just take them one at the time.
Assuming you initiate the database connection somewhere else the first issue is
the line:
$result21 = mysql_query("SELECT * FROM photos WHERE eid='$eid' ORDER BY id DESC") or die (mysql_error());
Prior to this line you do not set the variable $eid and thus this will only fetch items with eid = ''
Second:
You do not end the last two rows with a semicolon, thus this will produce a fatal error.
Third:
Probably the reason to why you get 'nothing is happen' (wich I interpet as a blank page)
In your function ShowItemImage you return strings but you do nothing with them.
You need to change this:
ShowItemImage(0,$res_array)
ShowItemImage(1,$res_array)
to:
echo ShowItemImage(0,$res_array);
echo ShowItemImage(1,$res_array);
and you will probably start noticing some things on the screen.

Categories