I am trying to get an AJAX query to work. Im passing data to a PHP script using:
$(".example").click(function(){
x = this.innerHTML;
$("#example").load("ajax.php",{"data":x});
});
If ajax.php just includes the following (did this as a test), everything is fine; I've passed JS data successfully to PHP.
echo $_POST['data'];
My goal is to query my DB using $_POST['data'] though. As another test, I made sure the DB connection was all ok. The following works:
$example = $dbc->prepare("SELECT x, y, z, a FROM clue WHERE userID=?");
$example->bind_param('s',$_SESSION['user_id']);
$example->execute();
$example->bind_result($x,$y,$z,$a);
while($example->fetch()){
echo '<h3>'.$x.'</h3>';
echo '<p>'.$y.'</p>';
echo '<p>'.$z.'</p>';
echo '<p>'.$a.'</p>';
}
When I amend the below lines however, nothing is returned from the script.
$example = $dbc->prepare("SELECT x, y, z, a FROM clue WHERE userID=? AND a=?");
$example->bind_param('ss',$_SESSION['user_id'],$_POST['data']);
The puzzling thing is that the data being passed from JS initially was obtained from the database. When I use alerts, the words are exactly the same as my my DB record.
Any suggestions? Could this be something to do with datatype? do I need to make sure $_POST['data'] is converted to a string somehow?
When I look in firebug, I see the following POST details ('Test Title' is the data used in my query)
Parameters
data Test Title
Source
data=+Test+Title
Do the + signs represent spaces? perhaps I need to trim a space from beginning of data?
This was due to white space. Fixed with the following:
$(".example").click(function(){
y = this.innerHTML;
x = y.trim();
$("#example").load("ajax.php",{"data":x});
});
Related
I have a conundrum that appears to defy logic, involving Lumen, PHP, PDO, and SQL Server.
I have a controller which contains an action, that executes a stored procedure on a QL Server instance before returning the results as a JSON string. Nothing special is happening but for certain parameters, I do not get any response.
Right, some code. Here's the PHP/PDO prepared statement.
// Prepare our query.
$query = $pdo->prepare("
EXEC [dbase].[dbo].[myStoredProc]
#A = :A,
#B = :B,
#C = :C,
#D = :D,
#E = :E,
#F = :F,
#G = :G
");
// Bind the parameters and execute the query.
$query->bindParam(':A', $A);
$query->bindParam(':B', $B);
$query->bindParam(':C', $C);
$query->bindParam(':D', $D);
$query->bindParam(':E', $E);
$query->bindParam(':F', $F);
$query->bindParam(':G', $G);
$query->execute();
// Uncomment the following line for debugging purposes.
$query->debugDumpParams();
// Lets get all of the data.
$data = $query->fetchAll(\PDO::FETCH_ASSOC);
print_r($data);
Perfectly normal as I said. If I use POSTMAN and pass in the parameters as follows:
A 'C_ICPMS_06'
B 'AQC1'
C '726'
D NULL
E '2021-08-30 00:00:00'
F '2021-11-30 23:59:59'
G NULL
I get a list of results as expected, both from POSTMAN and PHP as well as through SSMS (using the output from the debug statement).
Now if I change parameter C from '726' to '728', I do not get any output from POSTMAN and PHP, but still, get output from SSMS.
Thinking that there could be some text within the output that is breaking the FETCHALL function, I amended the stored procedure to return a single record, all columns containing 1's. Once more the parameter of 726 works, 728 does not.
I added a VAR_DUMP command to ensure that the parameter isn't being molested on its way to the controller, both parameter values report that they are strings with 3 characters in length.
if I change the prepared statement as below, I still don't get any results seen within POSTMAN/PHP.
// Bind the parameters and execute the query.
$query->bindParam(':A', $A);
$query->bindParam(':B', $B);
//$query->bindParam(':C', $C);
$query->bindValue(':C', '728');
$query->bindParam(':D', $D);
$query->bindParam(':E', $E);
$query->bindParam(':F', $F);
$query->bindParam(':G', $G);
$query->execute();
The debug SQL statement is identical to before (using the param as opposed to value).
If I change the stored procedure, such that regardless of what value is passed in for parameter C, it is hardcoded to 728, it works as intended (obviously it does not matter what the parameter is set within POSTMAN). So I get values within POSTMAN and SSMS, therefore, it is safe to assume that the whole problem is being caused by the parameter and value '728'.
Further digging at this issue, I find that if the parameter has a value of '72F' or '70W', also returns no results via POSTMAN/PHP but does from within SSMS. I've checked and cannot see any error messages being produced.
I added the below lines to the controller to see if I can see an issue, but nothing was seen (not on screen nor within error files).
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
In trying to figure this out, I created a temporary database table in order to capture the input parameters and the number of records as found within the SP. This should show where the problem lies, i.e. within PHP or within SQL Server. It now gets stranger.
Calling the SP from within SSMS, it populates with an expected record, including the number of records the initial search returned. However, calling it from POSTMAN using the controller, everything is the same in terms of parameters, but the number of records found is 0!
So I know something very weird is going on, but cannot put my finger on what and therefore how to fix it. If anyone has any ideas or has come across a similar problem, please let me know. this is bugging me now. No doubt when I get this working, it'll be a silly error and I'll end up kicking myself.
The issue was that a temporary table that was being created couldn't hold a specific value being assigned to it. The column was designated as a TINYINT but should have been a SMALLINT since the value could go negative.
Why SSMS never reported that as an issue and happily allowed it through, God only knows. But when called externally, it failed to insert any records within the temporary table, returning no records as a result.
There go 1.5 days of my life never to be seen again.
Please can somebody be so kind to show me the syntax for using cloneblock in phpword.
So Ive got data in a MySQL DB, and for the single rows that I need to import into my word doc via phpword it works fine....to run my query and search and replace with template processor. BUT, now I want to insert multiple rows into my word document. I've researched and found that the cloneblock method is the answer. However I cannot get it working....currently my code runs but it doesn't seem to get to the second row.
I actually dnt get any error messages. My code executes fine...but the end display word file doesn't display fine....and if you see my code I got an echo statement...which echo's out in my browser exactly what I want "damaged" &"good", (as an example given of one of the row data) but that data doesn't get pulled into my word doc like that...it duplicates "damaged" , "damaged". .
$group_key=1;
do {
//loop to increase my uuid - ($repeatgroup')
$repeatgroup = $id."/"."trailer_repeat_group"."[".$group_key."]";
// query string
$trailer_repeat_grouping = mysqli_query($connect, "SELECT * FROM trailer_repeat_group LEFT JOIN main on trailer_repeat_group.PARENT_KEY = main.metainstanceID WHERE trailer_repeat_group.KEY_id = '$repeatgroup'");
$templateProcessor->cloneBlock('CLONEME', $trailer_count);
while ($row1 = mysqli_fetch_array($trailer_repeat_grouping)) {
//this echo below I am using to test exactly what happends – independent of
//PHPword/templateprocessor
echo $rttc = $row1['right_trailer_tyre_condition'];
//inserting / searching / inserting values
$templateProcessor->setValue("right_trailer_tyre_condition", $rttc);
}
// ending of loop / checking loop
$group_key++;
} while ($group_key <= $trailer_count);
I've done investigation and found the solution.
You're cloning same blocks N times:
$templateProcessor->cloneBlock('CLONEME', $trailer_count);
and then by doing fetch You're trying to replace right_trailer_tyre_condition with some value:
$templateProcessor->setValue("right_trailer_tyre_condition", $rttc);
Issue is that You're replacing all placeholders.
But in fact You need to replace them one by one with different values.
Solution is to define 3rd argument that means count of items to replace.
Simply change it to be:
$templateProcessor->setValue("right_trailer_tyre_condition", $rttc, 1);
I have a bunch of R scripts that do some calculations and return a result. I am planning of building a PHP website that the user can actually submit a form where the data gets passed to my R script, processed and then return the result to the PHP and update the interface.
The plan is to have a database so when a user submits a form, the data gets stored in the database so R can read, process the input and then insert the result in the database so PHP can grab it. However, there are 2 problems:
How do my R script knows that certain values have been stored in the database so it can grab those values and do the processing?
When my R script finishes processing the data and insert it to mysql db, how do I get PHP to understand that at this moment PHP needs to query the database and grab the value?
Let's say my R script is like the following:
range<-1:20
m<-mean(range)
s<-sum(range)
print(m)
print(s)
As you can see the input at this case would be 1 and 20 to define the range, and the output is to show the values of m and s on my webpage.
Any idea how to accomplish that?
thanks!
shell_exec() or exec() are likely your best choices in PHP. This answer explains the difference.
echo shell_exec("Rscript my_script.R {$_GET['range']}");
I'm no r expert, but it's been done :
/ poorman.php
echo "
";
echo "Number values to generate:
";
echo "Submit";
echo ""
;
if(isset($_GET['N']))
{
$N = $_GET['N'];
// execute R script from shell
// this will save a plot at temp.png to the filesystem
exec("Rscript my_rscript.R $N");
// return image tag
$nocache = rand();
echo("");
}
?>
and the R script…
my_rscript.R
args <- commandArgs(TRUE)
N <- args[1]
x <- rnorm(N,0,1)
png(filename="temp.png", width=500, height=500)
hist(x, col="lightblue")
dev.off()
source
Trying to make a little Search feature for a user, so he can type in a date on a webpage made with HTML/PHP, and see which people in the db have registered as member on or after (a date). My user inputs the date in format 2015-10-01. This gets sent to a PHP page with a jqxGrid on it, populated with member details of members conforming to my query on the MySQL database (using PDO).
The query uses the operator >= on a string passed as (for example) "2015-10-01" in the WHERE clause, so I am using STR_TO_DATE to make the comparison work:
WHERE `lastUpdated` >= STR_TO_DATE( ? , '%Y-%m-%d');
With PDO, the ? later gets bound to the date (which was passed in as a string).
The db column for registration date is in DATETIME format, and in the db values look like: "2015-10-12 17:12:52".
My query returns an empty array every time, - and this after many hours of trying every conceivable permutation of date format, both in the MySQL statement and on the page that prepares the data for populating the grid.
Can someone show me what's wrong here?
Thanks!!
SP
Make it
WHERE `lastUpdated` > ?
and check your data and stuff.
Basically, you should never touch PDO until you get raw SQL to work.
okay, so here is the PDO version that works - passing in ? instead of the date:
function getJSONAllMembersByDate($PDOdbObject, $regDate)
{
try
{
$membersByDateSQL = "SELECT `id`, `name_first`, `name_last`, `organization`,`email`, `phone`,`source`,`comments`,`language_id`, `lastUpdated` FROM `member` WHERE lastUpdated>=?";//'$regDate'
$get=$PDOdbObject->prepare($membersByDateSQL);
$get->execute(array($regDate));
$rows = $get->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($rows);
return $json;
}
The fact that it works proves there were other errors in the file containing the jqxwidget (the version before I posted here). I certainly tried about a million different things to get this working.
I don't know if this counts as an answer, but at least it WORKS! There are so many variables in this problem - json, jqxgrid, pdo ... not forgetting that there are several ways to use PDO. I probably had several errors in different places.
(#apokryfos, the STR_TO_DATE was indeed unnecessary.)
In the end, this is what works:
In the PHP page containing the jqxGrid, the url sent to the server is:
url: 'my-json-responses.php?fct=getJSONAllMembersByDate®Date=<?php echo $fromDate ?>'
This $fromDate comes from the $_POST when the user typed in a date (in the format 2015-10-01) on the input page. When the PHP page containing the jqxGrid loads, it does
$fromDate = $_POST['regDate'];
The url "transits" through the file my-json-reponses.php, which contains many functions. It finds the right one:
if ($_GET['fct'] == 'getJSONAllMembersByDate')
{
$result = getJSONAllMembersByDate($connectionObject, $_GET['regDate']);
echo $result;
}
The $result is called on the file that contains all my PDO database requests, including:
function getJSONAllMembersByDate($PDOdbObject, $regDate) { try
{
$membersByDateSQL = "SELECT `id`, `name_first`, `name_last`, `organization`,`email`, `phone`,`source`,`comments`,`language_id`, `lastUpdated` FROM `member` WHERE lastUpdated>='$regDate'";
$get=$PDOdbObject->query($membersByDateSQL);
$rows = $get->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($rows);
return $json;
}
catch (PDOException $e)
{
echo "There was a problem getting all members with this search query.";
echo $e->getMessage();
}}
Note that I couldn't make the version using "?" in the query work at all, hence passing in the variable $regDate directly, with single quotes around the variable just to make life interesting.
This returns a nice list of all my users as of 2015-10-01 - but is presumably still open to MySQL injection attacks ...
But after this marathon of debugging I am happy enough for now. (All improvements welcomed, naturally!)
SP
I'm building a script using PHP and MySQL to compare a certain live page against older versions of it - i'm doing it by md5 hashing it and comparing it to the latest version.
Now i'm trying to pull the latest known hash of a certain page using the following:
SELECT latest_hash FROM tracked_sites WHERE domain = 'domain.com
Which shows me the actual contant of latest_hash for a certain "domain.com"
Now i'm trying to put it in a valid variable so i can compare it using the following:
$latestmd5_sql=(mysqli_query($con,"SELECT latest_hash FROM tracked_sites WHERE domain = 'domain.com'"));
Now, thinking i have the actual content of the database i'm trying to compare it with
if ((md5(file_get_contents("https://domain.com/page.html")))==$latestmd5_sql)
BUT, for some reason i get False as answer.
I've tried to print out the $latestmd5_sql var using echo or print_r but it seems to be empty or empty array, i'm a bit puzzled as to what i'm doing wrong and would love to get ideas.
In your provided code, $latestmd5_sql will be a resource, not the value in the database.
You'll need to "fetch" the data from the resource in order to compare values.
Here's an example to illustrate the workflow from sql code to php variable:
// your sql
$sql="SELECT latest_hash FROM tracked_sites WHERE domain = 'domain.com'";
// the query (returns a resource)
$query = mysqli_query($con,$sql);
// fetch the resulting data (this is the part you're missing)
$result=mysqli_fetch_assoc($query);
// take a look at the data (for debugging purposes)
echo"DATA:<pre>".print_r($result,true)."</pre>";
// compare
if ((md5(file_get_contents("https://domain.com/page.html")))==$result['latest_hash']) {
echo"<p>Match</p>";
} else {
echo"<p>No Match</p>";
}