what I want is to to display this error message in the form of some alert, or some good display.. any idea?
if (mysql_error()) < echo " "; >
EVen you can write the script without echoing it(Not sure but works maximum) and try to avoid using mysql_* functions due to they are depricated.Instead use mysqli_* functions or PDO statements
You can simply add a few HTML and/or JS in your die :
if (mysql_error()) die(' ' );
Technically, that query should never return an error unless either:
In both cases, the error message you want to show doesn’t apply; you will want to test the number of affected rows instead.
That said, it’s not really possible to create an alert using server-side code; but you could create an AJAX endpoint instead:
if (errors) < $response = array('error' =>'Error message here'); > else < // update this if you want to pass data back to caller $response = array(); >header('Content-Type: application/json'); echo json_encode($response); exit;
On the client side you would submit the form using AJAX like so:
$.ajax(< url: '/path/to/endpoint', data: < whatever >, success: function(response) < if (response.error) < alert(response.error); return; >// yay, it worked > >);
Alternatively, and perhaps to serve older browsers, you could just generate a (stylized) HTML response. I personally dislike a page refresh followed by an alert() dialogue window.
Sorry, but your code is plain wrong (you’re doing mysql_query twice). I guess you meant
$sql="UPDATE customers SET password='$id' WHERE c_number='$users1' "; $result = mysql_query($sql); if (mysql_error()) die('Error, You have not used our services before, so no details for you to visit and explore');
To quote the PHP manual: *This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information*
But anyway, let’s make this work (and more secure):
$sql="UPDATE customers SET password='".myqsl_escape_string($id)."' WHERE c_number='".mysql_escape_string($users1)."' ";
This prevents SQL injection, by escaping every possible special char in both $id and $users1 (i suspect at least one of these is user submitted data).
$result = mysql_query($sql); if ($result===false) die('Error, You have not used our services before, so no details for you to visit and explore');
The key here is to use the result of mysql_query, which is FALSE if the query failed. It is good practice to use the ‘===’ comparator here, since we don’t want to look for 0 or an empty string, but only the boolean false. For more information, see the PHP mysql_query manual page
How to Display PHP Errors, To use it, you need to act like this: display_errors = on. So, you need to turn on the display_errors directive inside the PHP.ini file. It can display all the errors, particularly, parse and syntax errors that can’t be shown by calling only the ini_set function. That file can be detected in the displayed output of the phpinfo () …
How to display validation error next to the field?
I am trying to create a simple form for a wordpress site. I’ve created a full form and it’s working fine. The code is below.
//Make sure that the email address is valid. if(!filter_var($senderEmail, FILTER_VALIDATE_EMAIL)) < //$email is not a valid email. Add error to $errors array. $errors[] = "That is not a valid email address!"; >if(!empty($errors))< echo '
This code snippet sends the user input as a HTML table to the email. Validation also works fine but the validation errors appear at top of the form.
I want to show the validation errors next to the each field. How can do that using PHP only?
You could add the field name as the key of the $errors array and then do a check after each field. Something like this:
//Check the name and make sure that it isn't a blank/empty string. if(strlen(trim($sender)) === 0) < //Blank string, add error to $errors array. $errors['sendername'] = "You must enter your name!"; >. ?>
You can do it this way also.
PHP Error Handling, We simply create a special function that can be called when an error occurs in PHP. This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context): Syntax error_function (error_level,error_message,
Where is the errors console?
I’m new to PHP, started with Code Igniter and MAMP. I start the server from the MAMP application, and write PHP in the text editor.
When errors occur in the code, the page doesn’t display anything! Is there anyway to see the errors on console? or PHP just doesn’t show errors?
I’m used to Eclipses console when developing Java, is there anything similar?
Error Reporting
In your code add :
error_reporting(E_ALL); // I don't know if you need to wrap the 1 inside of double quotes. ini_set("display_startup_errors",1); ini_set("display_errors",1);
or you can do it from your php.ini file.
I’m used to Eclipses console when developing Java, is there anything similar?
Yes, there is Zend Studio — Eclipse, and also PHP IDE by Eclipse.
The errors should be displayed, looks like a supression issue which the others have covered. Something to look into is the application/config/config.php file that contains run-time configuration for the CodeIgniter framework:
166 | 0 = Disables logging, Error logging TURNED OFF 167 | 1 = Error Messages (including PHP errors) 168 | 2 = Debug Messages 169 | 3 = Informational Messages 170 | 4 = All Messages 171 | 172 | For a live site you'll usually only enable Errors (1) to be logged otherwise 173 | your log files will fill up very fast. 174 | 175 */ 176 $config['log_threshold'] = 4;
This throws all errors, even if they aren’t displayed into the Codeigniter logs folder (refer to your documentation for the location of this in your installed version.)
There are many fancy ways, similar to your eclipse console, but only 2 that works everythere.
First of all you have to decide, where you want to see your errors — online or in the log file. Usually we set online for developers machine and log for the public server. Unix-way for log is often used — tail -f /path/error_log
To set bullet-proof settings use either php config or apache config. So, to display errors online, set display_errors = on in the php.ini file (be sure you edit working one) or set php_value display_errors = 1 in the httpd.conf / .htaccess
For the public server on the shared hosting I usually add these lines into .htaccess :
php_value display_errors = 0 php_value log_errors = 1 php_value error_log = "/path/to/log.file" #if I want to have it separate from webserver's error log
Reporting level always remain the same and set in the config php file with
How to create an error 404 page using PHP?, In the Drupal or WordPress CMS (and likely others), if you are trying to make some custom php code appear not to exist (unless some condition is met), the following works well by making the CMS’s 404 handler take over: else < include ('index.php'); >?> Share Improve this answer edited May 12, …?php>
PHP предлагает гибкие настройки вывода ошибок, среди которых функия error_reporting($level) – задает, какие ошибки PHP попадут в отчет, могут быть значения:
Файлы логов также не должны быть доступны из браузера, храните их в закрытой директории с файлом .htaccess:
Order Allow,Deny Deny from all
Или запретить доступ к файлам по расширению .log (заодно и другие системные файлы и исходники):
Order Allow,Deny Deny from all
Отправка ошибок на e-mail
Ошибки можно отправлять на е-mail разработчика, но приведенные методы не работает при критических ошибках.
Первый – register_shutdown_function() регистрирует функцию, которая выполнится при завершении работы скрипта, error_get_last() получает последнюю ошибку.
register_shutdown_function('error_alert'); function error_alert() < $error = error_get_last(); if (!empty($error)) < mail('mail@example.com', 'Ошибка на сайте example.com', print_r($error, true)); >>
Стоит учесть что оператор управления ошибками (знак @) работать в данном случаи не будет и письмо будет отправляться при каждой ошибке.
Второй метод использует «пользовательский обработчик ошибок», поэтому в браузер ошибки выводится не будут.
PHP позволяет разработчику самому объявлять ошибки, которые выведутся в браузере или в логе. Для создания ошибки используется функция trigger_error() :
Alert boxes are used for displaying a warning message to the user. As you know that PHP does not have the feature to popup an alert message box, but you can use the javascript code within the PHP code to display an alert message box. In this way, you can display an alert message box of Javascript in PHP.
JavaScript has three types of pop-up boxes, which are the following:
In this article, you will learn about the alert box, confirmation box, and prompt box with examples.
1. Display alert box in PHP
An alert box is nothing but a pop-up window box on your screen with some message or information which requires user attention.
An alert box is a JavaScript dialog box that is supported by browsers.
PHP is a server-side language and does not support pop-up alert messages. The browser of the client renders an alert.
To pop an alert message via PHP, we need to render JavaScript code in PHP and send it to the browser. JavaScript is a client-side language.
alert(«Type your message here»);
Example: Using the JavaScript alert box
'; echo ' alert("JavaScript Alert Box by PHP")'; //not showing an alert box. echo ''; ?>
Example: Using the PHP function
alert('$msg');"; > ?>
2. Display confirm box in PHP
A confirm box mostly used to take user’s approval to verify or accept a value.
confirm(«Type your message here»);
Example: Using the Javascript confirmation pop-up box
'; echo ' function openulr(newurl) '; echo '>'; echo ''; > ?> Open new URL
Open new URL
3. Display prompt box in PHP
A prompt box is mostly used, when you want the user input, the user needs to fill data into the given field displaying in the pop-up box and has to click either ok or cancel to proceed further.
prompt(«Type your message here»);
Example: Using the Javascript prompt pop-up box
'; echo 'var inputname = prompt("Please enter your name", "");'; echo 'alert(inputname);'; echo ''; > ?>