i have a DB MySQL;
CREATE TABLE IF NOT EXISTS `obsequios` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`promocion` int(1) NOT NULL,
`dia` date NOT NULL,
`hora` time NOT NULL,
`autorizacion` varchar(30) NOT NULL,
`obsequiado_a` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
php code:
$sql_obsequios = '"INSERT INTO `obsequios`(`promocion`, `dia`, `hora`, `autorizacion`, `obsequiado_a`) VALUES ('.$promocion.','.'"'.$date.'"'.','.'"'.$hour.'"'.','.'"'.$user_loading.'"'.','.'"'.$regalado_a.'"'.')"';
$sql_obsequios_result = mysqli_query($con, $sql_obsequios);
if ($sql_obsequios_result) {
$result_gral = true;
}else{
$result_gral = false;
}
when I try to add data to the table, I get the value return is false.
try to see the value of $ sql_obsequiosy its value is as follows:
"INSERT INTO `obsequios`(`promocion`, `dia`, `hora`, `autorizacion`, `obsequiado_a`)
VALUES (1,"2014-04-13","08:47:55","marcos","sergio")"
using phpmyadmin I have managed to successfully query. I detect what's wrong in this code
Where is Your instructions to add data to DB ?
$sql_obsequios = ...
if ($sql_obsequios_result) ...
it is not the same
Try this and see the difference:
$sql_obsequios = "
INSERT INTO `obsequios`
(`promocion`, `dia`, `hora`, `autorizacion`, `obsequiado_a`)
VALUES
('".$promocion."','".$date."','".$hour."','".$user_loading."','".$regalado_a."')";
Also, I dont see any call of mysql_query() or something to get $sql_obsequios_result
Try this:
$sql_obsequios = "INSERT INTO `obsequios`(`promocion`, `dia`, `hora`, `autorizacion`, `obsequiado_a`) VALUES ('$promocion','$date','$hour','$user_loading','$regalado_a')";
$sql_obsequios_result = mysql_query(sql_obsequios);
if ($sql_obsequios_result) {
$result_gral = true;
}else{
$result_gral = false;
}
Or try:
$sql_obsequios = "INSERT INTO obsequios(promocion, dia, hora, autorizacion, obsequiado_a) VALUES ('.$promocion.',''.$date.'',''.$hour.'',''.$user_loading.'',''.$regalado_a.'')";
$sql_obsequios_result = mysql_query(sql_obsequios);
if ($sql_obsequios_result) {
$result_gral = true;
}else{
$result_gral = false;
}
Related
I have an php array:
$cont_array = Array("613:m-ent:id=one","930:m-lk:id=one;x=180;y=79;which=1","1080:m-lev:id=one;");
I want to insert it into a MySQL table with table-name as variable, like $table_name = "user1".
In addition, I want to break each array-element by the first ":" .After executing my php code I get just an empty table.
I need help please. This is my code:
<?php
$connection = mysqli_connect('localhost','root','','prueba');
$cont_array = Array("613:m-ent:id=one","930:m-clk:id=one;x=180;y=79;which=1","1080:m-lev:id=one;");
$table_name = "user1";
$sql_1 = "DROP TABLE IF EXISTS `".$table_name."`;";
$sql_1 .= "CREATE TABLE `".$table_name."` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`usercod` varchar(20) NOT NULL DEFAULT '',
`pid` varchar(1000) NOT NULL DEFAULT '',
`name` varchar(1000) NOT NULL DEFAULT '',
`time` varchar(1000) NOT NULL DEFAULT '',
`all_act` varchar(1000) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;";
mysqli_multi_query($connection,$sql_1);
foreach ($cont_array as $row){
$break_e = explode(':', $row, 2);
$sql="INSERT INTO`".$table_name."` (usercode,pid,name,time,all_act) VALUES ("user","pid_value","user_name",'$break_e [0]','$break_e [1]');";
mysqli_query($connection,$sql);
}
?>
This is what I get:
This is what I would like to get:
Your SQL seem to have issue check below SQL statement.
$sql = "INSERT INTO $table_name (usercod,pid,name,time,all_act) VALUES ('user','pid_value','user_name','".$break_e [0]."','".$break_e [1]."')";
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;
Im trying to Get the users teams he is a part of to compare the 2 tables
DB TABLES:
CREATE TABLE `teams` (
`teamid` int(11) NOT NULL AUTO_INCREMENT,
`teamname` varchar(45) DEFAULT NULL,
`teamdesc` longtext,
`founder` varchar(45) NOT NULL,
`dateformed` int(11) NOT NULL,
PRIMARY KEY (`teamid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
CREATE TABLE `teammembers` (
`teamid` int(11) NOT NULL,
`member` varchar(45) NOT NULL,
`rank` varchar(45) DEFAULT NULL,
PRIMARY KEY (`teamid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Current function i have to do stuff:
/* removeProject */
function getTeamNames($id){
global $session, $database;
$link = $database->connection;
$stmt = $link->prepare("SELECT teamname FROM teams WHERE teamid=$id");
$stmt->execute();
$r = $stmt->fetch();
return array('teams'=>$r['teamname']);
}
Query to get the team names:
$link = $database->connection;
try{
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = "SELECT * FROM teammembers WHERE member=:un";
$prep = $link->prepare($q);
$array = array(
':un' => $user
);
$prep->execute($array);
}catch(PDOException $error){
echo($error);
}
Then the info to display the data:
<select multiple class="form-control">
<?php
while($tid = $prep->fetch()){
$teams = $database->getTeamNames($tid['teamid']);
echo ("<option>$teams</option>");
} ?>
</select>
Its only displaying the data as "Array"
UPDATE!!!
This is how i fixed it :)
while($tid = $prep->fetch()){
$teams = $database->getTeamNames($tid['teamid']);
//echo var_dump($teams);
$team = $teams['teams'];
echo ("<option>$team</option>");
}
The code is correct, you returned the data as array (return array('teams'=>$r['teamname']);)
So when you echo the data, use echo("<option>".$teams['teams']."</option>") or dont return result as an array.
Your function function getTeamNames($id) returns an associative array that's why you are not getting the results.
Your loop should look something like
<?php
while($tid = $prep->fetch()){
$teams = $database->getTeamNames($tid['teamid']);
foreach($teams['teams'] as $team){
echo ("<option>$teams</option>");
}
}
?>
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;
}
}