else statement not displaying data - php

i have some code to check for duplicates in a db before submitting the data, but the statement i have does not work. if a duplicate is found a message is returned to the form. however, it is not working and i am sure it has to do with my else statements near the bottom of the file being incorrect. assume all connections are working. where is the error? many thanks
<?php
$array = split('[,]', $_POST['fileno']);
if (isset($_POST['submit'])) {
foreach ($array as $fileno) {
if ($fileno == '' && $box == '')
{
echo '<div style="background-color:#ffa; padding:2px; color:#ff0000;font-size:12px;font-weight:normal">' . 'You must incude a box and a file' . '</div>';
}
elseif ($fileno == '')
{
echo '<div style="background-color:#ffa; padding:2px; color:#ff0000;font-size:12px;font-weight:normal">' . 'You must enter a file reference' . '</div>';
}
elseif ($box == '')
{
//echo error;
echo '<div style="background-color:#ffa; padding:2px; color:#ff0000;font-size:12px;font-weight:normal">' . 'You must enter a box' . '</div>';
}
else
{
$sql = "SELECT custref FROM files WHERE custref = '$fileno' ";
$result = runSQL($sql) or die(mysql_error());
if (mysql_num_rows($result)>0){
echo '<div style="background-color:#ffa; padding:2px; color:#ff0000;font-size:12px;font-weight:normal">' . $fileno . ' is already in the database. No duplicates' . '</div>';
}
$sql = "SELECT custref FROM boxes WHERE custref = '$box' ";
$result = runSQL($sql) or die(mysql_error());
if (mysql_num_rows($result)>0){
echo '<div style="background-color:#ffa; padding:2px; color:#ff0000;font-size:12px;font-weight:normal">' . $box . ' is already in the database. No duplicates' . '</div>';
}
else
{
//insert into db;
echo '<div style="background-color:#ffa; padding:2px; color:#33CC33;font-size:12px;font-weight:normal">' . $fileno . "Box: " . $box . $authorised . 'Successfull' . '</div>';
$sql = "INSERT INTO `files` (customer, authorisation, boxstatus, boxref, custref, filestatus) VALUES ('$customer', '$authorised', '$boxstatus', '$box', '$fileno', $filestatus)";
$result = runSQL($sql) or die(mysql_error());
//echo 'This record is valid';
//header("Location: http://localhost/sample/admin/files/index.php");
//exit();
}
}
}
}
?>

Please check whether it is coming in this section:-
// Some logic
if (...) {
// some more logic
}
...
elseif ($box == '') {
//echo error;
echo '<div style="background-color:#ffa; padding:2px; color:#ff0000;font-size:12px;font-weight:normal">' . 'You must enter a box' . '</div>';
}
else {
echo 'check it here please';
// some more logic
}
...
Hope it helps.

Put some echos to check the values:
foreach ($array as $fileno) {
echo "fileno='$fileno' , box='$box'<br>";
......
then in each block of if/elseif
echo "i'm running line : ",__LINE__,"<br>";
What do you obtain ?

You should try using exit();/die(); in your echoed errors(not the best way of error handling! - try exceptions out) instead of encapsulating dependent code in an else. I suspect this may fix your issue, as you're only checking to add the row against one of your error statements.

Related

Show summary if php loop?

I have a loop that looks like this:
/* For Loop for all sheets */
for($i=0;$i<$totalSheet;$i++) {
$Reader->ChangeSheet($i);
foreach ($Reader as $Row) {
//variables here
$query = "INSERT INTO schools (
//code here
)";
if ($mysqli->query($query) === TRUE) {
echo "<br> New record created successfully <br>";
} else {
echo "Error: " . $query . "<br>" . $mysqli->error;
}
}
}
How do I turn this:
if ($mysqli->query($query) === TRUE) {
echo "<br> New record created successfully <br>";
into a code that will show something like:
XX inputted successfully
{list of schools with ID listed here}
XX not inpputed due to errors
{list of schools not inputted}
Would like to see a simple summary of the entire loop rather than seeing a repeated result of each loop that occurred.
Collect all the information you want in variables, and print them at the end.
$success = $fail = "";
$success_count = $fail_count = 0;
for($i=0;$i<$totalSheet;$i++) {
$Reader->ChangeSheet($i);
foreach ($Reader as $Row) {
//variables here
$query = "INSERT INTO schools (
//code here
)";
if ($mysqli->query($query)) {
$success .= "<li>" . $Row['school_name'] . "</li>";
$success_count++;
} else {
$fail .= "<li>" . $Row['school_name'] . "</li>";
$fail_count++;
}
}
}
echo $success_count . " inputted successfully:<br><ul>" . $success . "</ul>";
echo $fail_count . " not inputted due to errors:<br><ul>" . $fail . "</ul>";
Replace $Row['school_name'] with whatever the correct variable is for the school name in your data.

