PHP Undefined index error. How to fix? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”
I am getting this notice:
PHP Notice: Undefined index: votefor in /home/.../savevote.php on line 2
How can I fix this?
Here is my line 2 in savevote.php:
<?php
$votefor = $_REQUEST["votefor"];
Thank you
Here is the code:
<?php
$votefor = $_REQUEST["votefor"];
// Returns a random RGB color (used to color the vote bars)
function getRandomColor()
{
$r = rand(128,255);
$g = rand(128,255);
$b = rand(128,255);
$color = dechex($r) . dechex($g) . dechex($b);
echo "$color";
}
//Get the IP of the user
$domain = $_SERVER["REMOTE_ADDR"];
$today = date("m/d/Y");
echo "<table id=\"tblResults\" align=\"center\">";
//If votefor is null, then we're just viewing results, so don't log the IP
if ($votefor != "")
{
//Load the addresses XML file
$doc = new DOMDocument();
$doc->load("../vote_dir/xml/addresses.xml");
$addresses = $doc->getElementsByTagName("address");
$pVoted = false;
$pFound = false;
//Loop through the addresses nodes and see if the person has voted before
foreach( $addresses as $address )
{
$lastvisits = $address->getElementsByTagName("lastvisit");
$lastvisit = $lastvisits->item(0)->nodeValue;
$ips = $address->getElementsByTagName("ip");
$ip = $ips->item(0)->nodeValue;
if ($ip == $domain)
{
$pFound = true;
if ($lastvisit == $today)
$pVoted = true;
else
{
$lastvisits->item(0)->nodeValue = $today;
$doc->save("../vote_dir/xml/addresses.xml");
}
break;
}
else
continue;
}
if ($pVoted == true) //Already voted
{
echo "<tr><td colspan=\"3\" class=\"message\">Έχετε ήδη ψηφίσει!</td></tr>";
}
else //Update the XML files
{
if ($pFound == false) //Add new node for IP and date to addresses.xml
{
echo "<tr><td colspan=\"3\" class=\"message\">Ευχαριστούμε που ψηφίσατε!</td></tr>";
$newAddy = $doc->getElementsByTagName('addresses')->item(0);
$newAddressElement = $doc->createElement('address');
$newLastVisitElement = $doc->createElement('lastvisit');
$newAddressElement->appendChild($newLastVisitElement);
$newIPElement = $doc->createElement('ip');
$newAddressElement->appendChild($newIPElement);
$dayvalue = $doc->createTextNode($today);
$dayvalue = $newLastVisitElement->appendChild($dayvalue);
$ipvalue = $doc->createTextNode($domain);
$ipvalue = $newIPElement->appendChild($ipvalue);
$newAddy->appendChild($newAddressElement);
$doc->save("../vote_dir/xml/addresses.xml");
}
else
{
echo "<tr><td colspan=\"3\" class=\"message\">Ευχαριστούμε για την ψήφο σας.</td></tr>";
}
// Update the vote
$doc = new DOMDocument();
$doc->load("../vote_dir/xml/results.xml");
$pollitems = $doc->getElementsByTagName("pollitem");
foreach( $pollitems as $pollitem )
{
$entries = $pollitem->getElementsByTagName("entryname");
$entry = $entries->item(0)->nodeValue;
if ($entry == $votefor)
{
$votes = $pollitem->getElementsByTagName("votes");
$count = $votes->item(0)->nodeValue;
$votes->item(0)->nodeValue = $count + 1;
break;
}
}
$doc->save("../vote_dir/xml/results.xml");
}
}
else
{
echo "<tr><td colspan=\"3\" class=\"message\">Αποτελέσματα Ψηφοφορίας Μέχρι Στιγμής</td></tr>";
}
// Get max vote count
$doc = new DOMDocument();
$doc->load("../vote_dir/xml/results.xml");
$maxvotes = 0;
$pollitems = $doc->getElementsByTagName("pollitem");
foreach( $pollitems as $pollitem )
{
$votes = $pollitem->getElementsByTagName("votes");
$vote = $votes->item(0)->nodeValue;
$maxvotes = $maxvotes + $vote;
}
// Generate the results table
$doc = new DOMDocument();
$doc->load("../vote_dir/xml/results.xml");
$pollitems = $doc->getElementsByTagName("pollitem");
foreach( $pollitems as $pollitem )
{
$entries = $pollitem->getElementsByTagName("entryname");
$entry = $entries->item(0)->nodeValue;
$votes = $pollitem->getElementsByTagName("votes");
$vote = $votes->item(0)->nodeValue;
$tempWidth = $vote / $maxvotes;
$tempWidth = 300 * $tempWidth;
$votepct = round(($vote / $maxvotes) * 100);
echo "<tr><td width=\"20%\" class=\"polls\">$entry</td>";
echo "<td width=\"30%\" class=\"resultbar\"><div class=\"bar\" style=\"background-color: ";
getRandomColor();
echo "; width: $tempWidth px;\">$votepct%</div></td><td width=\"20%\">($vote votes)</td></tr>";
}
echo "<tr><td class=\"total\" colspan=\"3\">$maxvotes άτομα ψήφισαν μέχρι τώρα.</td>";
echo "</table>";
?>
#Brian
<script language="javascript">
function setVote(voteName)
{
document.getElementById("votefor").value = voteName;
}
function confirmSubmit()
{
if (document.getElementById("votefor").value == "")
{
var agree=confirm("Παρακαλώ επιλέξτε μια απάντηση, για να ψηφίσετε");
return false;
}
}
</script>

