I am getting this error:
Fatal error: Array callback has to contain indices 0 and 1 in C:xampphtdocsphpprojectsplappworker.php on line 53
How can I solve that problem? What’s wrong with what I am doing here?
$results = mysql_query("SELECT asin_link FROM work WHERE email=$w_email");
while($row = mysql_fetch_array($result)) {
$work_link = $row['asin_link'];
echo '<a href="'.$work_link.'" target="'.$work_link.'">Visit Work link<br></a>';
echo '<form action="" method="post">
ASIN Number: <input type="text" name="asin"><br>
<input type="submit" value="Submit" name="submit">
</form>';}
if (isset($_POST['submit'])) {
$asin = $_POST('asin');
$qu ="INSERT INTO work (asin, email, asin_link) VALUES ('$asin', '$w_email','$work_link')";
if (mysql_query($qu)) {
echo "Your ASIN was received! Thanks";
}
}
Panda
6,9356 gold badges41 silver badges55 bronze badges
asked May 22, 2016 at 4:09
0
change this
$asin = $_POST('asin');
to
$asin = $_POST['asin'];
answered May 22, 2016 at 4:13
Waleed AhmedWaleed Ahmed
1,13410 silver badges16 bronze badges
4
It happens because your code tried to call an array as a function.
(That’s why the error calls it Array Callback)
I know it’s really late for any answers on this, but for anyone else coming from Googling this error and seeking more info I post this example of alternative syntax, it seems to run PHP >= 7 :
<?php
class A {
static function ech($a) {echo $a;}
function echa($a) {echo $a;}
}
['A', 'ech']('Test');
[new A, 'echa']('Test');
Yes, it seems arrays can be called as functions.
answered May 3, 2022 at 9:32
Содержание
- php — Fatal error: Array callback has to contain indices 0 and 1
- Answer
- Solution:
- Share solution ↓
- Additional Information:
- Didn’t find the answer?
- Similar questions
- Write quick answer
- About the technologies asked in this question
- MySQL
- Welcome to programmierfrage.com
- Get answers to specific questions
- Help Others Solve Their Issues
- Name already in use
- php-src / Zend / tests / bug63173.phpt /
- Footer
- Fatal error – page do not load properly and cannot access admin panel either.
- Ошибка при обновлении php до 8
- Fatal error: Uncaught Error: Call to undefined function mysql_connect() — как исправить
- С чем связана ошибка Fatal error
- Создание резервных копий сайта
- Настройка журнала ошибок
- Переводим сайт на MySQLi
- CP1251 и PHP 7 – как расшифровать непонятный набор символов
- Заключение
php — Fatal error: Array callback has to contain indices 0 and 1
I am getting this error:
Fatal error: Array callback has to contain indices 0 and 1 in C:xampphtdocsphpprojectsplappworker.php on line 53
How can I solve that problem? What’s wrong with what I am doing here?
Answer
Solution:
Additional Information:
Didn’t find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
About the technologies asked in this question
PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
MySQL
DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL. It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/
Welcome to programmierfrage.com
programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.
Get answers to specific questions
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Help Others Solve Their Issues
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.
Источник
Name already in use
php-src / Zend / tests / bug63173.phpt /
- Go to file T
- Go to line L
- Go to definition R
- Copy path
- Copy permalink
Copy raw contents
Copy raw contents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| —TEST— |
| Bug #63173: Crash when invoking invalid array callback |
| —FILE— |
| // the important part here are the indexes 1 and 2 |
| $ callback = [ 1 => 0 , 2 => 0 ]; |
| $ callback (); |
| ?> |
| —EXPECTF— |
| Fatal error: Uncaught Error: Array callback has to contain indices 0 and 1 in %s:%d |
| Stack trace: |
| #0 |
| thrown in %s on line %d |
© 2023 GitHub, Inc.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Fatal error – page do not load properly and cannot access admin panel either.
Please help:
Our website is down with Fatal error message: “Uncaught Error: Array callback has to contain indices 0 and 1 in /home/customer/www/kirnukreativ.com/public_html/wp-content/themes/bifrost/functions.php:319 Stack trace: #0 /home/customer/www/kirnukreativ.com/public_html/wp-includes/class-wp-hook.php(287): bifrost_widgets_init(”) #1 /home/customer/www/kirnukreativ.com/public_html/wp-includes/class-wp-hook.php(311): WP_Hook->apply_filters(”, Array) #2 /home/customer/www/kirnukreativ.com/public_html/wp-includes/plugin.php(484): WP_Hook->do_action(Array) #3 /home/customer/www/kirnukreativ.com/public_html/wp-includes/widgets.php(1795): do_action(‘widgets_init’) #4 /home/customer/www/kirnukreativ.com/public_html/wp-includes/class-wp-hook.php(287): wp_widgets_init(”) #5 /home/customer/www/kirnukreativ.com/public_html/wp-includes/class-wp-hook.php(311): WP_Hook->apply_filters(NULL, Array) #6 /home/customer/www/kirnukreativ.com/public_html/wp-includes/plugin.php(484): WP_Hook->do_action(Array) #7 /home/customer/www/kirnukreativ.com/public_html/wp-settings.php(557) in /home/customer/www/kirnukreativ.com/public_html/wp-content/themes/bifrost/functions.php on line 319″.
The problem is that I cannot access WordPress admin panel (also not in recovery mode either). I assume this some kind of plugin problem as refers to bifrost theme plugin. Please help, how to fix this!
We use SiteGround as service provider. Thanks for any guidance!
The page I need help with: [log in to see the link]
Most probably it’s your theme.
Try manually resetting your plugins (no Dashboard access required). If that resolves the issue, reactivate each one individually until you find the cause.
If that does not resolve the issue, access your server via SFTP or FTP, or a file manager in your hosting account’s control panel, navigate to /wp-content/themes/ and rename the directory of your currently active theme. This will force the default theme to activate and hopefully rule-out a theme-specific issue (theme functions can interfere like plugins).
Источник
Ошибка при обновлении php до 8
| Цитата |
|---|
| написал: non-static method JivoSiteClass::addScriptTag() cannot be called statically |
Убрал приложение, сайт стартует, но есть что не работает и выдает ошибки.
В общем решил отложить эту затею как минимум на пол года, к тому времени уже думаю совместимость будет куда выше.
| Цитата |
|---|
| написал: Обратиться к разработчикам JivoSite |
| Цитата |
|---|
| написал: Так ошибка в самом ядре, лезть в ядро, чтобы обновить ядро?) |
| Цитата |
|---|
| написал: Так ошибка в самом ядре, лезть в ядро, чтобы обновить ядро?) |
На вашем скрине — ошибка в кастомном классе, а не в ядре.
А помочь и подсказать как, ну ни как, ладно Анатолий Зайчёнок хоть ссылку кинул, почитать. Вообще об этом Битриксоиды должны думать под их руководством писали модули и выкладывали на маркет
Вчера обновил до php8.0 из 12 модулей осталось 3, пришлось вернуть все в зад до php7.4
| Цитата |
|---|
| написал: Интересно сколько времени ещё пройдёт до тех пор пока кто-нибудь объяснит на примере как надо переделать код, чтоб рабочий код в php 7.4 оставался рабочим и в php 8. |
| Цитата |
|---|
| написал: Интересно сколько времени ещё пройдёт до тех пор пока кто-нибудь объяснит на примере как надо переделать код, чтоб рабочий код в php 7.4 оставался рабочим и в php 8. |
Да чего объяснять то?
Я же дал ссылку.
Проблема основная одна — статически вызывается метод класса, в котором не указано static в коде.
Соответственно, проходимся по всем сторонним модулям и прописываем static.
Проблема в том что поставив костыль, потом так и пойдешь с ним, и где ниб он вылезет опять, тогда зачем вообще битрикс и маркет и все модули, т.е. это не решено в самой системе. Переходить на php8 чтобы потом всё работало на костылях? отличный план!
А админ молчит, видно зубы лечит
| Цитата |
|---|
| написал: я на всех сайтах использовал код приведенный здесь в документации Битрикса в качестве примера |
Вероятно, Вы брали код когда-то давно. Сейчас сходил по указанной ссылке — код в примере имеет ключевое слово static в объявлении метода, всё ок.
Лично я не понимаю, почему разработчики Битрикса страдали этой глупостью ( не указывали у явно статических методов static, и при этом вызывали эти методы как статические ) более десятка лет, но имеем, что имеем.
| Цитата |
|---|
| написал: Проблема в том что поставив костыль |
| Цитата |
|---|
| написал: Проблема в том что поставив костыль |
Это не костыль. Это исправление бага, который раньше жить не мешал, а теперь мешает.
Я может не понимаю, но у меня 12 модулей при переводе на php 8 осталось работать только 3, но мне нужен весь комплект. Хорошо я поправил баг, при любом другом обновлении все начнется сначала. Хорошо отделю модули и вынесу отдельно, тогда модули перестанут обновляться.
По любому битриксоидам нужно решать это в общем комплексе и для всех, а не только предупреждать что с 1 февраля не будет поддержки ( «. а кто не купит лотерею отключим газ»)
Мое мнение такое, что сначала предупредить разработчиков — кто не обновит до поддержки php8 удалим с маркета, или разделить маркет до и маркет после (может кто то захочет остаться и не обновляться вообще, я знаю таких). И после этого клиентам — — — Обновитесь.
Источник
Fatal error: Uncaught Error: Call to undefined function mysql_connect() — как исправить
PHP 7 является новой версией языка программирования. Её предшественницей считается PHP 5, т. к. 6 версия так и не была выпущена для общего пользования в связи с возникшими во время разработки проблемами. Но это отдельная тема, а сегодня мы разберем, когда при переводе сайта с PHP 5 на PHP 7 возникает ошибка Fatal error: Uncaught Error: Call to undefined function mysql_connect(), и как её исправить, чтобы наш ресурс заработал быстрее, стабильнее и надежнее.
С чем связана ошибка Fatal error
Ошибка, начинающаяся словами «Fatal error: Uncaught Error:», вызывает прекращение работы скрипта. В нашем случае она вместе с рядом других часто появляется при переводе старого сайта с PHP 5 на PHP 7. Выскакивают либо сообщения с уведомлениями об ошибках, либо просто висит белый экран. Здесь есть 2 пути – либо вернуть все назад, переключившись в панели управления хостингом, либо проявить настойчивость, разобраться с этой ошибкой и работать уже с новой версией PHP. Итак, давайте посмотрим, с чем же конкретно связана наша ошибка.
Как видно из самого названия ошибки, проблема связана с тем, что новые версии PHP (начиная с v. 5.5.0) не осуществляют поддержку оригинального расширения MySQL, в связи с чем сайт не собирает и не отправляет данные из БД. В этом случае разработчики предлагают перейти на расширения PDO или MySQLi. Попробуем выполнить несколько простых действий по переходу на MySQLi. Также пользователи иногда сталкиваются с ошибкой Error CertEnroll, возникающей в процессе создания запроса на выпуск сертификата на сайте “Росказна”.
Создание резервных копий сайта
Прежде чем предпринимать какие-либо серьезные попытки исправить Fatal error: Uncaught Error: Call to undefined function mysql_connect, необходимо создать резервные копии своего сайта и БД. Также для того, чтобы была неограниченная возможность экспериментировать, добавляем на хостинге еще один сайт и копируем туда файлы, в которые будем вносить различные корректировки. Подобный подход поможет избежать последствий необдуманных или неосторожных действий с данными – мы их уже не потеряем, т. к. они дополнительно хранятся в резервных копиях. Это актуально при решении различных задач, например, при отладке кода на JavaScript иногда приходится решать ошибку TypeError: Cannot read property ‘xxx’ of undefined.
Настройка журнала ошибок
Также настраиваем ведение журнала ошибок (если этого не было сделано ранее). Открываем файл .htaccess и корректируем информацию в нем. Она должна выглядеть следующим образом.
Мы найдем файл .htaccess, если пройдем путь /home/login/domains/domain.ru/public_html/, где login – это логин нашего аккаунта, а domain.ru – домен нашего сайта. Третья строка на картинке выше показывает, где лежит файл с ошибками PHP, которые записываются в процессе работы сайта. Открыть error.log и просмотреть журнал ошибок возможно при помощи файлового менеджера в Панели управления.
Переводим сайт на MySQLi
Итак, вначале вносим коррективы в конструкцию, при помощи которой сайт подключается к базе данных. Открываем действующую запись.
- Везде mysql меняем на mysqli.
- В первой строчке после $password через запятую добавляем $dbname.
- Вторую строчку mysql_select_db($dbname, $link) убираем совсем.
- В третьей строчке перед ‘set names cp1251’ ставим $link и запятую.
В конструкцию, отвечающую за запросы, также вносим изменения. Берем действующую запись.
- Также заменяем mysql на mysqli.
- Меняем местами то, что заключено в скобки.
Теперь выглядит так.
Измененная конструкция, отвечающая за запросы
Открываем следующие популярные функции:
- mysql_fetch_array();
- mysql_fetch_row();
- mysql_fetch_assoc();
- mysql_fetch_array();
- mysql_num_rows();
- mysql_insert_id();
- mysql_close().
И везде производим замену mysql на mysqli. Наша картина выглядит следующим образом.
Теперь сбор и отправка информации из БД должны осуществляться без сбоев.
CP1251 и PHP 7 – как расшифровать непонятный набор символов
Иногда при написании сайта некоторые программисты используют не процедурный подход, являющийся на данный момент самым кратким решением, не раз доказавшим свою эффективность, а кодировку CP1251 и другие. В этом случае при переходе на PHP 7 на экране компьютера вся информация выглядит как непонятный набор палочек и иероглифов. В этом случае пробуем в файле дополнительной конфигурации .htaccess указать кодировку так.
Исправляем ситуацию в сайте, написанном при помощи CP1251
Проблемы с компьютером возникают нередко, и многие из них нужно научиться устранять самостоятельно. Например, это такие ситуации, как ошибка html5 Video file not found при просмотре видеороликов в сети или ошибки 0x0001, 0x0003 в дополнительной утилите Nvidia GeForce Experience.
Заключение
В этой статье мы рассмотрели, почему при переводе сайта с PHP 5 на PHP 7 возникает ошибка Fatal error: Uncaught Error: Call to undefined function mysql_connect(), и рассмотрели пути ее решения. Сложного в этом ничего нет, были внесены небольшие коррективы в конструкции, отвечающие за подключение к БД и за запросы. Также коснулись ситуации, когда сайт написан с использованием старой кодировки CP1251. Надеюсь, что предложенные варианты помогут вам исправить ситуацию и без проблем работать на PHP 7.
Источник
Я хочу создать систему обмена сообщениями, и вот ее php-код
<?php
$connect= new mysqli('localhost', 'root','' ,'user');
if($connect->connect_error){
die('connection failed bruh');
} else
echo 'connected';
$message= $_POST('message');
$name= $_POST('name');
$sql = "INSERT message into user WHERE name=$name AND message=$message ";
$result = $connect-> query($sql);
if ($result-> num_rows > 1 ){
while ($result->fetch_assoc()){
echo $row["$message"];
}
} else {
echo 'some error';
}
?>
А HTML — это
<!DOCTYPE html>
<html>
<head>
<title>CHATTING WEB</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="cbox">
<div class="clogs">
<div class="chat friend">
<div class="user-photo"> </div>
<p class="c-message">Hi there!</p>
</div>
<div class="chat self">
<div class="user-photo"> </div>
<p class="c-message">Hi!...How are you..?</p>
</div>
</div>
<form action="post.php" method="post">
<div class="c-form">
<input type="text" name="name" required>
<textarea name="message"></textarea>
<button>send</button>
</div>
</form>
</div>
</body>
</html>
И я получаю ФАТАЛЬНУЮ ОШИБКУ:
Fatal error: Array callback has to contain indices 0 and 1 in
E:xamphtdocschattingpost.php on line 14
У меня возникла эта ошибка, и если кто-то считает, что в этом коде больше ошибок, скажите, пожалуйста, что я использовал фигурные скобки, но он все еще не работает
2 ответа
Лучший ответ
Вы должны основные ошибки:
1 .
$message= $_POST['message'];
$name= $_POST['name'];
2 .
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";";
0
Yosved Villar
23 Май 2017 в 22:07
Вам нужно использовать квадратные скобки для доступа к свойствам массива $_POST:
$message= $_POST['message'];
$name= $_POST['name'];
0
rickdenhaan
23 Май 2017 в 20:42
-
Home
- php — Fatal error: Array callback has to contain indices 0 and 1
360 votes
1 answers


