Jqgrid I can't update my changes into a database - php

My jqgrid loads perfectly data, but when I want to commit changes on it, nothing happens on my database.
I don't know exactly when happens the "enter key" event for saving the row, so I don't know where put this code:
jQuery("#lista").saveRow(id, function(){alert("changes saved")}, 'guardar_lista.php');
I already saw this example: JQgrid checkbox onclick update database
but I'm very hard headed about how to use ajax for send the info (sorry, I'm a newbie).
Can you give me a code example of how to send the info with ajax?
Here is my Editurl code:
<?
$dbhost="localhost";
$dbuser="root";
$dbpassword="";
$database="db_proyecto";
$db = mysql_connect($dbhost, $dbuser, $dbpassword) or die("Connection Error: " . mysql_error());
mysql_select_db($database, $db);
if($_POST['oper']=='edit'){
$invid=$_POST['id'];
$tax=$_POST['tax'];
$note=$_POST['note'];
$total=$_POST['total'];
$SQL="update invheader set note='"+$note+"' where invid="+$invid;
mysql_query($SQL,$db);
}
Thank you in advance #ruffin! (Sorry for the delay, I was very busy)

Well, you're going to have to post a little more code for us to know for sure. Your grid should have a value for your editurl, which is the page that's going to process your updated data (iirc). Just to be clear, that url is where you'd insert your mysql_query jive.
Note that you're either going to have jive coming in your $_GET or $_POST collection with the new values from the grid, with "_empty" for the id column if it's a new row (since it's not filled; this is a new row). (Yes, I realize you're updating, but just in case you add soon enough.)
Eg... ("FORM" each time means it's coming from the $_POST array)
FORM: PREFIX :: REV
FORM: FNAME :: Joe
FORM: MNAME :: Frazier
FORM: LNAME :: Test
FORM: SUFFIX :: suffix
FORM: oper :: add
FORM: id :: _empty
Decent code to review here:
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing
More on _empty and form editing here:
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:form_editing
So we need your editurl, we need to know that the "php code for update data" is IN that page, and we probably should see what you've got on the page with the grid in full to give a SUPER WONDERFUL answer. ;^)
You should probably also write up a dummy page at your editurl that iterates through all the values from your $_GET and $_POST collections and writes them to a file so that you can check what the grid is sending you -- and that you're getting anything at all. Also, please please PUH-lease use mysql_real_escape_string() around $name and at least an int check for $id!

Related

Passing function result into sqli

I'm new to this and I know I'm probably doing this entire thing the wrong way, but I've been at it all day trying to figure it out. I'm realizing there's a big difference between programming a real project of my own rather than just practicing small syntax-code online. So, I lack the experience on how to merge/pass different variables/scopes together. Understanding how to fit everything within the bigger picture is a completely different story for me. Thanks in advance.
What I'm trying to do, is to make the function "selectyacht" output data in a different location from where it's being called (in viewship.php). The output data (in viewship.php) needs to be only certain fields (not everything) returned and those results will be scattered all over the html page (not in a table). In addition to that, I have this variable: "$sqlstatement" (in sqlconn.php) that I'm trying to bring outside the function because I don't want to repeat the connection function every time. I tried a global variable, as much as I shouldn't, and it thankfully it gave me an error, which means I have to find a better way.
Basically my struggle is in understanding how I should structure this entire thing based on two factors:
To allow the second conditional statement in sqlconn.php to be typed
as least often as possible for different "selectyacht" functions
that will come in the future.
To allow the connection instance in sqlconn.php to reside outside the function since it will be used many times for different functions.
Returning data in a different place from where it's being called in viewship.php because the call will be a button press, not the results to be shown.
This is probably very simple, but yet it eludes me.
P.S. Some of this code is a copy/paste from other resources on the internet that I'm trying to merge with my own needs.
sqlconn.php
<?php
$servername = "XXXXXXXX";
$username = "XXXXXXXX";
$password = "XXXXXXXX";
$dbname = "XXXXXXXX";
// Instantiate the connection object
$dbconn = new mysqli($servername, $username, $password, $dbname);
// Check if the connection works or show an error
if ($dbconn->connect_error) {
die("Connection failed: " . $dbconn->connect_error);
}
// Create a query based on the ship's name
function selectyacht($shipname) {
global $sqlstatement;
$sqlstatement = "SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
}
// Put the sql statement inside the connection.
// Additional sql statements will be added in the future somehow from other functions
$query = $dbconn->query($sqlstatement);
// Return the data from the ship to be repeated as less as possible for each future function
if ($query->field_count > 0) {
while($data = $query->fetch_assoc()) {
return $data;
}
}
else {
echo "No data found";
}
// Close the connection
$dbconn->close();
?>
viewship.php
<html>
<body>
<?php include 'sqlconn.php';?>
<!-- ship being selected from different buttons -->
<?php selectyacht("Pelorus");?>
<br>
<!-- This is the output result -->
<?php echo $data["Designer"];?>
<?php echo $data["Length"];?>
<?php echo $data["Beam"];?>
<?php echo $data["Height"];?>
</body>
</html>
Mate, I am not sure if I can cover whole PHP coding standards in one answer but I will try to at least direct you.
First of all you need to learn about classes and object oriented programming. The subject itself could be a book but what you should research is autoloading which basically allows you to put your functions code in different files and let server to include these files when you call function used in one of these files. This way you will be able to split code responsible for database connection and for performing data operations (fetching/updating/deleting).
Second, drop mysqli and move to PDO (or even better to DBAL when you discover what Composer is). I know that Internet is full of examples based on mysqli but this method is just on it's way out and it is not coming back.
Next, use prepared statements - it's a security thing (read about SQL injection). Never, ever put external variables into query like this:
"SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
Anyone with mean intentions is able to put there string which will modify your query to do whatever he wants eg. erase your database completely. Using prepared statements in PDO your query would look like this:
$stmt = $this->pdo->prepare("SELECT * FROM ships WHERE Name = :ship_name");
$stmt->bindValue(':ship_name', $shipname);
Now to your structure - you should have DB class responsible only for database connection and Ships class where you would have your functions responsible eg. for fetching data. Than you would pass (inject) database connection as an argument to class containing you selectYacht function.
Look here for details how implementation looks like: Singleton alternative for PHP PDO
For
'Returning data in a different place from where it's being called'
If I understand you correctly you would like to have some field to input ship name and button to show its details after clicking into it. You have 2 options here:
standard form - you just create standard html form and submit it with button click redirecting it to itself (or other page). In file where you would like to show results you just use function selectYacht getting ship name from POST and passing it to function selectYacht and then just printing it's results (field by field in places you need them)
AJAX form - if you prefer doing it without reloading original page - sending field value representing ship name via AJAX to other page where you use selectYacht function and update page with Java Script

Using GET to register button click

I am trying to register a button click on my website using PHP.The click downloads a file to client's machine. Database connection was tested before and it works fine. I just need to register that click into DB. Here is my code, could you guide me through?
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
if(isset($_GET['dl']))
{
$server = "xx.xxx.xx.xxx";
$dbusername = "xxxx";
$dbpassword = "xxxx";
$database = "xxxx";
$dbcon = new mysqli($server,$dbusername,$dbpassword, $database);
$userid = $_SESSION['suserid'];
$date_downloaded = date('Y-m-d H:i:s');
$sql = "INSERT INTO external_activity (
userid,
saleid,
activity,
date_register,
) VALUES (
'".$userid."',
'".$ref_no."',
'".'Downloaded file'."',
'".$date_downloaded."'
)";
$dbcon->query($sql);
$dbcon->close();
}
If using jquery is an option, you could create a "register_click.php", paste the if(isset($_GET['dl'])) stuff inside and call it via ajax using an onclick listener that you will have to create and bind to the anchor.
You could do it with POST data instead of GET.
$i = 0;
if $_POST['submit'] {
$i++;
$number_of_times_clicked = $number_of_times_clicked_stored_into_database + $i;
}
After that restore the new value back into the database. If you really want the onclick you need javascript. PHP is unable to check when a button is clicked, since the code only works once when the page is loaded.
This is too long for a comment.
The & in your code might give you some problems, I said "might". If so, then consider changing those to & (ampersands).
Should it be the case, then you could change:
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
to:
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
Then you will need to check and see if each GET array is is set/not empty with isset() and !empty().
References:
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.empty.php
I only see if(isset($_GET['dl'])) as a single array, so it's unsure as to how you're wanting to fetch the other GET arrays in your URL and if you did set those.
Your present code (if it's the full code), will throw a few notices about certain variables not being defined.
For example, the if(isset($_GET['dl'])) and using the other GET arrays, would look like this:
if( isset($_GET['f']) && !empty($_GET['l']) && !empty($_GET['dl']) ){
// do something inside here
}
You also need to make sure that the session was indeed started with session_start(); and to be included inside all files using sessions.
Reference:
http://php.net/manual/en/function.session-start.php
This is usually the first line under the opening PHP tag.
<?php
session_start();
// rest of your code
The $userid = $_SESSION['suserid']; needs to have a value/equal something, so that is unknown as to whether or not there is indeed a value for it.
Error reporting will be of help here for you, as will checking for errors against your query.
References:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
You also have a trailing comma in date_register, < and that needs to be removed, as I already stated in comments.
That alone would have thrown a syntax error.
The use of '".'Downloaded file'."' is unclear. If you just want to insert the Downloaded file as a string, then you can just place it inside single quotes 'Downloaded file' and do:
$sql = "INSERT INTO external_activity (
userid,
saleid,
activity,
date_register
) VALUES (
'".$userid."',
'".$ref_no."',
'Downloaded file',
'".$date_downloaded."'
)";
Make sure that the date_register column type is DATE and not VARCHAR or other format. Although VARCHAR would not throw an error, it's best to use MySQL's built-in dating functions; that column's type is unknown.
Now, make sure that the userid column is not an AUTO_INCREMENT'ed column, otherwise your code will fail.
If the ultimate goal here is to "UPDATE" that userid column, then use just that, UPDATE:
http://dev.mysql.com/doc/refman/5.7/en/update.html
You also need to make sure that all columns' types are correct and have a length long enough to accomodate the incoming data and that there are no characters that MySQL will complain about, such as apostrophes.
Escaping those with a prepared statement will ensure that it doesn't throw/cause a syntax error and is something you should be using in order to help prevent against an SQL injection and you are open to one right now.
References:
https://en.wikipedia.org/wiki/Prepared_statement
https://en.wikipedia.org/wiki/SQL_injection
This is the best way that I can offer for the question, given the information left in the question.
Again; check for errors. That is one of the most important things that needs to be done during the development of your code.

