JQuery string not parsing correctly in PHP - php

In a previous post, I asked about how to deserialize a JQuery string, and was told to use parse_str(). However, I didn't post my code until later. So, here is my JQuery string:
age_gender=1&age_gender=2&age_gender=3&age_gender=4&age_gender=5&age_gender=6
And here is my PHP code:
if(isset($_POST['age_gender'])) {
$formSerialized = $_POST['age_gender'];
$formData = array();
parse_str($formSerialized, $formData);
addRow($formData, $link);
}
function addRow($dataArray, $link) {
$age_group = $dataArray[0];
$populations = array(intval($dataArray[1]) + intval($dataArray[2]), intval($dataArray[1]), intval($dataArray[2]));
$percents = array(doubleval($dataArray[3]) + doubleval($dataArray[4]), doubleval($dataArray[3]), doubleval($dataArray[4]));
$m_per_100_f = doubleval($dataArray[6]);
$query = "INSERT INTO national_age_gender_demographics (age_group, both_pop, male_pop, female_pop, both_percent, male_percent, female_percent, males_per_100_females)
VALUES ('$age_group','$populations[0]','$populations[1]','$populations[2]','$percents[0]','$percents[1]','$percents[2]','$m_per_100_f')";
$result = mysqli_query($link,$query);
if(!$result) die( "Query: " . $query . "\nError:" . mysql_error() );
}
For some reason, I am getting a blank string for $age_group, and 0's for all other values. Could anyone help me here?

Try to pass the data like this instead:
age_gender[]=1&age_gender[]=2&age_gender[]=3&age_gender[]=4&age_gender[]=5&age_gender[]=6
note the '[]' after the name, if they come from html input you would just have to name your html input age_gender[].
Then you function addRow should look like:
function addRow($dataArray, $link) {
$dataArray = $dataArray['age_gender'];//Added this line
$age_group = $dataArray[0];
$populations = array(intval($dataArray[1]) + intval($dataArray[2]), intval($dataArray[1]), intval($dataArray[2]));
$percents = array(doubleval($dataArray[3]) + doubleval($dataArray[4]), doubleval($dataArray[3]), doubleval($dataArray[4]));
$m_per_100_f = doubleval($dataArray[6]);
$query = "INSERT INTO national_age_gender_demographics (age_group, both_pop, male_pop, female_pop, both_percent, male_percent, female_percent, males_per_100_females)
VALUES ('$age_group','$populations[0]','$populations[1]','$populations[2]','$percents[0]','$percents[1]','$percents[2]','$m_per_100_f')";
$result = mysqli_query($link,$query);
if(!$result) die( "Query: " . $query . "\nError:" . mysql_error() );
}

You can try encoding with Json, this is a good solution
$.stringfy(your_var);
and to read with php use json_decode

Related

function in PHP not returning result

I have a simple data retrieval PHP file from Mysql and encodes in JSON string. The code below returns the result as expected
<?php
require 'dbconnection.php';
$tablename = $_GET["tabname"];
$sql = "SELECT * FROM ". $tablename ;
if (!mysqli_query($conn,$sql))
{
echo("Error description: " . mysqli_error($con));
} else {
$res = mysqli_query($conn,$sql);
}
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('_id'=>$row[0],
'course_name'=>$row[1],
'address'=>$row[2],
'city'=>$row[3],
'state'=>$row[4],
'zipcode'=>$row[5],
'phone'=>$row[6]));
}
echo json_encode(array("result"=>$result));
$conn->close();
?>
Sample Result...
{"result":[{"_id":"1","course_name":"Quail Valley","address":"12565 NW Aerts Rd.","city":"Banks","state":"OR","zipcode":"97106","phone":"5033244444"},...]}
My goal is to use the variable that was passed to PHP and based on it's name call function. I can't seem to figure out what I'm doing wrong!
<?php
require 'dbconnection.php';
$tablename = $_GET["tabname"];
function Course() {
$sql = "SELECT * FROM ". $tablename ;
if (!mysqli_query($conn,$sql))
{
echo("Error description: " . mysqli_error($conn));
} else {
$res = mysqli_query($conn,$sql);
}
$results = array();
while($row = mysqli_fetch_array($res)){
array_push($results,
array('_id'=>$row[0],
'course_name'=>$row[1],
'address'=>$row[2],
'city'=>$row[3],
'state'=>$row[4],
'zipcode'=>$row[5],
'phone'=>$row[6]));
}
return $results;
}
$result = call_user_func(Course());
// OR... $result = call_user_func($tablename());
echo json_encode(array("result"=>$result));
$conn->close();
?>
Here is the output...
Error description: {"result":null}
As you can see in the doc of php.net http://php.net/manual/fr/function.call-user-func.php
The function accepts a string as a parameter (see the examples).
So it should be call_user_func('Course')
Preferred way is directly go for:-
$result = Course();
But if you want to use call_user_func() then use like below:-
$result = call_user_func('Course');
It's because it take a callback as a string :-call_user_func

