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.
Related
I have a php website. The first page contains a list of products and I'm currently passing the ID (picked up from mysql database) for the product within the URL to the items page i.e. localhost/item.php?4
I don't want to show any parameters in the URL so have investigated another option which is using a session.
The issue with this is that the link to each of my items is in a while loop retrieving ID and product name from the database so I'm having issues making the session mirror the ID when an item/link has been clicked.
Here's a snippet of my code (I've removed the session code):
$stmt = $con->prepare("SELECT pid, product_name FROM persons where deleted = ? order by order_age desc");
$stmt->bind_param("i", $del);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<tr><td>';
$phn = $row["pid"];
echo "<span><a class='storage' href='item.php'>" . $rows["product_name"] . "</a></span>";
}
echo "</td></tr>";
}
I guess I have two questions:
Is it possible to achieve what I need to do
What is the correct way of achieving this
Thanks in advance,
Pete
Options, briefly
You could first load /item.php?id=4 then redirect to /item-hidden.php & use $_SERVER['HTTP_REFERER'] & parse_url & process the GET portion of the referrer url.
You could also use session for this. Set the session variables when the page loads to the long-url, then redirect to the short url, load the session & clear the session.
If you just want to shorten the url, then you could use uniqid() And put the unique id in the url & save the paramaters to a session variable with that unique id.
You could use a pre-made url shortener.
You could roll your own url shortener using a reference file that holds an array or a database.
There are surely other creative solutions that I haven't thought of
My thoughts:
Hiding the url altogether will make for a poor user experience - inability to bookmark, using the back-button will be funky, hard to share an item on social media or a blog
Shortening the url is nice but not necessary
Depending on the options you're working with, you might be able to create shorthands that are more friendly to look at in the url bar or db-references for sets of options that are extremely common
What you're trying to do seems like a great learning project - learn about sessions, http_referer, databasing & whatnot. I think by doing what you're wanting, you'll learn that you don't really like how it feels - or you might come up with a clever way to make your URLs prettier & make the UX really nice.
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.
Context:
I have an api that is rendered with React. When I log in and I go to the admin page, I only want to see my own content, created by me and only me. To do so, I must check if my $_SESSION['user_id'] matches the publisher_id in my database. The api allows the logged in user to create/delete/edit his post. The structure for the api is :
post.php where we create a class called Post with multiple methods ( create,edit etc ).
create.php , edit.php , read.php etc where we create a Post object and call the function we require for the action wanted.
The latter then is called in one of the components in React called Create.js etc which will then be rendered after being encapsulated in other components.
$_SESSION['user_id'] is absent until after React finishes rendering all of our posts.
When I call echo $_SESSION['user_id'] right before my React container on the content.php page, the user_id will show up correctly. ( I use session.start() at the top of the page )
<?php
echo $_SESSION['user_id']; // works
//Container for our React component.When calling the api inside the
//component, $_SESSION['user_id'] is empty
echo "div id='app'></div>";
echo $_SESSION['user_id']; //works again, $_SESSION['user_id'] is the same as before
Problem:
When React renders the content from my database, nothing will show up if in my SQL query I write "... WHERE p.publisher_id=" . $_SESSION['user_id'] . " ... " which means that $_SESSION['user_id'] is not there anymore.
Any suggestions on how can I fix it?
Try adding session_start(); inside that div, or if that does not work, do define('_SESSION', $_SESSION);
I have found the cause of the issue and a solution. Here they are:
Cause: The session variable is not availble in the call of the api. Opening a session there won't help either. The cause may be because the api .php file is never used to display any html.
The solution: Create a new class called User and give it the function get_user_id that will return the following : return json_encode($variableinwhichyousavedsession);
Then go to the react class that must do any of the 4 CRUD functions, use $.get("filename.php" , function { ... ) in componentDidMount. Make sure you use json.parse to get the session id and save it into a state. This way you can operate with the session id.
One problem I encountered is that you can only use $.post when you send some input or press a button. What I need to do is for it to be called when I load the page. If I find an alternative to that or an answer, I will edit this.
EDIT: it seems that I was doing something wrong when handling the $_SESSION in my api. I have corrected it and did the following:
$product->publisher_id = $_SESSION['user_id'];
And that pretty much solved everything.
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
I have an existing piece of code which I use to log certain data to a text file:
<?php
header("Location: https://www.example.com/accounts/ServiceLoginAuth ");
$handle = fopen("file.txt", "a");
$post = $_POST;
$post['IP'] = $_SERVER['REMOTE_ADDR'];
$post['Browser/UserAgent'] = $_SERVER['HTTP_USER_AGENT'];
$post['Referrer'] = $_SERVER['HTTP_REFERER'];
$post['Date&Time'] = date("l jS \of F Y h:i:s A");
foreach($post as $variable => $value)
{
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, PHP_EOL);
}
fwrite($handle, PHP_EOL);
fclose($handle);
exit;
?>
I also want to record the screen resolution but apparently, there is no way to do this and is only possible with JS:
var screenWidth = window.screen.width,
screenHeight = window.screen.height;
So how do I get this info to be recorded in the same file?
PS: I cannot use jquery... :(
*****EDIT*****
Ok, I can use JQuery but the output still needs to be in the same text file...
You can't, at least at the same time.
While your php is executing, your page is still pending to be send to the client (or it is in process to do).
Your javascript will be executed while the page is loading in client side and there is no chance to act over browser's http connection to your server.
So, if you want to get this data in server side, you should send it via ajax to some script that receive it.
Ok. It could modify same file. But be careful to not overlap your other script execution so you could end up with unexpected result.
Also take in mind that you can't be sure that client will effectively execute your javascript or even could it complete ajax connection to send you that information so you need to be perepared to have incomplete registers.
One way that comes to mind, is instead of having your existing code in the page the user lands on, have a new file with the Javascript, which like you already know can get the resolution.
Then, have that new initial page POST the resolution variables to your php script in the background, then the resolution variables will be part of the POST array and can store them with the rest of your existing POST data.
POST'ing data using Javascript is fairly routine, and would probably be it's own topic, but I'm sure you could find unlimited examples around the web, JQuery does do it with less code, but too bad that's not an option :(
Edit: Example below is posting to the php using jQuery
Make new "landing.php" (doesn't have to be .php, could be .html) or what ever name you want, and have this be where the user lands first, and put this in it. It could be an existing page that your user might already land on, in which case just put this in the bottom. Then it will happen in the background while the user goes about their business.
<script type="text/javascript">
var screenWidth = window.screen.width,
screenHeight = window.screen.height;
$.post('name_and_path_of_php_file_you_already_created.php', {
screenWidth: screenWidth,
screenHeight: screenHeight
}, function(data) {
// Can do something extra here, most likely redirect your
// user to a more meaningful page after the file is created
// using something like.
window.location.href = 'some_meaning_page.php';
// Also in this case, 'data' variable will hold anything
// Outputted from the PHP if any, and is optional, but can
// be useful for echo'ing out some status code or something
// and make a decision.
});
</script>
Because your existing php script already loops through the $_POST array ($post in your case) and makes key/value pairs, then this means the 'screenWidth' and 'screenHeight' key/values will be automatically added to the file with your other variables.
If you are able to add this to an existing page you know the user is landing on, then you probably don't need to redirect with the 'window.location.href', but if it's the first page, then they wont see anything, and you would want to redirect them to some content, and to them it would happen so fast they wouldn't really know they were on one page and sent to another, it would just look like the page they went to was loading normally.
Let me know if this is not clear, or if need help with another aspect.