How to Check If 10 Most Recent Entries in MySQL DB Begin with a String Using PHP?

I want to allow people to write something like BOLD: or ITALIC: at the beginning of their message to make bold or italic. The only way I can think of is to get the total amount of entries by ID and minus 10 then make an IF statement and minus 9 and so on. Is there a single statement I could query to check if the string in the database begins a certain way and display it in HTML in bold or italic if it does?
<?PHP
$A = "localhost"; // Server Name
$B = "root"; // MySQL Username
$C = ""; // MySQL Password
$D = "sql"; // Database
$CONNECT = new mysqli($A, $B, $C, $D);
if ($CONNECT->connect_error) {
die('<DIV>Connection Failed</DIV>');
}
echo "<DIV>Connected</DIV>";
if (isset($_POST['MSG'])) {
$MSG = htmlspecialchars($_POST['MSG']);
$SQL = "INSERT INTO Messages (Message) VALUES ('$MSG')";
if ($CONNECT->query($SQL) === TRUE) {
echo "<DIV>Message Sent</DIV>";
} else {
echo "<DIV>Error Sending Message</DIV>";
}
}
$SELECT = 'SELECT * FROM Messages ORDER BY ID DESC LIMIT 10';
$RESULT = $CONNECT->query($SELECT);
if (mysqli_num_rows($RESULT) > 0) {
while ($ROW = mysqli_fetch_assoc($RESULT)) {
echo '<DIV>ID: ' . $ROW['ID'] . ' MSG: ' . $ROW['Message'] . '</DIV>';
}
}
I added in some code if somebody begins their message with "'", but the type of strpos if statement doesn't work in the while loop for retrieving messages.
if (isset($_POST['MSG'])) {
$MSG = htmlspecialchars($_POST['MSG']);
$SQL = "INSERT INTO Messages (Message) VALUES ('$MSG')";
if ($CONNECT->query($SQL) === TRUE) {
echo "<DIV>Message Sent</DIV>";
} else {
if (substr($MSG,0,1 == '\'')) {
echo "<DIV>Error Sending Message</DIV>";
} else {
echo "<DIV>Nice Try :')</DIV>";
}
}
In order for this question to have an answer i will sum up what i did in the comments:
if (mysqli_num_rows($RESULT) > 0) {
while ($ROW = mysqli_fetch_assoc($RESULT)) {
$message = $ROW['message'];
if(strpos($ROW['message'], 'BOLD:') !== false){
$message = '<strong>'.substr($ROW['message'], 5).'</strong>';
} else if(strpos($ROW['message'], 'ITALIC:') !== false){
$message = '<i>'.substr($ROW['message'], 7).'</i>';
}
echo '<DIV>ID: ' . $ROW['ID'] . ' MSG: ' . $message . '</DIV>';
}
}
edit: oops i forgot to add the different style tags..
for bold you can wrap the $message in a strong -tag. for italic its the i -tag
edit2: included tags in the code

Getting table doesnt exist with php and mysql

This code down here should search database. but I am getting error that my table doesnt exists. And also I want to ask why if I push second time submit button it just jumps to else so it echo choose at least.... and also all data from database. Thanks!
Here is php
if (isset($_POST['submit'])) {
$query = 'SELECT * FROM station_tab';
if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone']))
{
$query .= 'WHERE station_name' .mysql_real_escape_string($_POST['station_name']) . 'AND city' . mysql_real_escape_string($_POST['city']) . 'AND zone' . mysql_real_escape_string($_POST['zone']);
} elseif (!empty($_POST['station_name'])) {
$query .= 'WHERE station_name' . mysql_real_escape_string($_POST['station_name']);
} elseif (!empty($_POST['city'])) {
$query .= 'WHERE city' . mysql_real_escape_string($_POST['city']);
} elseif (!empty($_POST['zone'])) {
$query .= 'WHERE zone' . mysql_real_escape_string($_POST['zone']);
} else {
echo "Choose at least one option for search";
}
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)){
echo '<br/><em>' .$row['station_name'] . '</em>';
echo '<br/>city: '. $row['city'];
echo '<br/> zone: ' .$row['zone'];
echo '<br/> Long: ' .$row['lon'];
echo '<br/> Lat: ' . $row['lat'];
}
}
}
here is error message when I add name of the city to city.
Table 'stanice_tab.station_tabwhere' doesn't exist
Here is your corrected code:
$query = 'SELECT * FROM station_tab '; // note the space at the end
if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone'])) {
$query .= ' WHERE station_name = "' .mysql_real_escape_string($_POST['station_name']) . '" AND city = "' . mysql_real_escape_string($_POST['city']) . '" AND zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = signs and the space before each AND
} elseif (!empty($_POST['station_name'])) {
$query .= ' WHERE station_name = "' . mysql_real_escape_string($_POST['station_name']).'"'; // note the = sign and the space at the beginning
} elseif (!empty($_POST['city'])) {
$query .= ' WHERE city = "' . mysql_real_escape_string($_POST['city']).'"'; // note the = sign and the space at the beginning
} elseif (!empty($_POST['zone'])) {
$query .= ' WHERE zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = sign and the space at the beginning
} else {
echo "Choose at least one option for search";
}
Take the habit of echoing your $query variable so concatenation does not add any typo mistakes.
in phpmyadmin select the database and then select your table
and in menu above there is a sql menu. you can use this functionality to construct sql queries or debug when there are errors like this