PHP MySql PDO Multiple insert doesn't work

I have this code for a multiple insert query (I have to transfer data from db to another and makes some update, so I wanna use a code that could do all this automatically)
$query = "select * from pubblicate order by idPubblicate asc";
$dbh = newPdo2();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query);
$sth->execute();
$count = 0;
$query2 = "insert into published_offer
(codice_onshop,nome,inbreve,anteprima,
galleria1,galleria2,galleria3,galleria4,prezzo,
tp_prezzo,bonus_usabile,proposta,condizioni,
prenotare,categoria,description,keywords,
valido_da,valido_a) ";
while($offerta = $sth->fetch(PDO::FETCH_ASSOC)) {
$array[$count]['id'] = $offerta['idPubblicate'];
$array[$count]['co'] = $offerta['codiceOfferta'];
$array[$count]['no'] = $offerta['nomeOfferta'];
$array[$count]['ib'] = $offerta['inBreve'];
$array[$count]['ke'] = $offerta['keywords'];
$array[$count]['de'] = $offerta['description'];
$array[$count]['pr'] = $pfferta['prezzo'];
$array[$count]['pe'] = $offerta['persona'];
$array[$count]['da'] = $offerta['daTimer'];
$array[$count]['a'] = $offerta['aTimer'];
$array[$count]['an'] = $offerta['anteprima'];
$array[$count]['g1'] = $offerta['galleria1'];
$array[$count]['g2'] = $offerta['galleria2'];
$array[$count]['g3'] = $offerta['galleria3'];
$array[$count]['g4'] = $offerta['galleria4'];
$array[$count]['pro'] = $offerta['proposta'];
$array[$count]['con'] = $offerta['condizioni'];
$array[$count]['pre'] = $offerta['prenotare'];
$array[$count]['bo'] = 999;
if($offerta['italia']=="Sì") $array[$count]['ca'] = "ita";
else if($offerta['europa']=="Sì") $array[$count]['ca'] = "eur";
else if($offerta['mondo']=="Sì") $array[$count]['ca'] = "mon";
$count++;
}
$query2 .= "values (:co,:no,:ib,:an,:g1,:g2,
:g3,:g4,:pr,:pe,:bo,:pro,:con,
:pre,:ca,:de,:ke,:da,:a)";
$dbh = newPdo();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query2);
$i=0;
echo $array[0]['no'] . " " . count($array) . " " . $array[125]['no'] . "<br>" . $query2 . "<br>";
while($i<count($array)) {
$sth->bindParam(":co", $array[$i]['co']);
$sth->bindParam(":no", $array[$i]['no']);
$sth->bindParam(":ib", $array[$i]['ib']);
$sth->bindParam(":an", $array[$i]['an']);
$sth->bindParam(":g1", $array[$i]['g1']);
$sth->bindParam(":g2", $array[$i]['g2']);
$sth->bindParam(":g3", $array[$i]['g3']);
$sth->bindParam(":g4", $array[$i]['g4']);
$sth->bindParam(":pr", $array[$i]['pr']);
$sth->bindParam(":pe", $array[$i]['pe']);
$sth->bindParam(":bo", $array[$i]['bo']);
$sth->bindParam(":pro",$array[$i]['pro']);
$sth->bindParam(":con",$array[$i]['con']);
$sth->bindParam(":pre",$array[$i]['pre']);
$sth->bindParam(":ca", $array[$i]['ca']);
$sth->bindParam(":de", $array[$i]['de']);
$sth->bindParam(":ke", $array[$i]['ke']);
$sth->bindParam(":da", $array[$i]['da']);
$sth->bindParam(":a", $array[$i]['a'] );
$sth->execute();
$i++;
}
But this code doesn't work. I've also tried to use try-catch(PDOException) for $sth->execute() but it doesn't show me anything.
Why?
Who says "this question is a duplicated" doesn't read really the question. Infact the error was a wrong character: $array[$count]['pr'] = $pfferta['prezzo'] would be been $array[$count]['pr'] = $offerta['prezzo']so I couldn't find an answer in another question.
Try adding some simple checks that things actually worked like this
$res = $sth->execute();
if ( ! $res ) {
echo sprintf('ERROR: %d - %s', $sth->errorCode(), $sth->errorInfo() );
}

Dynamic select query according to form fields