The request parameter isn't being passed. If you know why it might be missing and just want to prevent the notice, you can say:
$votefor = isset( $_REQUEST["votefor"] ) ? $_REQUEST["votefor"] : null;

It is not safe to use $_REQUEST because it can be $_GET or $_POST, better is specify which you want.
At second you need to check if the array key exists. This can officially be done with array_key_exists(). But unfortunately this function is a little bit slow. You can replace it by using the isset() function, but this says a null value is not set and returns false when it is null. The best approach is to use them both, first the isset and then the array_key_exists:
<?php
if (isset($_POST['votefor']) || array_key_exists($_POST['votefor'])) {
// do something
}
?>
Or use only isset if you are sure the value won't be null.
If you are almost 100% sure the index votefor exists in the array you need to debug it. var_dump the $_REQUEST array to see which items (and indexes) are in there and look what you did wrong.

1/ Check you have a request parameter named votefor
2/ Check you didn't misspelt it

Handle it like so:
if(array_key_exists("votefor", $_REQUEST)) {
...
}

You may ignore notice reports by setting error_reporting no to show them
error_reporting(E_ALL & ~E_NOTICE);

Related

Laravel conditional statement with each() result error

Partly confused (still) because the variable $investment_type resulting of "Creating default object from empty value" when I follow this previous question of mine Laravel list() with each() function error with deprecated function.
This is the original code.
$assetsData = ClientPropertyManagement::find($assets_id);
$investmentType = Input::get('investmenttype'.$assets_id);
$legalname = Input::get('legalname'.$assets_id);
$ownership = Input::get('ownership'.$assets_id);
$tic = Input::get('tic'.$assets_id);
$entity_id = Input::get('entity_id'.$assets_id);
foreach($investmentType as $investment_type) {
list($key,$value) = each($legalname);
list($key,$valueOwner) = each($ownership);
list($key,$valueTic) = each($tic);
list($key,$valueEntityId) = each($entity_id);
if($valueEntityId == 0) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($valueEntityId);
}
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $value;
$assetEntity->ownership = $valueOwner;
$assetEntity->ticnum = $valueTic;
$assetEntity->save();
}
Here's what I did in my code.
foreach( $investmentType as $key => $investment_type ) {
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $legalname[$key];
$assetEntity->ownership = $ownership[$key];
$assetEntity->ticnum = $tic[$key];
if ( $entity_id[$key] == 0 ) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($investment_type);
}
$assetEntity->save();
}
The problem is that $assetEntity isn't created yet, and you are trying to use as an object. To solve that, you need to change the position where you instantiate the object and create the variable $assetEntity:
foreach( $investmentType as $key => $investment_type ) {
if ( $entity_id[$key] == 0 ) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($investment_type);
}
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $legalname[$key];
$assetEntity->ownership = $ownership[$key];
$assetEntity->ticnum = $tic[$key];
$assetEntity->save();
}
That way $assetEntity will be created, and then you populate the other attributes.
Also, you may want to use the IoC Container and replace the new ClientEntityManagement with App::make('ClientEntityManagement'). Read more at https://laravel.com/docs/4.2/ioc

escaping numbers in array index in php