php code not working after php.ini file reset

My service provider reset my php.ini file on me. My php code has not changed but now none of my functions are working?
I am running php.ini 5.2 what would I need to turn on, or off, to get the following code to work again?
Thank you in advance for your help
function characterListPost() {
global $wpdbNew;
$q = "SELECT id, ch_position, ch_name, ch_image, ch_description, ch_age, ch_like, ch_dislike FROM characters ORDER BY ch_position";
$rows = $wpdbNew->get_results($q,ARRAY_A);
// start with nonsense value to force a heading
$previous_season = 0;
$outputTwo='';
$i = 1;
foreach ($rows as $row) {
$outputTwo.= "<div class=\"characterbox\" id=\"div{$i}\">";
$i++;
$outputTwo.= "<div class=\"ch_name\">{$row["ch_name"]}</div>";
$outputTwo.= "<div><image class=\"ch_image\" id=\"ch_image{$row["id"]}\" alt=\"character image TBA\" src=\"{$row["ch_image"]}\" /></div>";
$outputTwo.= "<div class=\"ch_description\"><p>{$row["ch_description"]}</p></div>";
$outputTwo.= "<div class=\"ch_age\"><b>Age:</b> {$row["ch_age"]}</div>";
$outputTwo.= "<div class=\"ch_like\"><b>Like:</b> {$row["ch_like"]}</div>";
$outputTwo.= "<div class=\"ch_dislike\"><b>Dislike:</b> {$row["ch_dislike"]}</div>";
$outputTwo.= "<div class=\"Down10px clear\"></div>";
$outputTwo.= "</div>";
}
// echo test successful but $outputTwo will not display?
echo 'Connected successfully';
return $outputTwo;
}
?>
I tested the db code and it works so by process of elimination the problem must be between my php.ini file and the function code above
<?php
$wpdbNew = new wpdb('myacc.myhost.com', 'myusername', 'mypassword', 'mydbname');
if (!$wpdbNew) {
die('Could not connect: ' . mysql_error());
}
The following are already On inside php.ini
allow_url_fopen = On
allow_url_include = On
register_long_arrays = On
register_globals = On
Second part, based on provided answer below, getting the following code to work
EDIT got it to work by removing foreach ($rows as $row) {
All set, everything is working!
<?php
episodeListPost();
function episodeListPost() {
$host = 'mydomain.com';
$user = 'myusername';
$pass = 'mypassword';
$data = 'dbname';
$cn = mysql_connect($host, $user, $pass) or die(mysql_error());
mysql_select_db($data, $cn) or die(mysql_error());
$sql = "SELECT id, season_num, temp_eps_num, eps_num, title, inspired, descrip FROM season ORDER BY season_num, temp_eps_num";
$result = mysql_query($sql, $cn) or die(mysql_error());
if($result) {
$previous_season = 0;
$outputOne='';
$i = 1;
while($row = mysql_fetch_assoc($result)) {
foreach ($rows as $row) {
$season = $row["season_num"];
if ($season != $previous_season){
$outputOne.= "<div class=\"seasonTitle\">Season $season</div>";
$previous_season = $season;
}
$outputOne.= "<div class=\"clear\">Episode: {$row["eps_num"]}</div>";
$outputOne.= "<div class=\"epsTitle\">Title: <span class=\"epsTitleOutput\">{$row["title"]}</span></div><div class=\"epsInsp\"> {$row["inspired"]}</div>";
$outputOne.= "<div class=\"epsDiscrip\">{$row["descrip"]}</div>";
$outputOne.= "<div class=\"Down10px\"></div>";
}
if($i == 1) { }
echo $outputOne;
mysql_free_result($result);
} else {
echo 'No results';
}
mysql_close($cn);
}
?>
The the following function. Most likely, your query is not returning any results, or the function $wpdbNew->get_results() is not returning any records.
function characterListPost() {
global $wpdbNew;
$q = "SELECT id, ch_position, ch_name, ch_image, ch_description, ch_age, ch_like, ch_dislike FROM characters ORDER BY ch_position";
$rows = $wpdbNew->get_results($q,ARRAY_A);
// start with nonsense value to force a heading
$previous_season = 0;
$outputTwo='';
$i = 1;
foreach ($rows as $row) {
$outputTwo.= "<div class=\"characterbox\" id=\"div{$i}\">";
$i++;
$outputTwo.= "<div class=\"ch_name\">{$row["ch_name"]}</div>";
$outputTwo.= "<div><image class=\"ch_image\" id=\"ch_image{$row["id"]}\" alt=\"character image TBA\" src=\"{$row["ch_image"]}\" /></div>";
$outputTwo.= "<div class=\"ch_description\"><p>{$row["ch_description"]}</p></div>";
$outputTwo.= "<div class=\"ch_age\"><b>Age:</b> {$row["ch_age"]}</div>";
$outputTwo.= "<div class=\"ch_like\"><b>Like:</b> {$row["ch_like"]}</div>";
$outputTwo.= "<div class=\"ch_dislike\"><b>Dislike:</b> {$row["ch_dislike"]}</div>";
$outputTwo.= "<div class=\"Down10px clear\"></div>";
$outputTwo.= "</div>";
}
// echo test successful but $outputTwo will not display?
echo 'Connected successfully.';
if($i == 1) { echo '<br />' . 'No Rows Found'; } else { echo '<br />' . $i . ' Rows Found'; }
return $outputTwo;
}
SECOND TEST
<?php
characterListPost();
function characterListPost() {
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$data = 'test';
$cn = mysql_connect($host, $user, $pass) or die(mysql_error());
mysql_select_db($data, $cn) or die(mysql_error());
$sql = "SELECT id, ch_position, ch_name, ch_image, ch_description, ch_age, ch_like, ch_dislike FROM characters ORDER BY ch_position";
$result = mysql_query($sql, $cn) or die(mysql_error());
if($result) {
$previous_season = 0;
$outputTwo='';
$i = 1;
while($row = mysql_fetch_assoc($result)) {
$outputTwo.= "\n\n" . '<!--- ROW #' . $i . ' -->' . "\n";
$outputTwo.= '<div class="characterbox" id="div' . $i . '">' . "\n";
$i++;
$outputTwo.= '<div class="ch_name">' . $row["ch_name"] . '</div>' . "\n";
$outputTwo.= '<div><image class="ch_image" id="ch_image' . $row["id"] . '" alt="character image TBA" src="' . $row["ch_image"] . '" /></div>' . "\n";
$outputTwo.= '<div class="ch_description"><p>' . $row["ch_description"] . '</p></div>' . "\n";
$outputTwo.= '<div class="ch_age"><b>Age:</b> ' . $row["ch_age"] . '</div>' . "\n";
$outputTwo.= '<div class="ch_like"><b>Like:</b> ' .$row["ch_like"] . '</div>' . "\n";
$outputTwo.= '<div class="ch_dislike"><b>Dislike:</b> ' . $row["ch_dislike"] . '</div>' . "\n";
$outputTwo.= '<div class="Down10px clear"></div>' . "\n";
$outputTwo.= '</div>' . "\n";
}
if($i == 1) { echo '<br />' . 'No Rows Found'; } else { echo '<br />' . $i . ' Rows Found'; }
echo '<textarea>' . $outputTwo . '</textarea>';
mysql_free_result($result);
} else {
echo 'No results';
}
mysql_close($cn);
}
?>
HACK AROUND
Replacing the function with this should work. Do not forget to call 'characterListPost()' wherever this is supposed to be output.
function characterListPost() {
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$data = 'test';
$cn = mysql_connect($host, $user, $pass) or die(mysql_error());
mysql_select_db($data, $cn) or die(mysql_error());
$sql = "SELECT id, ch_position, ch_name, ch_image, ch_description, ch_age, ch_like, ch_dislike FROM characters ORDER BY ch_position";
$result = mysql_query($sql, $cn) or die(mysql_error());
$return = "";
if($result) {
$previous_season = 0;
$outputTwo='';
$i = 1;
while($row = mysql_fetch_assoc($result)) {
$outputTwo.= "<div class=\"characterbox\" id=\"div{$i}\">";
$i++;
$outputTwo.= "<div class=\"ch_name\">{$row["ch_name"]}</div>";
$outputTwo.= "<div><image class=\"ch_image\" id=\"ch_image{$row["id"]}\" alt=\"character image TBA\" src=\"{$row["ch_image"]}\" /></div>";
$outputTwo.= "<div class=\"ch_description\"><p>{$row["ch_description"]}</p></div>";
$outputTwo.= "<div class=\"ch_age\"><b>Age:</b> {$row["ch_age"]}</div>";
$outputTwo.= "<div class=\"ch_like\"><b>Like:</b> {$row["ch_like"]}</div>";
$outputTwo.= "<div class=\"ch_dislike\"><b>Dislike:</b> {$row["ch_dislike"]}</div>";
$outputTwo.= "<div class=\"Down10px clear\"></div>";
$outputTwo.= "</div>";
}
// if($i == 1) { echo '<br />' . 'No Rows Found'; } else { echo '<br />' . $i . ' Rows Found'; }
$return = $outputTwo;
mysql_free_result($result);
// } else {
// echo 'No results';
}
mysql_close($cn);
return $return;
}

PHP not inserting datetime into mysql table

I've searched and tried a couple of different ways but I always get a 0000-00-00 00:00:00
Here's my page:
<?php
require_once "../../maincore.php";
require_once THEMES."templates/header.php";
$earnedpoints = false;
$account = $_GET['account'];
$account = mysql_real_escape_string($account);
if ($account == "") {
echo 'Enter an account name!';
exit();
}
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$query = mysql_query("SELECT *, SUM(`times`) as amount FROM votingrecords WHERE account='$account' OR ip='$ip'");
$lasttime = mysql_fetch_array($query);
$amount = $lasttime['amount'];
$insertnew = false;
if ($amount == "") {
$insertnew = true;
}
$timecalc = $time - $lasttime['date'];
if (!$insertnew) {
if ($timecalc < 43200) {
require_once THEMES."templates/header.php";
add_to_title(" - Vote");
opentable("Error");
echo "<table class='tbl-border' width='100%' cellspacing='1' cellpadding='5'><td class='tbl2'>";
echo ' Hello '. $account .' you have already voted with this account ('. $account .') or IP ('. $ip .') in the last 12 hours!';
echo ' Last voted on: '. date('Y-m-d H:i:s', $lasttime['date']) .'';
echo '<html>';
echo '<head>';
echo '<meta HTTP-EQUIV="REFRESH" content="10; url=\vote.php?account=' . $_GET['account'] . '">';
echo '</head>';
echo '<body>';
echo '<br /><br /><center>You will be redirected to the main website in 10 seconds.</center>';
echo '</body>';
echo '</html>';
echo "</td></table>";
closetable();
require_once THEMES."templates/footer.php";
exit();
} else {
$update = mysql_query("UPDATE votingrecords SET account='$account', date='NOW()', times=times+1 WHERE ip='$ip'");
if (!$update) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $update;
die($message);
} else {
$earnedpoints = true;
}
}
} else {
$success = mysql_query("INSERT INTO votingrecords (`account`, `ip`, `date`, `times`) VALUES ('$account', '$ip', 'NOW()', 1)");
if (!$success) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $success;
die($message);
} else {
$earnedpoints = true;
}
}
if ($earnedpoints) {
$points = mysql_query("UPDATE user SET votingpoints = votingpoints + 1 WHERE login='$account'");
if (!$points) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close();
echo '<html>';
echo '<head>';
echo '<meta HTTP-EQUIV="REFRESH" content="0; url=vote here">';
echo '</head>';
echo '</html>';
} else {
echo 'There was an error processing your request.';
exit();
}
require_once THEMES."templates/footer.php";
?>
That solved my problem with it not inserting the date, that works fine now!! thanks alot!
I thought it would solve my issue with it not keeping track of when a user votes so they can only vote each 12 hours.It still lets people vote over and over again >.<
Is there anyway to bump this? Lmao.. Still could use some help
Don't put NOW() inside of single quotes...
I just checked the code and you have 'NOW()' in the insert take out quotes and use just now().
'NOW()' will be treated as string and while adding to mysql datetime field its invalid and thus will have 0000-00.....

Categories