monah1983 0 / 0 / 1 Регистрация: 29.08.2013 Сообщений: 70 |
||||||||
1 |
||||||||
25.06.2017, 19:24. Показов 1492. Ответов 8 Метки нет (Все метки)
Всем добрый день! Errormessage: Unknown system variable ‘a’ Fatal error: Call to a member function fetch_assoc() on null in G:\OpenServer\domains\localhost\test1\session.php on line 14 код session.php
код db.php
подскажите куда копать?
0 |
313 / 312 / 221 Регистрация: 11.07.2015 Сообщений: 1,107 |
|
25.06.2017, 20:46 |
2 |
0 |
monah1983 0 / 0 / 1 Регистрация: 29.08.2013 Сообщений: 70 |
||||
25.06.2017, 20:57 [ТС] |
3 |
|||
спасибо, но мне надо именно вот этот код
0 |
plohoyav 313 / 312 / 221 Регистрация: 11.07.2015 Сообщений: 1,107 |
||||||||
25.06.2017, 21:04 |
4 |
|||||||
если удалить
исчезнет ошибка
0 |
Особый статус 623 / 221 / 164 Регистрация: 18.11.2015 Сообщений: 1,086 |
|
25.06.2017, 21:35 |
5 |
вроде бы вы сразу закрываете соединение с БД, а потом пытаетесь выполнить запрос уже без соединения, отсюда должны исчезнуть остальные 2 ошибки
0 |
0 / 0 / 1 Регистрация: 29.08.2013 Сообщений: 70 |
|
26.06.2017, 15:37 [ТС] |
6 |
c этим разобрался, спасибо))
0 |
0 / 0 / 1 Регистрация: 29.08.2013 Сообщений: 70 |
|
27.06.2017, 09:29 [ТС] |
8 |
понятно. скрипт делает изменения, но данные в БД не заносятся. что можно сделать?
0 |
313 / 312 / 221 Регистрация: 11.07.2015 Сообщений: 1,107 |
|
27.06.2017, 18:19 |
9 |
firefox, правый клик, исследовать элемент, сеть выбрать post запрос, посмотреть ответ сервера
0 |
I am creating a cursor for the first time.(referring this site)
I made this so far(
CREATE PROCEDURE `abc`.`cursordemo` (IN start_date DATETIME,IN end_date DATETIME)
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE k1,k2,g,s,last_status VARCHAR(45);
DECLARE b, c INT;
DECLARE cur1 CURSOR FOR SELECT `key` FROM `abc`.`temp_weekly`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO k1;
IF done THEN
LEAVE read_loop;
END IF;
block_cursor:BEGIN
DECLARE cur2 CURSOR FOR SELECT `key`,`group`,`status` FROM `abc`.`jira_local` WHERE `key` = k1 AND updateddate < end_date;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done1 = TRUE;
OPEN cur2;
REPEAT
FETCH cur2 INTO k2,g,s;
IF NOT done1 THEN
IF s != last_status THEN
CASE
WHEN s = 'verified' THEN
SET c = c +1;
WHEN s = 'closed' THEN
SET c = c +1;
WHEN s = 'to be scheduled' THEN
SET c = c +1;
WHEN s = 'deferred' THEN
SET c = c +1;
/*'resolved','closed','to be scheduled','deferred','validated','assigned','l3 need more info','l2 need more info','need more info'*/
WHEN s = 'resolved' THEN
SET c = c +1;
WHEN s = 'validated' THEN
SET c = c +1;
WHEN s = 'assigned' THEN
SET c = c +1;
WHEN s = 'l3 need more info' THEN
SET c = c +1;
WHEN s = 'l2 need more info' THEN
SET c = c +1;
WHEN s = 'need more info' THEN
SET c = c +1;
END CASE;
SET last_status = s;
END IF;
END IF;
UNTIL NOT done1 END REPEAT;
INSERT INTO ticketsResolvedCount values(k2,g,s,c);
END block_cursor;
END LOOP;
CLOSE cur1;
CLOSE cur2;
END$$
What I am doing
1) read all keys from temp_weekly and iterate
2) find all the records from jira_local table for a particular key and count the number of times it was verified,resolved etc.
Problem :
When I compile this it gives an error
ERROR 1193: Unknown system variable 'done1'
Also, I referred this link to create a stored procedure inside a loop
UPDATE:
After declaring done/done1
my procedure looks like this
BEGIN
DECLARE k1,k2,g,s,last_status VARCHAR(45);
DECLARE b, c INT;
DECLARE cur1 CURSOR FOR SELECT `key` FROM `abc`.`temp_weekly`;
DECLARE done1 BOOLEAN DEFAULT FALSE;
DECLARE done BOOLEAN DEFAULT FALSE;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
.
.
.
block_cursor:BEGIN
DECLARE cur2 CURSOR FOR SELECT `key`,`group`,`status` FROM `abc`.`jira_local` WHERE `key` = k1 AND updateddate < end_date;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done1 = TRUE;
.
.
.
this gives me
ERROR 1337: Variable or condition declaration after cursor or handler declaration
I’ve this simple table:
CREATE TABLE IF NOT EXISTS `testing`
(
`testing_ID` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`meter` INT NOT NULL,
`price` DECIMAL(12,2) NOT NULL,
`price_per_meter` DECIMAL(10,2) NOT NULL,
PRIMARY KEY (`testing_ID`)
)
And I’ve written this MySQL PROCEDURE
:
DELIMITER $$
CREATE PROCEDURE `price_per_meter_calc` (price DECIMAL(12,2))
BEGIN
SET price_per_meter = price/meter;
END
$$
DELIMITER ;
but I’ve got an error #1193 - Unknown system variable 'price_per_meter'
. I believe it’s pretty straightforward code. What I want is simply MySQL to automatically calculate price_per_meter
given the user will only insert price
and meter
values.
asked Mar 21, 2015 at 14:00
0
You need to declare variable first and then only you can set the value.
Something like:
DECLARE price_per_meter DECIMAL(6,2);
Then other part is just logics.
answered Nov 3, 2018 at 2:36
The Procedure fails to mention the table containing price_per_meter
and meter
.
Do you really want to feed in price
? Do you want to store price
in the table — if so, need another set. Or do you want to use the price
that is already in the table — if so, don’t pass it in.
My recommendation is to completely erase the STORED PROCEDURE
and start over. Think about what you «have» and what you «want to achieve», and what it takes to get from one to the other.
answered Mar 21, 2015 at 17:00
Rick JamesRick James
76.1k5 gold badges45 silver badges109 bronze badges
mysqli_error
(PHP 5, PHP 7, PHP
mysqli::$error — mysqli_error — Возвращает строку с описанием последней ошибки
Описание
Объектно-ориентированный стиль
Процедурный стиль
mysqli_error(mysqli $mysql
): string
Возвращаемые значения
Строка с описанием ошибки. Пустая строка, если ошибки нет.
Примеры
Пример #1 Пример с $mysqli->error
Объектно-ориентированный стиль
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");/* Проверить соединение */
if ($mysqli->connect_errno) {
printf("Соединение не удалось: %s\n", $mysqli->connect_error);
exit();
}
if (!
$mysqli->query("SET a=1")) {
printf("Сообщение ошибки: %s\n", $mysqli->error);
}/* Закрыть соединение */
$mysqli->close();
?>
Процедурный стиль
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");/* Проверить соединение */
if (mysqli_connect_errno()) {
printf("Соединение не удалось: %s\n", mysqli_connect_error());
exit();
}
if (!
mysqli_query($link, "SET a=1")) {
printf("Сообщение ошибки: %s\n", mysqli_error($link));
}/* Закрыть соединение */
mysqli_close($link);
?>
Результат выполнения данных примеров:
Сообщение ошибки: Unknown system variable 'a'
Смотрите также
- mysqli_connect_errno() — Возвращает код ошибки последней попытки соединения
- mysqli_connect_error() — Возвращает описание последней ошибки подключения
- mysqli_errno() — Возвращает код ошибки последнего вызова функции
- mysqli_sqlstate() — Возвращает код состояния SQLSTATE последней MySQL операции
information at saunderswebsolutions dot com ¶
17 years ago
The mysqli_sql_exception class is not available to PHP 5.05
I used this code to catch errors
<?php
$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);
if (!
$res) {
printf("Errormessage: %s\n", $mysqli->error);
}?>
The problem with this is that valid values for $res are: a mysqli_result object , true or false
This doesn't tell us that there has been an error with the sql used.
If you pass an update statement, false is a valid result if the update fails.
So, a better way is:
<?php
$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);
if (!
$mysqli->error) {
printf("Errormessage: %s\n", $mysqli->error);
}?>
This would output something like:
Unexpected PHP error [mysqli::query() [<a href='function.query'>function.query</a>]: (42S22/1054): Unknown column 'XXname' in 'field list'] severity [E_WARNING] in [G:\database.php] line [249]
Very frustrating as I wanted to also catch the sql error and print out the stack trace.
A better way is:
<?php
mysqli_report(MYSQLI_REPORT_OFF); //Turn off irritating default messages$mysqli = new mysqli("localhost", "my_user", "my_password", "world");$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);
if (
$mysqli->error) {
try {
throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $msqli->errno);
} catch(Exception $e ) {
echo "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >";
echo nl2br($e->getTraceAsString());
}
}//Do stuff with the result
?>
Prints out something like:
Error No: 1054
Unknown column 'XXname' in 'field list'
Query:
SELECT XXname FROM customer_table
#0 G:\\database.php(251): database->dbError('Unknown column ...', 1054, 'getQuery()', 'SELECT XXname F...')
#1 G:\data\WorkSites\1framework5\tests\dbtest.php(29): database->getString('SELECT XXname F...')
#2 c:\PHP\includes\simpletest\runner.php(58): testOfDB->testGetVal()
#3 c:\PHP\includes\simpletest\runner.php(96): SimpleInvoker->invoke('testGetVal')
#4 c:\PHP\includes\simpletest\runner.php(125): SimpleInvokerDecorator->invoke('testGetVal')
#5 c:\PHP\includes\simpletest\runner.php(183): SimpleErrorTrappingInvoker->invoke('testGetVal')
#6 c:\PHP\includes\simpletest\simple_test.php(90): SimpleRunner->run()
#7 c:\PHP\includes\simpletest\simple_test.php(498): SimpleTestCase->run(Object(HtmlReporter))
#8 c:\PHP\includes\simpletest\simple_test.php(500): GroupTest->run(Object(HtmlReporter))
#9 G:\all_tests.php(16): GroupTest->run(Object(HtmlReporter))
This will actually print out the error, a stack trace and the offending sql statement. Much more helpful when the sql statement is generated somewhere else in the code.
se (at) brainbits (dot) net ¶
17 years ago
The decription "mysqli_error -- Returns a string description of the LAST error" is not exactly that what you get from mysqli_error. You get the error description from the last mysqli-function, not from the last mysql-error.
If you have the following situation
if (!$mysqli->query("SET a=1")) {
$mysqli->query("ROLLBACK;")
printf("Errormessage: %s\n", $mysqli->error);
}
you don't get an error-message, if the ROLLBACK-Query didn't failed, too. In order to get the right error-message you have to write:
if (!$mysqli->query("SET a=1")) {
printf("Errormessage: %s\n", $mysqli->error);
$mysqli->query("ROLLBACK;")
}
callforeach at gmail dot com ¶
8 years ago
I had to set mysqli_report(MYSQLI_REPORT_ALL) at the begin of my script to be able to catch mysqli errors within the catch block of my php code.
Initially, I used the below code to throw and subsequent catch mysqli exceptions
<?php
try {
$mysqli = new mysqli('localhost','root','pwd','db');
if ($mysqli->connect_errno)
throw new Exception($mysqli->connect_error);
} catch (
Exception $e) {
echo $e->getMessage();
}I realized the exception was being thrown before the actual throw statement and hence the catch block was not being called.My current code looks like
mysqli_report(MYSQLI_REPORT_ALL) ;
try {
$mysqli = new mysqli('localhost','root','pwd','db');
/* I don't need to throw the exception, it's being thrown automatically */} catch (Exception $e) {
echo $e->getMessage();
}This works fine and I'm able to trap all mysqli errors
asmith16 at littlesvr dot ca ¶
9 years ago
Please note that the string returned may contain data initially provided by the user, possibly making your code vulnerable to XSS.
So even if you escape everything in your SQL query using mysqli_real_escape_string(), make sure that if you plan to display the string returned by mysqli_error() you run that string through htmlspecialchars().
As far as I can tell the two escape functions don't escape the same characters, which is why you need both (the first for SQL and the second for HTML/JS).
abderrahmanekaddour dot aissat at gmail dot com ¶
1 year ago
<?php// The idea is the add formated errors information for developers to easier bugs detection.$myfile = fopen("database_log.log", "r");
$db = new mysqli("localhost", "root","root","data");
if(!$db->query("SELECT")){
$timestamp = new DateTime();
$data_err = " {
\"title\": \" Select statement error \",
\"date_time\": ".$timestamp->getTimestamp().",
\"error\":\" ".$db->error." \"
} "; // Do more information
fwrite($myfile, $data_err); // writing data
}
// In separate file do file read and format it for good visual.$db->close();
fclose($myfile);
?>
information at saunderswebsolutions dot com ¶
17 years ago
Hi, you can also use the new mysqli_sql_exception to catch sql errors.
Example:
<?php
//set up $mysqli_instance here..
$Select = "SELECT xyz FROM mytable ";
try {
$res = $mysqli_instance->query($Select);
}catch (mysqli_sql_exception $e) {
print "Error Code <br>".$e->getCode();
print "Error Message <br>".$e->getMessage();
print "Strack Trace <br>".nl2br($e->getTraceAsString());
}?>
Will print out something like
Error Code: 0
Error Message
No index used in query/prepared statement select sess_value from frame_sessions where sess_name = '5b85upjqkitjsostvs6g9rkul1'
Strack Trace:
#0 G:\classfiles\lib5\database.php(214): mysqli->query('select sess_val...')
#1 G:\classfiles\lib5\Session.php(52): database->getString('select sess_val...')
#2 [internal function]: sess_read('5b85upjqkitjsos...')
#3 G:\classfiles\includes.php(50): session_start()
#4 G:\tests\all_tests.php(4): include('G:\data\WorkSit...')
#5 {main}
Anonymous ¶
3 years ago
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$this->connection = mysqli_connect($hostname,$username,$password, $dbname);
} catch (Exception $e) {
echo "Errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Text error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
Ok so i’m working on triggers, and it tells me it(MySQL workbench 5.2) doesn’t recognize this variable.
*Error Code: 1193. Unknown system variable error_msg_3*
I think it would be correct using it in a trigger, please help me
CREATE TRIGGER controlla_MaxCARDINALITA_INSERT
BEFORE INSERT ON SENTIERO__HA__TAPPA
FOR EACH ROW
BEGIN
DECLARE max_cardinalita INTEGER;
DECLARE error_msg_3 CONDITION FOR SQLSTATE '99003';
SELECT COUNT(*) into max_cardinalita
FROM SENTIERO__HA__TAPPA
WHERE IDsentiero=NEW.IDsentiero;
IF max_cardinalita>=10 THEN
SIGNAL error_msg_3;
SET error_msg_3='INSERT: Il sentiero ha già il massimo numero di tappe consentito';
END IF;
END$$
EDIT ::
I tried this, and it seems working
DECLARE msg VARCHAR(255);
set msg = concat('MyTriggerError: Trying to insert a negative value in trigger_test: ');
signal sqlstate '45000' set message_text = msg;