I have a form with two fields. The user can fill in either one or both and the MySQL database should be queried accordingly.
Here is my php code:
$number1 = $_POST['number1'];
$number2= $_POST['number2'];
$set = FALSE;
$query = "SELECT * FROM table";
if (!empty($number1 ))
{
$query .= " WHERE number1 = ".$number1."";
$set = TRUE;
}
if (!empty($number2))
{
$query .= ($set===TRUE ? " AND" : " WHERE") . " number2 = ".$number2."";
}
$data = mysql_query($query) or die("Couldn't execute query. ". mysql_error());
The code works fine if either number1 or both of the fields are filled in. However when only the second field is filled in I get the error:
Couldn't execute query. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
If I echo the query it is shown correctly:
SELECT * FROM table WHERE number2 = entered value
Any help is much appreciated! Thanks!!
have you forget escape values? u can use somthing like this
$fields = array();
if(!empty($_POST['number1'])) {
$fields[] = 'number1='.mysqli_real_escape_string($_POST['number1']);
}
if(!empty($_POST['number2'])) {
$fields[] = 'number2='.mysqli_real_escape_string($_POST['number2']);
}
$sql = "SELECT * FROM table WHERE ".implide(" AND ", $fields);
$data = mysqli_query($query) or die("Couldn't execute query. ". mysql_error());
mysql extension is deprecated, use mysqli instead
try this
$number1 = $_POST['number1'];
$number2= $_POST['number2'];
$set = FALSE;
$query = "SELECT * FROM table";
if (!empty($number1 ))
{
$query .= " WHERE number1 = ".$number1."";
$set = TRUE;
}
if (!empty($number2))
{
if($set==FALSE)
$query .= " WHERE number2 = ".$number2;
else
$query .= " AND number2 = ".$number2;
}
I think you get the error because of the assignment. You wrote $set===TRUE, its == not ===
The error is here:
if (!empty($number2))
{
$query .= ($set===TRUE ? " AND" : " WHERE") . " number2 = ".$number2."";
}

echo json_encode() is returning NULL

I am trying to pass data to a php page via ajax, the data gets inserted to the database, then I need to pick up the last insert and pass the back to update a select menu with that last insert selected. The database gets updated correctly, but Im getting a NULL return for the echo json_echo($data);
Been stuck on this all day, would really appreciate the help!!!
if (empty($_POST) === false && empty($errors) === true) {
$company_id = $_POST['company_id'];
$patient_id = $_POST['addpatient_id'];
$first_name = $_POST['addpatient_firstname'];
$last_name = $_POST['addpatient_lastname'];
$dob = $_POST['addpatient_dob'];
$updated = $_POST['patient_added'];
$update = array();
array_walk($update_data, 'array_sanitize');
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("INSERT INTO `lab`.`patients` (`company_id`, `patient_firstname`, `patient_lastname`, `patient_dob`, `patient_added`) VALUES ('$company_id', '$first_name', '$last_name', '$dob', '$updated')");
$last_patient_id = mysql_insert_id();
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname`, `patient_dob` FROM `patients` WHERE `patient_id` = $last_patient_id");
$data[] = mysql_fetch_assoc($result);
}
echo json_encode( $data );
json_encode returns false if an error happened (php manual). I would start there.
$json_string = json_encode( $data );
if( $json_string ){
echo $json_string;
}else{
echo "Error";
echo "<pre>";
print_r($data);
echo "</pre>";
}
That should at least lead you a way to debug.
EDIT: Also try add this to the beginning of the function all
error_reporting(E_ALL);
ini_set('display_errors', '1');
This will help display errors that the mysql is throwing.
EDIT: I wanted to just fix spelling, but since I need 6 characters minimum I will mention http://jsonlint.com/ to validate what you're putting into json_encode

Transparent mysql_error logging: How can I read mysql_error() twice?

I want to do a transparent mysql_error logging in my php app. I've done the following yet:
function mysql_query_log_error($query) {
$debug_trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$caller = $debug_trace[1];
$file = substr($caller[file], strrpos($caller[file], '/')+1);
$line = $caller[line];
$error = mysql_error();
$error_query = "INSERT INTO Common.ERRsql SET "
."errQuery = '".mysql_real_escape_string($query)."', "
."errText = '".mysql_real_escape_string($error)."', "
."errDate = NOW(), "
."errFile = '".mysql_real_escape_string($file)."', "
."errLine = '".mysql_real_escape_string($line)."' ";
mysql_query($error_query);
}
function mysql_query_log($query) {
$result = mysql_query($query) or mysql_query_log_error($query);
return $result;
}
But when I read mysql_error() in the mysql_query_log_error() function, the original caller can't access the mysql_error() (because it returns an empty string, so it's "read out").
How can I do it in a transparent way, I mean, the mysql_error() will remain intact?
You assign the original error to a variable, then pass that variable into the function. There's no need trying to duplicate the error, when you can get it once and store it in a variable.
This should accomplish what you're trying to do :
function mysql_query_log_error($query, $error) {
$debug_trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$caller = $debug_trace[1];
$file = substr($caller[file], strrpos($caller[file], '/')+1);
$line = $caller[line];
$error_query = "INSERT INTO Common.ERRsql SET "
."errQuery = '".mysql_real_escape_string($query)."', "
."errText = '".mysql_real_escape_string($error)."', "
."errDate = NOW(), "
."errFile = '".mysql_real_escape_string($file)."', "
."errLine = '".mysql_real_escape_string($line)."' ";
mysql_query($error_query);
}
function mysql_query_log($query) {
$result = mysql_query($query) or mysql_query_log_error($query, mysql_error());
return $result;
}
In your mysql_query_log function, you will directly store the error in a variable.

Categories