FIXED BUT HAVE TO WAIT ONE DAY
I got a table from MySQL on my php page. First I needed to sort the columns which is working great. Now I need to be able to edit, add und delete the rows which I can't seem to get to work
I already tried every pre-built plugin I was able to find but nothing worked. I always wasn't able to save the edits into my database. If that comes to your mind: Yes I set up the connection correctly.
I'm to unexperienced to write that code by myself that's why I'm asking you for help
What the "plugin" should do is that I can edit, add and delete rows. It should be saved into my database the second I hit save.
I appreciate any help. Even some starting/important parts for the code that I have to finish myself
I fixed it while reading everything again.
OLD:
if($input["action"] === 'edit') {
$query = "UPDATE Test SET
Date = '$date',
User = '$user',
// some more stuff but enough
WHERE Num = '$num'";
$connect->query($query);
}
NEW:
if($input["action"] === 'edit') {
$query = "UPDATE Test SET
Date = '$date',
User = '$user'
//some more stuff but enough
WHERE Num = '$num'";
$connect->query($query);
}
Had do delete one , after the last column to change.
Related
This is my php code that will put the inserted data to database and will prevent to insert data if there is duplicate.
include('session.php');
$cid="";
$chat_name=$_POST['chatname'];
$chat_password=$_POST['chatpass'];
$sql3="SELECT * FROM chatroom where chat_name='$chat_name'";
$query=mysqli_query($conn,$sql3);
if(mysqli_affected_rows($query) == 1){
echo("<script>alert('ee');</script>");
}
else{
mysqli_query($conn,"insert into chatroom (chat_name, chat_password, date_created, userid) values ('$chat_name', '$chat_password', NOW(), '".$_SESSION['id']."')");
$cid=mysqli_insert_id($conn);
mysqli_query($conn,"insert into chat_member (chatroomid, userid) values ('$cid', '".$_SESSION['id']."')");
echo $cid;
}
this is jquery code
$(document).on('click', '#addchatroom', function(){
chatname=$('#chat_name').val();
chatpass=$('#chat_password').val();
$.ajax({
url:"add_chatroom.php",
method:"POST",
data:{
chatname: chatname,
chatpass: chatpass,
},
success:function(data){
window.location.href='chat.php';
}
});
});
When I enter a duplicate data the alert in echo don't execute but it continue to put in database although it is duplicate. THANKS FOR THE HELP !
First thing, I would change
if(mysqli_affected_rows($query) == 1){
to
if(mysqli_affected_rows($query) >= 1){
this will make sure that even if there are already duplicates, no more duplicates can be added
There are however some bigger issues with the code that you should address
You should add a uniqueness constraint on your chatname (in the database). This will make it that even if your code is wrong, you will not be able to add duplicate entries to your table.
You are receiving user input and just adding it into your sql querys. This leaves your database open to SQL injection which basically means, anyone can do anything to your database (delete things, add things, etc.). You should look into prepared statements to solve this issue
I am making a project which is a website. Basically it will set a reminder and notify the user using email/SMS. I am using PHP and JavaScript. My database stores the the list of users in table 1 and a separate table for each user and his tasks(with the time and dates). I want to refer the database every minute to check for tasks even if the user is not logged in(browser is closed). What do i do to keep running the check for query all the time?
I want something that will run in background all the time even if user never opens the browser.
Please help.
The php code to store in a users database is
<?php
include("init.php");
session_start();
if(isset($_POST))
{
$date = $_POST["date"];
$event = $_POST["event"];
$time = $_POST["time"];
$daily = $_POST["daily"];
$weekly = $_POST["weekly"];
$monthly = $_POST["monthly"];
$fname = $_SESSION['fname'];
$fname = mysql_real_escape_string($fname);
$sql = "insert into $fname(fname,date,event,time,daily,weekly,monthly) values('$fname','$date','$event','$time','$daily','$weekly','$monthly')";
if(mysqli_multi_query($con,$sql))
echo "<br><h3> row inserted...</h3>done";
else
echo "Error in insertion...".mysqli_error($con);
}
?>
There is no issue with the code.
I just need to know how and using what can i refer the database all the time at the server end when user is not on the page.
Can php work 24hrs even if the browser is closed because i know javascript wont work.
You need to create an event in MySQL (or the database manager you are using, for example:
CREATE EVENT e_totals
-> ON SCHEDULE AT '2006-02-10 23:59:00'
-> DO INSERT INTO test.totals VALUES (NOW());
Or a recurrent event:
delimiter |
CREATE EVENT e_daily
ON SCHEDULE
EVERY 1 DAY
COMMENT 'Saves total number of sessions then clears the table each day'
DO
BEGIN
INSERT INTO site_activity.totals (time, total)
SELECT CURRENT_TIMESTAMP, COUNT(*)
FROM site_activity.sessions;
DELETE FROM site_activity.sessions;
END |
delimiter ;
Sagar what you are looking for is CRON Task. I am afraid that PHP and Javascript alone can't trigger it.
Work flow:
Make an API containing all your business logic or processing you need to execute it.
Register a CRON job in cPanel or crontab -e in your linux machine.
Use the end point directly using AJAX calls or make a separate end point as cron task will continue working.
Refer to this link in case you want to learn more about cron jobs - http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples
Thanks,
Abhishek Jain
To illustrate my problem description, there is a list to which one or more tasks can be attached.
when user tries to delete the list, a php code would check mysql 'tasks' table to see if there is any task(s) attached to the list being deleted.
if there is/are task(s), user would be prompted a popup, saying that deleting the list would also delete all the attached tasks, asking for confirmation for the same.
on OK, would proceed and delete all tasks, then delete the list .... on Cancel, would do nothing.
I have devised thing as below,
<?php
try
{
$list_id = $_GET['id'];
//Instantiate Database object
$database = new Database;
//check if task exist for the list to be deleted
$database->query('SELECT * FROM tasks WHERE list_id = :id');
$database->bind(':id',$list_id);
$database->single();
$rc = $database->rowCount();
if($rc > 0)
{
?>
<script type="text/javascript">
if(confirm('The list has one or more task attached to it. Deleting the list will also delete the attached tasks. Do you want to proceed ?'))
{
//prepare and execute delete tasks
$database->query('DELETE FROM tasks WHERE list_id = :id');
$database->bind(':id',$list_id);
$database->execute();
//prepare and execute delete lists
$database->query('DELETE FROM lists WHERE id = :id');
$database->bind(':id',$list_id);
$database->execute();
if($database->rowCount() > 0)
{
header("Location:index.php?msg=listdeleted");
}
}
</script>
<?php
}
}
catch(Exception $e)
{
echo '<p>'.$e->getMessage().'</p>';
}
?>
The problem is that - The code does nothing. No error. Simply nothing.
I did some googling and found out that most people are suggesting ajax call to do that. I do not know ajax. So, to do this tiny bit of thing, I would have to devote some considerable amount of time now. So, I need the following 2 things -
Could you people please confirm me if ajax is the only possible solution here? I would only go to ajax if no other way left to execute php as shown above
From the code I pasted above, can anyone suggest any better approach to what I am trying to accomplish?
Either
a) learn to use ajax, as it is the most obvious solution. Once you have learned it you will find it invaluable
or, if you really haven't the time
b) use your JS 'confirm' to redirect the user to a new PHP page, passing the ID of the record that you want to delete in the URL of the page redirect. On that new PHP page, process your delete and then use a PHP redirect to bring the user back to your original page.
Go for option (a)...
Yes, as the guys said, ajax will be one nice way to do this.
The confirm alert it's working?
Inside of your js function, you can't put the php code without the "< ? php..?>" between then as you did.
I am needing a little help with updating a mysql table from data in an jquery array using ajax. I have tried searching for similar issues but could not find anything, or maybe I do not know the correct terms to search... I'm still fairly new to web dev/coding.
I'll try explain what I am trying to do as clearly as I can. I have a page with seats which users select by clicking on them, upon clicking the seat ID is added in its own span tag in a kind of shopping cart area on the left of the page. This works fine.
Upon checkout my js file is able to pick up these seat ID's in an array, but from here I am unsure of how to properly send this array to the php file, and then for the php file to read the seat ID's from the array and update the relevant seat rows to change the availability from 1 to 0 (this is using ajax).
Here is my code:
checkout.js
$(document).ready(function(){
$('#checkout').click(function(){
var status = sessionStorage.getItem("username");
if(sessionStorage.getItem("username")){
var tickets = [];
$("#myTickets").find("span").each(function(){ tickets.push(this.id); });
var type = "POST",
url = "scripts/sendSeatDetails.php";
console.log(tickets);
$.ajax ({
url:url,
type:type,
data:tickets,
success: function(response){
if(response == 5){
alert("Seat update query failed");
} else {
alert("success");
}
}
});
} else {
alert("Before purchasing please log in. If you do not have an account please register.");
}
});
});
In the console log this shows: ["A2", "A3", "A4"] (if I have selected seats with ID A2, A3, A4 etc).
sendSeatDetails.php
<?php
include("dbconnect.php");
$myseats=$_POST['tickets'];
$query="update seats set status='0' where seatnum=";
for($i=0;$i<count($myseats);$i++){
$query.="'$myseats[$i]'";
if($i<count($myseats)-1){
$query.=" || seatnum=";
}
}
$link = mysql_query($query);
if (!$link) {
echo 5;
}
?>
This returns the alert showing success, but this is not true as the tables are not being updated. Can anyone help me with this or point me in the right direction?
I appreciate your help, and hopefully will be able to contribute to this site when I am at a better skill level in the future.
Many Thanks.
To send an array in jQuery you have to serialize it then parse it in the PHP file:
data: tickets.serialize(),
...
parse_str($_POST['data'], $data);
And then you treat it as an ordinary array.
Run update query one by one.
$myseats=$_POST['tickets'];
$flag=0;// Total successful updates
$myseats=explode(',',$myseats);
for($i=0;$i<count($myseats);$i++){
$query="update seats set status=0 where seatnum='".$myseats[$i]."'";
$link = mysql_query($query);
if (!$link) {
$flag=$flag+1;
}
}
echo $flag;die;
Check response. it will be number of updated rows.
I have a rather simple DHTMLX page that I'm working on. I managed to load data from a database and display it in a DHTMLXGrid. However, when I change data in the grid, the data is not saved to the database and is therefore lost when the page is reloaded.
The database in question is three tables: users, shows and watching. watching is the only one that needs updating (right now at least) and I just can't seem to get it to work.
This is my "connector.php" file
<?php
require("codebase/connector/grid_connector.php");
require("codebase/connector/db_mysqli.php");
$servername = "nope";
$username = "nope";
$password = "nope";
$databaseName = "nope";
$conn = new mysqli($servername, $username, $password,$databaseName);
$query = "SELECT watching.user_ID, watching.show_ID,shows.name, watching.episodeswatched, shows.episodes, (shows.episodes - watching.episodeswatched) AS episodesremaining, watching.dropped, watching.waiting FROM watching INNER JOIN shows ON watching.show_ID = shows.ID INNER JOIN users ON watching.user_ID=users.ID";
$gridConnector = new GridConnector($conn, "MySQLi");
if($gridConnector->is_select_mode())
$gridConnector->render_complex_sql($query,"ID","name,episodeswatched,episodes,episodesremaining,dropped,waiting","user_ID,show_ID");
else
{
$gridConnector->render_table("watching","ID", "episodeswatched,dropped,waiting","user_ID,show_ID");
}
?>
And the relevant parts of the Javascript to make the processor and DHTMLXGrid
showsGrid.init();
showsGrid.load("connector.php");
var myDP = new dataProcessor("connector.php")
myDP.enableDataNames(true);
myDP.init(showsGrid);
I tried using the same line for fetching data and updating (render_complex_sqlquery) but that does nothing but paint the row in question red. At least with this method the row stays black.
Am I missing something? Am I doing something completely wrong? I've been completely stuck here for way too long and I'm admitting defeat. I've looked at every sample and tutorial I could find, scoured the documentation and found no help for this.
Forgot the GitHub link: https://github.com/lightspeed1001/dhtmlxdemo
You need to remove the "myDP.enableDataNames(true);" line
This command can be used with custom backend, but while you are using connector on server side you must use the default data sending mode.
I updated the connector.js and some other things, also messed with the names for the cells a bit and now it works.
You can view the diff on the github page for details.
Also, I needed to have datanames enabled, because of how many values I have and they aren't always in the same order when recieving and sending data.