I was not having any luck with searching so if this is a duplicate please let me know rather than downvoting.
I have a script for a game server that fills a database with the character data (name, level, userid and character type).
Rather than deleting the whole sql table each time and recreating it, I have it perform a check on the character data in the table and compare and only update whats different. it all works nicely.
However, A certain few character names are causing issues.
[09-Sep-2017 02:16:34 America/New_York] PHP Notice: Undefined index: 1OO4 in C:\Scripts\charlist.php on line 56
[09-Sep-2017 02:16:34 America/New_York] PHP Notice: Undefined index: 1zxx in C:\Scripts\charlist.php on line 56
That is this part of the script:
if ($current[$charName] !== $level) {
Where $current is an array of all the characters already in the database, I have it populate the array as Name => Level
The characters are in the database but they are not updating due to the error its throwing (as seen above) I tried wrapping $charName in "" but it did not work.
If anyone can provide advice it would be greatly appreciated.
entire script for reference, can see where i've fixed it in here.
<?php
$ClanServer = "";
$SodServer = '';
$UID = "";
$PWD = "";
$file = 'C:\account.txt';
$errlog = ini_get('php_errors');
$ConnInfo = array("UID"=>"$UID", "PWD"=>"$PWD", "CharacterSet" => "UTF-8");
$ClanConn = sqlsrv_connect($ClanServer, $ConnInfo);
$SodConn = sqlsrv_connect($SodServer, $ConnInfo);
if (!$SodConn) {
die('Connection Failed!');
} else {
echo "Connection Successful!<br />".PHP_EOL;
$query = "SELECT * FROM soddb.dbo.levellist";
$result = sqlsrv_query($SodConn, $query, array(), array('Scrollable' => 'buffered'));
$current = array();
$files = array();
while ($row = sqlsrv_fetch_array($result)) {
$name = $row['CharName'];
$current["'".$name."'"] = $row['CharLevel'];
}
$rootDir = realpath('C:/PT-Server/DataServer/userdata/');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootDir), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
if (substr($name, -4) == '.dat') {
$fOpen = fopen($name, "r");
$fRead = fread($fOpen,filesize($name));
/* details */
$charLevel = substr($fRead,0xc8,1);
$charClass = substr($fRead,0xc4,1);
$charName = trim(substr($fRead,0x10,16),"\x00");
$charID = trim(substr($fRead,0x2d0,16),"\x00");
$level = ord($charLevel);
#fclose($fOpen);
$files[] = $charName;
if ($charName == "")
{
unlink($name); // Delete char file with no name...
}
switch (ord($charClass)){
case 1: $class = 'Fighter'; break;
case 2: $class = 'Mechanician'; break;
case 3: $class = 'Archer'; break;
case 4: $class = 'Pikeman'; break;
case 5: $class = 'Atalanta'; break;
case 6: $class = 'Knight'; break;
case 7: $class = 'Magician'; break;
case 8: $class = 'Priestess'; break;
case 9: $class = 'Assassin'; break;
case 10: $class = 'Shaman'; break;
}
if (in_array("'".$charName."'",array_keys($current))) {
if ($current["'".$charName."'"] !== $level) {
$dbentry = "UPDATE soddb.dbo.levellist SET CharLevel='$level',CharClass='$class' WHERE CharName='$charName'";
$clanupdate = "UPDATE clandb.dbo.ul SET ChLv='$level' WHERE ChName='$charName'";
$enter = sqlsrv_query($SodConn, $dbentry);
sqlsrv_query($ClanConn, $clanupdate);
if ($enter) {
echo "Update $charName, $level successful!<br />".PHP_EOL;
}
}
} else {
$dbentry = "INSERT INTO soddb.dbo.Levellist ([ID], [CharName], [CharClass], [CharLevel]) VALUES ('$charID', '$charName', '$class', '$level') ";
$clanupdate = "UPDATE clandb.dbo.ul SET ChLv='$level' WHERE ChName='$charName'";
$enter = sqlsrv_query($SodConn, $dbentry);
sqlsrv_query($ClanConn, $clanupdate);
if ($enter) {
echo "Insert $charName, $level successful!<br />".PHP_EOL;
}
}
}
}
/* Remove deleted characters */
foreach ($current as $k => $v) {
if (!in_array($k, $files)) {
$query = "DELETE FROM soddb.dbo.levellist WHERE CharName='$k'";
sqlsrv_query($SodConn, $query);
}
}
sqlsrv_close($ClanConn);
sqlsrv_close($SodConn);
}
?>
I've worked it out,
where I push the names to the array ($current[$name] = $level;)
I encapsulated that with '' which treats its as a string number a number (where the name was starting with a number)
so its now $current["'".$name."'"] = $level; and i did the same further down
if (in_array("'".$charName."'",array_keys($current))) {
if ($current["'".$charName."'"] !== $level) {
do stuff
}
}
I've now run the script about 15 times to test and its not giving the issue at all.

sqlite3 replacement for sqlite_has_more