Issues on using $.post to insert db data through PHP

So... I've been trying to use a JQuery post requests to insert data in my database for 2 days and can't make it work, and don't have any idea why... I bet someone already faced this issue too, so I'm here looking for this person :)
Here's the issue:
Into the html file, the part with JQuery (it's on a click event):
var eventData;
eventData = {
title: title,
start: start,
end: end
};
$.post("add.php", eventData);
The add.php file:
$con = mysqli_connect("localhost", "root", "", "jqcalendar" );
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
mysqli_query($con, "INSERT INTO jqcalendar(title,start,end) VALUES({$title},{$start},{$end})");
mysqli_close($con);
Can't make this thing work, already tried putting echoes but it seems the php file isn't even being executed by the $.post command... If someone could help I'd really really appreciate it...
EDIT:
the title, start and end are strings previously defined with the "" !
I used the console inspection and got this error at the same line as the
$.post:
$.fullCalendar.select # index.html:35
You have to use quotes when you are specifying the value in a javascript object (otherthan for numbers).
eventData = {
title: "title",
start: "start",
end: "end"
};
Tips
Also, you can see whether there's an error with your javascript part by inspecting element. Right click and click inspect/inspect element. Then go to the console. You will see errors there if there's any once you execute the javascript part.
Also when debugging javascript part, you can use console.log() to see the values of the variables
Figured it out, the problem is within the variables "start" and "end", they're composite date type ISO8601, what was causing trouble when received for inserting into database... thank you all for your time, but now the problem is converting this date object to a custom String...

Web Request through Maker Channel of IFTTT not sending any data

I have a simple IFTTT recipe that triggers whenever an instagram photo is posted with the hashtag #dog (used as an example since it triggers nearly every second and makes it easy to troubleshoot). This works fine. The associated action is with Maker to submit a GET call to a website as pictured below.
This then runs a very simple PHP script as below.
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$dump = $conn->real_escape_string(var_export($_GET, true));
$sql = sprintf("INSERT INTO table (dump) VALUES ('%s');", $dump);
echo $sql;
if ($conn->query($sql) !== TRUE) {
echo "#######Error: ". $conn->error ."#######<br/>";
}
$conn->close();
This should simply 'dump' the $GET array into the MySQL table. When I use the browser to run the PHP script such as
http://www.example.com?data=test&data2=testing
I get the correct response in the DB. However, when triggered through IFTTT I get an empty array.
I've tried all the options for Content Type and both POST and GET Methods but nothing is submitted either way. I have found a workaround by putting the GET call together in the URL field, BUT this isn't tidy and I figure it should work so want to understand the problem. Also, I'd like to POST rather the GET if possible.
I assume the problem to be with the Body and it not being formatted correctly, but I've tried every combination I can think of and what you see here is how the example on IFTTT is displayed.
Does anyone have any ideas or a known solution.
Thanks,
You need to embed the data in the URL itself like you mentioned. That is how GET requests work. If you want to keep it tidy and nor embed the data in the URL, you can use $_POST in your PHP script and then use the body section in IFTTT to embed the data, as seen in the screenshot.

setting enum value to 1 on link click?

can someone please help, i am trying to get the column 'privellages' (i know its spelt wrong) to update in my table 'ptb_permissions' when a link is clicked.
basically i've done this before for loads of other things and its worked fine its just this not working for some reason.
users are notified in their inbox when a user sends a request to view their pictures. and the user will have two links one to approve or one to delete the request.
if they click approve then this should update the enum colum 'privellages' from 0 to 1.
this is not working. im not getting any errors im just not getting anything happening. please can someone show me where im going wrong thanks.
Yes this is ok
contents of approve_priv_pix.php;
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
approve_pix ($_GET['picture'], $_SESSION['user_id']);
header("Location: {$_SERVER['HTTP_REFERER']}");
?>
mysql function:
function approve_pix($picture, $user) {
global $connection;
global $_SESSION;
$query = "UPDATE ptb_permissions
SET privellages='1'
WHERE id=$picture
AND to_user_id=$user";
mysql_query($query, $connection);
}
$_GET['picture'] should be $_GET['pix']
Also double check your privellages column enum values.
Yes this is ok
Here you have pix as a key, but in approve_priv_pix.php you are taking picture id from $_GET['picture']. Suppose it should be replaced with $_GET['pix']
Also, not sure why do you have <?php echo $pix['user_id']; ?> in link code. Possibly it should be something like <?php echo $pix['picture_id']; ?>
Additionally, you code is opened to sql injections. Here:
$query = "UPDATE ptb_permissions
SET privellages='1'
WHERE id=$picture
AND to_user_id=$user";
Instead of that you should better do:
$query = "UPDATE ptb_permissions
SET privellages='1'
WHERE id=" .mysql_real_escape_string($picture) . "
AND to_user_id=" .mysql_real_escape_string($user);
More details about mysql_real_escape_string. Take a look at warning message on top of that page. mysql extension is deprecated and will be remove soon. For new projects you should better use PDO or MySQLi extensions.
Another note: global $_SESSION; is not needed at all. It is accessible form any place in PHP by default.
im not getting any errors im just not getting anything happening
To see all errors you should set error_reporting to E_ALL (in your ini file or directly in code). With this option enabled you would see all notices/warnings/errors.

Categories