Get the solution ↓↓↓
I am getting this error:
Fatal error: Array callback has to contain indices 0 and 1 in C:xampphtdocsphpprojectsplappworker.php on line 53
How can I solve that problem? What’s wrong with what I am doing here?
$results = mysql_query("SELECT asin_link FROM work WHERE email=$w_email");
while($row = mysql_fetch_array($result)) {
$work_link = $row['asin_link'];
echo '<a href="'.$work_link.'" target="'.$work_link.'">Visit Work link<br></a>';
echo '<form action="" method="post">
ASIN Number: <input type="text" name="asin"><br>
<input type="submit" value="Submit" name="submit">
</form>';}
if (isset($_POST['submit'])) {
$asin = $_POST('asin');
$qu ="INSERT INTO work (asin, email, asin_link) VALUES ('$asin', '$w_email','$work_link')";
if (mysql_query($qu)) {
echo "Your ASIN was received! Thanks";
}
}
2022-03-7
Write your answer
828
votes


Answer
Solution:
change this
$asin = $_POST('asin');
to
$asin = $_POST['asin'];
Share solution ↓
Additional Information:
Date the issue was resolved:
2022-03-7
Link To Source
Link To Answer
People are also looking for solutions of the problem: composer detected issues in your platform: your composer dependencies require a php version «>= 8.0.2».
Didn’t find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
About the technologies asked in this question
PHP
PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
MySQL
DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL.
It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/
Welcome to programmierfrage.com
programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.
Get answers to specific questions
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Help Others Solve Their Issues
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.
PHP Online Compiler
Write, Run & Share PHP code online using OneCompiler’s PHP online compiler for free. It’s one of the robust, feature-rich online compilers for PHP language, running on the latest version 7. Getting started with the OneCompiler’s PHP compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as PHP and start coding.
Taking inputs (stdin)
OneCompiler’s PHP online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample PHP program which takes name as input and prints hello message with your name.
<?php
fscanf(STDIN, "%sn", $name);
echo "Hello ".$name.".n";
?>
About PHP
PHP(Hypertext Preprocessor) is widely used server sripting language by Rasmus Lerdorf in the year 1994.
Key features
- Free
- powerful tool for making dynamic and interactive web pages
- can integrate with almost all popular databases like MySQL, PostgreSQL, Oracle, Sybase, Informix, Microsoft SQL Server etc.
- C like Syntax and easy to learn.
- Object oriented scripting language.
- easily embeddable into HTML
- Loosely typed language.
Syntax help
Variables
In PHP, there is no need to explicitly declare variables to reserve memory space. When you assign a value to a variable, declaration happens automatically. Variables are case-sensitive in PHP.
$variable_name = value;
Loops
1. IF Family:
If, If-else, Nested-Ifs are used when you want to perform a certain set of operations based on conditional expressions.
If
if(conditional-expression){
//code
}
If-else
if(conditional-expression){
//code if condition is true
} else {
//code if condition is false
}
Nested-If-else
if(condition-expression1) {
//code if above condition is true
} elseif(condition-expression2){
//code if above condition is true
}
elseif(condition-expression3) {
//code if above condition is true
}
...
else {
//code if all the conditions are false
}
2. Switch:
Switch is used to execute one set of statement from multiple conditions.
switch(conditional-expression) {
case value1:
// code if the above value is matched
break; // optional
case value2:
// code if the above value is matched
break; // optional
...
default:
// code to be executed when all the above cases are not matched;
}
3. For:
For loop is used to iterate a set of statements based on a condition.
for(Initialization; Condition; Increment/decrement){
// code
}
For-each:
// you can use any of the below syntax
foreach ($array as $element-value) {
//code
}
foreach ($array as $key => $element-value) {
//code
}
4. While:
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while(condition) {
// code
}
5. Do-While:
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (condition);
Functions
Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity.
How to define a Function
function function_name(parameters) {
//code
}
How to call a Function
function_name (parameters)
I’m new to PHP. I’m currently working on adding data into a MySQL database table ‘store’ from store_master entered into an HTML form (Store name, address store, and status store). I’m at a complete loss. I have been struggling over this for the past few hours. I looked at a lot of similar questions, but I still don’t see/understand what’s going wrong in my code. About the error page it’s like the image I had attached.
This is crudAction.php
<?php
function runQuery($db, $query, $queryType) {
$result = mysqli_query($db, $query);
if(!empty(mysqli_error($db))) {
return [
'error' => true,
'message' => mysqli_error($db)
];
}
return [
'error' => false,
'message' => getMessage($queryType)
];
}
function buildInsertQuery($tableName, $data) {
$tableColumns = [];
$insertValues = [];
foreach ($data as $key => $value) {
array_push($tableColumns, $key);
array_push($insertValues, $value);
}
$columns = "(`" . implode("`,`", $tableColumns) . "`)";
$values = "('" . implode("','", $insertValues) . "')";
$query = "INSERT INTO `$tableName` ". $columns . " VALUES " . $values ." ";
return $query ?? false;
}
function getMessage($queryType) {
$messages = [
'insert' => 'Data has been succesfuly added',
'delete' => 'Data has been succesfuly deleted'
];
return $messages($queryType);
}
function getLastID() {
return mysqli_insert_id();
}
?>
This is formAction.php
<?php
$actionObject = $_REQUEST['actionObject'] ?? '';
$actionType = $_REQUEST['actionType'] ?? '';
include $actionObject .'Crud.php';
include 'config.php';
function getTableName($actionObject)
{
$tableMapping = [
'toko' => 'master_toko'
// 'barang' => 'table_barang',
// 'jenis' => 'table_jenis',
];
return $tableMapping[$actionObject];
}
$db = getDBConnection();
$tableName = getTableName($actionObject);
switch($actionType):
case 'insert' : $result = insertData($db, $tableName);
break;
case 'delete' : $result = deleteData($db, $tableName);
break;
case 'update' : $result = updateData($db, $tableName);
break;
endswitch;
if (!$result['error']) {
header('location: ' . $_REQUEST['pageReferrer'] . '&success=true&message=' . $result['message']);
} else {
header('location: ' . $_REQUEST['pageReferrer'] . '&error=true&message=' . $result['message']);
}
?>
This is tokoCrud.php
<?php
include ('crudAction.php');
function insertData($db, $tableName) {
$data = [
'id_ot' => ' ',
'nama_ot' => $_POST['namaToko'],
'alamat_ot' => $_POST['alamatToko'],
'status_ot' => '1'
];
$query = buildInsertQuery($tableName, $data);
return runQuery($db, $query, 'insert');
}
?>
This is the HTML Form
<?php
require "partial/header.php";
require "partial/sidebar.php";
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Master Toko</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="#">Home</a></li>
<li class="breadcrumb-item active">Master Toko</li>
</ol>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Data Toko</h3>
<button type="button" class="btn btn-success float-right" data-toggle="modal" data-target=".modalBesar">Tambah Data</button>
</div>
<!-- Bagian Form Modal -->
<div class="modal fade modalBesar" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel">Tambah Toko</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method = "post" action = "library/services/formAction.php">
<input type="hidden" name="pageReferrer" value="" >
<input type="hidden" name="actionObject" value="toko" >
<input type="hidden" name="actionType" value="insert" >
<div class="form-group">
<label for="recipient-name" class="col-form-label">Nama Toko</label>
<input type="text" class="form-control" id="namaToko" placeholder="Masukkan Nama Toko" name="namaToko" required>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Alamat Toko</label>
<input type="text" class="form-control" id="alamatToko" placeholder="Masukkan Nama Toko" name="alamatToko" required>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Akhir Bagian Modal -->
<!-- /.card-header -->
<div class="card-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>No</th>
<th>Toko</th>
<th>Alamat</th>
<th>Status</th>
<th>Opsi</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- /.content-wrapper -->
<?php require "partial/footer.php"; ?>