First of thank you for your help.
The code piece "while (sqlite_has_more($dres))" is using sqlite2 and I need sqlite3. If there isn't a replacement for has_more is there another code I can use to still Find whether or not more rows are available?
F.Y.I. The server updated their stuff which included their sqlite and now I have to fix this last peice of code to get the schedule to populate and not give me this error.
Fatal error: Non-static method SQLite3::open() cannot be called statically in /home/server/public_html/current-list.php on line 57
$row_num = 0;
if ($dbh = SQLite3::open($sked_path))
{
$qsql = "SELECT rowid,* FROM sked ORDER BY sk_dow_num, sk_time_start, sk_time_end";
$dres = SQLite3::query($dbh, $qsql);
if (SQLite3::num_Rows($dres) > 0)
{
$last_dow = "";
$last_start = "0000";
$last_end = "0000";
while (sqlite_has_more($dres))
{
$ska = Sqlite3Result::fetchArray($dres, SQLITE3_ASSOC);
$rid = $ska['rowid'];
$dow = $ska['sk_dow_name'];
$start = $ska['sk_time_start'];
$end = $ska['sk_time_end'];
$title = preg_replace("/<br\s*\/*>/", " ", $ska['sk_show_title']);
$show_dow = strtoupper($dow);
$show_start = strtoupper(formatTimeAmPm($start));
$show_end = strtoupper(formatTimeAmPm($end));
$show_style = "";
if (stristr($title, "Encore Show"))
$show_style = " class=\"$text_style\"";
Something like ...
<?php
$dbh = new SQLite3;
if ( !$dbh->open($sked_path) ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$dres = $dbh->query('
SELECT
rowid,*
FROM
sked
ORDER BY
sk_dow_num, sk_time_start, sk_time_end
');
if ( !$dres ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$ska = $dres->fetchArray(SQLITE3_ASSOC);
if ( !$ska ) {
onNoRecords();
}
else {
do {
doSomethingWithRowData($ska);
}
while( false!=($ska=$dres->fetchArray(SQLITE3_ASSOC)) );
}
}
}
(completely untested)

Use function to change PHP variable name

kindly need your help,
I'm trying to use function to change the name of a PHP variable. I tried to change $name to $graph1, $graph2 ... $graph31. Here's the code I made:
<?php
function bar($name, $label, $value) {
return
$name = new BAR_GRAPH("pBar");
$name->values = $value;
$name->labels = $label;
$name->labelColor = "white";
$name->labelBGColor = "#282828";
$name->barBorder = "0px";
$name->barColors = "white";
$name->barBGColor = "#282828";
$name->showValues = 0;
$name->percValuesColor = "white";
$name->barColors = "white";
echo $name->create();
}
bar("$graph1","ornamen","$totkakiOrnamen;7");
?>
Unfortunately the code doesn't work, it says:
Notice: Undefined variable: graph in C:\xampp\htdocs\app\process.php
on line 56
I don't know what's wrong. How can I change $name to $graph1, $graph2 ... $graph31 ?
PS: The return code looks weird because I used gerd-tentler's script to generate horizontal bar. http://www.gerd-tentler.de/tools/phpgraphs/?page=introduction
This may or may not be what you are asking but maybe....??
<?php
function bar($name, $label, $value) {
$$name = new BAR_GRAPH("pBar");
$$name->values = $value;
$$name->labels = $label;
$$name->labelColor = "white";
$$name->labelBGColor = "#282828";
$$name->barBorder = "0px";
$$name->barColors = "white";
$$name->barBGColor = "#282828";
$$name->showValues = 0;
$$name->percValuesColor = "white";
$$name->barColors = "white";
$$name->create();
return $$name;
}
$graph1 = bar('graph1',"ornamen","$totkakiOrnamen;7"); ?>
if not, the only other guess is that you are trying to do a variable variable:
http://php.net/manual/en/language.variables.variable.php

PHP $_POST Validation

Is there a quick and easy way to check if any of my $_POST data has the same value?
I need it as a conditional statement...
Example:
$week1 = $_POST['Week_1'];
$week2 = $_POST['Week_2'];
$week3 = $_POST['Week_3'];
$week4 = $_POST['Week_4'];
$week5 = $_POST['Week_5'];
$week6 = $_POST['Week_6'];
$week7 = $_POST['Week_7'];
$week8 = $_POST['Week_8'];
$week9 = $_POST['Week_9'];
$week10 = $_POST['Week_10'];
$week11 = $_POST['Week_11'];
$week12 = $_POST['Week_12'];
$week13 = $_POST['Week_13'];
$week14 = $_POST['Week_14'];
$week15 = $_POST['Week_15'];
$week16 = $_POST['Week_16'];
$week17 = $_POST['Week_17'];
If the values of any of the weeks = equal the value of any of the other weeks, error...
Is there a quick way to do this in PHP?
Thanks!
Chris
first though to pop in to my head:
$r=array_unique(array($week1, ...));
if (count($r) !=17){
//error
}
If the only $_POST values you have are 'Week_1' through 'Week_17' then
if (count(array_unique($_POST)) === count($_POST)) {
//all unique values, do stuff...
}
Just loop through the pairs and compare them:
$weeks=array();
foreach(range(1,17) as $i)
{
array_push($weeks,'Week_' . $i);
}
foreach(range(1,16) as $i)
{
foreach(range($i+1,17) as $j)
{
if($_POST[$weeks[$i]]==$_POST[$weeks[$j]])
{
die("Rut-roh!");
{
}
}
}

Categories