I've created a chained menu using php and a database, following this tutorial.
The first table content a list of categories like :
CREATE TABLE IF NOT EXISTS `chainmenu_categories` (
`id_cat` int(4) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
PRIMARY KEY (`id_cat`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ;
My second table, the type, like :
CREATE TABLE IF NOT EXISTS `type` (
`id_type` int(4) unsigned NOT NULL AUTO_INCREMENT,
`id_cat` int(4) unsigned NOT NULL,
`name` varchar(40) NOT NULL,
`destination` varchar(40) NOT NULL,
PRIMARY KEY (`id_type`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
I managed, once clicking on submit, to redirect to another page by that in my select.php:
var result = $("select#type option:selected").html();
$("#select_form").submit(function( event ) {
var the_url = $("#type").val();
window.location = the_url;
event.preventDefault();
});
and adding this on my select.class.php
public function ShowCategory()
{
$sql = "SELECT * FROM chainmenu_categories";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['id_cat'] . $row['destination']. '">' . $row['name'] . '</option>';
}
return $category;
}
So now it redirects each time to a different page depending of the option choose from the menu, like http://mydomain.com//3 then 4, 5, 6, etc.
But as the page doesn't exist, it redirects to a dead link.
Can someone give me help to create these pages from the chained menu (or have some highlight)? and if possible, some pointer to create the admin interface to allow an admin to add the pages and categories to the chained menu?
I've been trying to start with something which look like:
PHP Code:
<?php require('db_config.php');
$stmt = $db->prepare('SELECT id_type, name FROM type WHERE id_cat=$_POST[id]');
$stmt->execute(array(':id_cat' => $_GET['name']));
$row = $stmt->fetch();
However, I don't know if this is good at all.
if(file_exists($filename.'.php'))
echo "file : " . $filename.'.php' . " is exist";
else
{
$file = fopen($filename.'.php',"w");
$code="here what U want to write inside the new page.php";
fwrite($file,$code);
fclose($file);
}
Related
So i have Many-to-many extra table and i want to delete a row from the extra table .
CREATE TABLE `person_cars` (
`person_cars_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`person_id` int(10) NOT NULL,
`car_id` int(10) NOT NULL,
PRIMARY KEY (`person_cars_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
This PHP doesn't work
if(isset($_GET['id']) && isset($_GET['person_cars_id'])) {
$person_id = $_GET['id'];
$person_cars_id = $_GET['person_cars_id'];
$person->deleteCarOfPerson($person_cars_id);
header('location:join.php?id=' + $person_id);
}
SQL
public function deleteCarOfPerson($person_cars_id) {
$sql = ("DELETE FROM person_cars
WHERE person_cars_id = '{$person_cars_id}'");
$result = mysql_query($sql, $this->mysql_database->getConnection());
return $result;
}
Now delete is working but not header('location:join.php?id=' + $person_id);
if(isset($_GET['person_cars_id'])) {
$person_id = $_GET['id'];
$person_cars_id = $_GET['person_cars_id'];
$person->deleteCarOfPerson($person_cars_id);
header('location:join.php?id=' + $person_id);
}
Your re-direct isn't working as you're mixing PHP with Javascript.
Change
header('location:join.php?id=' + $person_id);
to
header('Location: join.php?id='.$person_id);
+ is used in Javascript to add something.
Whenever use header function you should use exit also after header redirection.
header("lOCATION:JOIN.PHP");
EXIT;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need help,
Scenario: Hotel, Checking Guests In. data in MySQL database.
MySQL:
CREATE TABLE IF NOT EXISTS `hotels` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(50) NOT NULL,
`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`Room01` int(11) NOT NULL,
`Room02` int(11) NOT NULL,
`Room03` int(11) NOT NULL,
`Room04` int(11) NOT NULL,
`Room05` int(11) NOT NULL,
`Room06` int(11) NOT NULL,
`Room07` int(11) NOT NULL,
`Room08` int(11) NOT NULL,
`Room09` int(11) NOT NULL,
`Room10` int(11) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
$result = mysql_query("SELECT * FROM hotels WHERE Name = 'hotel1'");
$row = mysql_fetch_array($result);
$room01 = $row['room01'];
0 = empty, 1 = not empty.
here is my code:
<?php
//example
$room01=1;
$room02=1;
$room03=0;
$room04=0;
//example
if ($room01 == 0)
{
echo "Your room is room01.";
}
elseif ($room02 == 0)
{
echo "Your room is room02.";
}
elseif ($room03 == 0)
{
echo "Your room is room03.";
}
elseif ($room04 == 0)
{
echo "Your room is room04.";
}
else
{
echo "None!";
}
?>
Result: Your room is room03.
What if I have 100 Rooms?
How to simplify if else statement and get the room name?
Use array_filter to find all empty rooms from database result and then print first room name, if any. Here's how you can write code without assuming there are 100 or n number of rooms in your database.
const EMPTY_ROOM = 0;
const OCCUPIED_ROOM = 1;
$rows = mysql_fetch_array($result);
$emptyRooms = array_filter($rows, function($room_value) {
return EMPTY_ROOM === $room_value;
});
if(empty($emptyRooms) || !is_array($emptyRooms)) {
echo 'None!';
return;
}
$rooms = array_keys($emptyRooms);
echo 'Your room is ' . $rooms[0] . '.' . PHP_EOL;
Update: It's probably because strict check is failing (EMPTY === $room_value). When you get data from database $room_value holds string data. Here's updated code:
function readDatabase() {
$handle = mysql_connect('localhost', 'root');
mysql_select_db('stackexchange');
if(!$handle) {
exit(mysql_error($handle));
}
$result = mysql_query("SELECT * FROM hotels WHERE Name = 'hotel1'", $handle);
return mysql_fetch_array($result, MYSQL_ASSOC);
}
$row = readDatabase();
const EMPTY_ROOM = '0';//set to string value to compare against database value
//use `array_slice` to get rid of columns: `id`, `Name`, `Date`.
//We want to search only in remaining columns: Room01, Room02 .... RoomN.
$row = array_slice($row, 3);
$emptyRooms = array_filter($row, function($room_value) {
return EMPTY_ROOM === $room_value;
});
if(empty($emptyRooms) || !is_array($emptyRooms)) {
echo 'None!';
return;
}
$rooms = array_keys($emptyRooms);
echo 'Your room is ' . $rooms[0] . '.' . PHP_EOL;
This should work (small explanation inside):
$row = mysql_fetch_array($result);
$roomNumber = 1;
//Get data from array
foreach($row as $data){
//if room returns 0 (empty)
if($data == 0){
if($roomNumber < 10){
echo "Your room is room0". $roomNumber;
break;
} else {
echo "Your room is room". $roomNumber;
break;
}
} else {
$roomNumber++;
}
}
The benefit of this approach is that it doesn't matter how many rooms you have. You can add or remove as many as you like. It'll loop through all of them, without having to adept the code.
EDIT:
After #Strawberrys comment, I realise that although my answer will work, this is not the way you should continue. Database normalisation would be the way to go. For example:
CREATE TABLE `hotels` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
CREATE TABLE `rooms` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`Hotel_id` INT(11) NOT NULL,
`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`Room_number` INT(5) NOT NULL,
`Occupied` INT(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
Using this type of Database design, you can easily add and remove Hotels to your system. Using Hotel_id as a reference, you can now easily add and remove rooms to your Hotels, without having to use an insane amount of table columns.
To use it, you simply query the Hotel_id inside rooms to get all rooms returned. Afterwards it's just a matter of checking the first Room_number where Occupied returned 0.
use array_search
const EMPTY_ROOM = 0;
$roomNumber = array_search(EMPTY_ROOM, $row);
if(false === $roomNumber) {
echo 'None!';
return;
}
echo 'Your room is ' . $roomNumber . '.' . PHP_EOL;
Update
hmm, I used test data to generate input. With your table structure here's updated code:
function readDatabase() {
$handle = mysql_connect('localhost', 'root');
mysql_select_db('stackexchange');
if(!$handle) {
exit(mysql_error($handle));
}
$result = mysql_query("SELECT * FROM hotels WHERE Name = 'hotel1'", $handle);
return mysql_fetch_array($result, MYSQL_ASSOC);
}
const EMPTY_ROOM = 0;
const OCCUPIED_ROOM = 1;
$row = readDatabase();
//use `array_slice` to get rid of columns: `id`, `Name`, `Date`. We want to search only in remaining columns: Room01, Room02 .... RoomN.
$roomNumber = array_search(EMPTY_ROOM, array_slice($row, 3));
if(false === $roomNumber) {
echo 'None!';
return;
}
echo 'Your room is ' . $roomNumber . '.' . PHP_EOL;
I have made a user_login table, having pk = userid.
A credit_request table is created which references to userid as fk.
when the user login, he should see only his entries in the dashboard.
But, here i am not able to insert data, once i link a foreign key to it.
and even the data inserted through phpmyadmin is visible to all users.
Please help me out.
how to insert and retrieve data for logged in users.
<>
//Database setup for Credit request
//Insert data into Credit request
if(isset($_POST['taskid']))
{
$taskid =$_POST['taskid'];
$orderid = $_POST['orderid'];
$status = $_POST['status'];
$query1 = "INSERT INTO credit_request(taskid, orderid, status)
VALUES ('$taskid', '$orderid', '$status')";
if ($connect->query($query1) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query1 . "<br>" . $connect->error;
}
}
//Display data for credit request
$query2 = "SELECT taskid, orderid, status FROM credit_request WHERE agentid = '$userid'";
$res = $connect->query($query2);
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
echo "<br>taskid: " . $row["taskid"]. " -orderid: " . $row["orderid"]. " --:" . $row["status"]."";
}
} else {
echo "0 results";
}
I think you have problem on update, on delete when creating foreign key..
Here's an example of how you'd build your schema:
CREATE TABLE `country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`country_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
CREATE TABLE `state_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state_name` varchar(45) DEFAULT NULL,
`country_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `country_fk` FOREIGN KEY (`country_id`)
REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='';
INSERT INTO country (country_name) VALUES ('US of A');
INSERT INTO state_table (state_name,country_id) VALUES
('Minnesota', 2),
('Arizona', 2);
See this fiddle for more.
I've been doing a chained select menu by Php, using a database SQL ( as i need later on t develop an update possibility for the client).
However, the chained menu ( at 2 levels) works perfectly,
Problem is I've no idea how to link the button to an other page once submitting . . . and depending of the "items" selected, If anybody can give me some highlite, i'll be really thanksfull.
Here is the Jquery part, which now display the value directly:, instead of this i 'd like to link to an other page.
$("#result").html('Your choice: '+result);
Here is the tutorial I've been following to do it:
http://www.yourinspirationweb.com/en/how-to-create-chained-select-with-php-and-jquery/
THank you so much !!
Firs, if you need to send the user to a different page depending on the selection, you should create a field "destination" where you can save the urls on the database:
CREATE TABLE `type` (
`id_type` int(4) unsigned NOT NULL auto_increment,
`id_cat` int(4) unsigned NOT NULL,
`name` varchar(40) NOT NULL,
`destination` varchar(40) NOT NULL,
PRIMARY KEY (`id_type`)
) ENGINE=MyISAM AUTO_INCREMENT=15 ;
then get the urls from the table and put them on the option value
public function ShowCategory()
{
$sql = "SELECT * FROM category";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['destination'] . '">' . $row['name'] . '</option>';
}
return $category;
}
And finaly make a jQuery to redirect to the page on submit
$("#select_form").submit(function( event ) {
var the_url = $("#type").val();
window.location = the_url;
event.preventDefault();
});
Hope that help.
Good day to all. I'm trying to make a task tracking module for my system. The logic is, whenever I assign a task to a user, the system updates the task to "IsTaken" meaning the particular user is responsible for that task. Upon updating, it creates an entry into "user_task" table which basically ties together the task and the user table. Whenever I assign a task to somebody it's fine. But when I do it again, the previous task record's IsTaken field reverts back to 0. I try to re-assign it, but again, the previous record reverts. It's quite weird. I'm using XAMPP, MySQL and PHP. I'm hoping I'm not the only one experiencing this. Any help would be much appreciated.
Here are my tables:
CREATE TABLE IF NOT EXISTS `task` (
`Task_No` int(11) NOT NULL AUTO_INCREMENT,
`Task_Name` varchar(100) NOT NULL,
`Task_Desc` varchar(450) DEFAULT NULL,
`Task_DateCreated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`Task_IsTaken` tinyint(1) NOT NULL,
PRIMARY KEY (`Task_No`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `user_task` (
`UT_No` int(11) NOT NULL AUTO_INCREMENT,
`User_Email` varchar(100) NOT NULL,
`Task_No` int(11) NOT NULL,
`Task_Duration` varchar(20) NOT NULL,
`Task_DateTaken` date DEFAULT NULL,
`Task_DateFinished` timestamp NULL DEFAULT NULL,
`Task_IsIssue` tinyint(1) NOT NULL,
PRIMARY KEY (`UT_No`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
And here are my scripts (from the form):
//Process - Insert Task
if(isset($_POST['btnCreateTask']))
{
if($_POST['taskName']!=NULL)
{
$taskName = mysql_real_escape_string ($_POST['taskName']);
$taskDesc = mysql_real_escape_string ($_POST['taskDesc']);
$insertTask = "INSERT INTO task(Task_Name, Task_Desc, Task_IsTaken) VALUES('$taskName', '$taskDesc', 0)";
$sqlResult1 = mysql_query($insertTask);}
else
{
echo "No task name given";
$errorCode = 1;
}
}
if(isset($_POST['btnAssignTask']))
{
if($_POST['assignTaskName']!=NULL)
{
$assigntaskName = mysql_real_escape_string($_POST['assignTaskName']);
$assigntaskNo = mysql_real_escape_string($_POST['assignTaskNo']);
$assigntaskOwner = mysql_real_escape_string($_POST['assignTaskOwner']);
$assigntaskDuration = mysql_real_escape_string($_POST['assignTaskDuration']);
$updateUpcomingTask = "UPDATE task SET Task_IsTaken = '1' AND Task_No = '$assigntaskNo'";
$createUserTask = "INSERT INTO user_task (User_Email, Task_No, Task_Duration, Task_DateTaken, Task_DateFinished)
VALUES ('$assigntaskOwner', '$assigntaskNo', '$assigntaskDuration', '$now', NULL)";
$sqlResult2 = mysql_query($updateUpcomingTask);
$sqlResult3 = mysql_query($createUserTask);
}
else
{
echo "No task selected";
$errorCode = 2;
}
}
Your code should be changed to:
if(isset($_POST['btnAssignTask']))
{
if($_POST['assignTaskName']!=NULL)
{
$assigntaskName = mysql_real_escape_string($_POST['assignTaskName']);
$assigntaskNo = intval($_POST['assignTaskNo']);
$assigntaskOwner = mysql_real_escape_string($_POST['assignTaskOwner']);
$assigntaskDuration = mysql_real_escape_string($_POST['assignTaskDuration']);
$updateUpcomingTask = "UPDATE task SET Task_IsTaken = '1' WHERE Task_No = $assigntaskNo";
$createUserTask = "INSERT INTO user_task (User_Email, Task_No, Task_Duration, Task_DateTaken, Task_DateFinished)
VALUES ('$assigntaskOwner', '$assigntaskNo', '$assigntaskDuration', '$now', NULL)";
$sqlResult2 = mysql_query($updateUpcomingTask);
$sqlResult3 = mysql_query($createUserTask);
}
else
{
echo "No task selected";
$errorCode = 2;
}
}