Pesky Apostrophes in Database results - php

Okay... to make a long story short... here is my code...
<?php
$con = mysql_connect($db_server_name,$db_username,$db_password);
if (!$con)
{
echo "0";
}
mysql_select_db("" . $db_database_name . "", $con);
$result = mysql_query("SELECT * FROM sched_posts
WHERE user_id='$user_id'");
while($row = mysql_fetch_array($result))
{
$post_id = $row['ID'];
$post_year = $row['post_year'];
$post_month = $row['post_month'];
$post_day = $row['post_day'];
$post_hour = $row['post_hour'];
$post_minute = $row['post_minute'];
$post_privacy = $row['post_privacy'];
$post_message = $row['post_message'];
echo " {";
echo " id: " . $post_id . ",";
echo " title: ' " . $post_message . "',";
echo " start: new Date(" . $post_year . ", " . $post_month . "-1, " . $post_day . ", " . $post_hour . ", " . $post_minute . "),";
echo " allDay: false";
echo " },";
}
?>
When returning results, the post_message sometime's comes back with apostrophes in it. How can I get those results to appear as \' instead of just ' (in other words... with a backslash in front of it)?
PS.. I know some of this code looks unnecessary but please try to ignore that.... this is only setup this way for some testing that i am doing for facebook SDK results (for example, the identifiers inside of the WHILE statement).
The problem is, the returned apostrophes are causing the entire thing to go loopy... you know what i mean.

If you convert all those "date partial" columns into a timestamp, you can simply use json_encode():
$ts = mktime($post_hour, $post_minute, 0, $post_month, $post_day, $post_year);
echo json_encode(array(
'id' => $row['ID'],
'title' => $row['post_message'],
'start' => date('r', $ts), // <-- that's a string now
'allDay' => false,
));
JavaScript has no problems using rfc822 formatted dates.

To add backslashes, the function addslashes() would work for this:
http://php.net/manual/en/function.addslashes.php
To encode JSON 100% reliably (especially for fields like this that you can't predict/expect certain values/input), it would be best to use json_encode():
while($row = mysql_fetch_array($result))
{
$post_id = $row['ID'];
$post_year = $row['post_year'];
$post_month = $row['post_month'];
$post_day = $row['post_day'];
$post_hour = $row['post_hour'];
$post_minute = $row['post_minute'];
$post_privacy = $row['post_privacy'];
$post_message = $row['post_message'];
$dateString = ''; // computed date string...
echo json_encode(array("id"=>$post_id,"title"=>$post_message,"start"=>
$dateString,"allDay"=>false));
}

The json_encode() function is designed to generate JSON data but, since JSON is a subset of JavaScript, it's the best alternative to generate dynamic strings. Here's a use example:
<?php
$post_id = 314;
$post_message = <<<EOM
Jim "Big Boy" O'brian wrote:
<strong>Hi</strong>
EOM;
$post_year = 2013;
$post_month = 10;
$post_day = 9;
$post_hour = 17;
$post_minute = 4;
echo "{";
echo " id: " . $post_id . ",";
echo " title: " . json_encode($post_message) . ",";
echo " start: new Date(" . $post_year . ", " . $post_month . "-1, " . $post_day . ", " . $post_hour . ", " . $post_minute . "),";
echo " allDay: false";
echo "},";
... that produces:
title: "Jim \"Big Boy\" O'brian wrote:\r\n\r\n<strong>Hi<\/strong>\r\n"
Please note you have to omit the surrounding quotes; the function adds them for you.

Related

PHP RESTful API not getting variables and crashing

I have simple restful api with php
<?php
require "../ConfigBaza.php";
$proizvodid = $_GET['proizvodid'];
$naziv = $_GET['naziv'];
$pdv = $_GET['pdv'];
$aa = $_GET['akcijski_artikal'];
$a = $_GET['aktivan'];
$slika = $_GET['slika'];
$jm = $_GET['jm'];
$opis = $_GET['opis'];
$katbr = $_GET['katbr'];
$sql = "INSERT INTO Proizvod (PROIZVODID, NAZIV, PDV, AKCIJSKI_ARTIKAL, AKTIVAN, SLIKA, JM, OPIS, KATBR) VALUES ('$proizvodid', '$naziv', '$pdv', '$aa', '$a', '$slika', '$jm', '$opis', '$katbr')";
if($mysqli->query($sql))
{
echo("1");
}
else
{
echo("0" . "<br>");
echo("PROIZVODID = " . $proizvodid . "<br>");
echo("NAZIV = " . $naziv . "<br>");
echo("PDV = " . $pdv . "<br>");
echo("Akcijski Artikal = " . $aa . "<br>");
echo("Aktivan = " . $a . "<br>");
echo("SLIKA = " . $slika . "<br>");
echo("JM = " . $jm . "<br>");
echo("OPIS = " . $opis . "<br>");
echo("KATBR = " . $katbr . "<br>");
}
?>
And when i enter url like this:
/Php/Proizvodi/Novi.php?proizvodid=3410&naziv=REVIZIJA%20200*200%20GIPS&pdv=20&akcijski_artikal=1&aktivan=1&slika=&katbr=74-1800%20P%20#2.012N3IZ&jm=kom&opis=Revizioni%20otvor
It doesn't execute sql and for some reason jm returns blank and opis returns blank even if doesn't need to.
I think you might be looking for something along these lines https://www.designcise.com/web/tutorial/how-to-get-key-value-pair-from-url-query-string-in-php
In this example they use parse_str($_SERVER['QUERY_STRING'], $output); to get the raw values without url encoding.
I believe it is to do with having the # in the url string.
The server can't access the variables beyond the #, they are only accessible from the front end.
Hope this helps.

php database query (phpMyAdmin) only brings back one value (the first one) into amcharts

The below php database query (from phpMyAdmin) only brings back one value (the first one or the oldest) into amcharts:
<?php
class custom_class2
{
var $charts; // reference to the calling object.
function customfunction2($content,$conf)
{
global $TSFE;
$TSFE->set_no_cache();
// do whatever you want here
// db connection
mysql_connect("hostname", "username", "password");
mysql_select_db("database name");
//db abfrage
$query = "
SELECT
YEAR(datetime) AS dy,
MONTH(datetime) -1 AS dm,
DAY(datetime) AS dd,
HOUR(datetime) AS th,
MINUTE(datetime) AS tm,
temp,
hum,
pressure
FROM stock1
ORDER BY datetime
";
// NEW: Variable definition
$zeilenzaehler = 1;
// output of the rows
$result = mysql_query($query) OR die("Error: $query <br>" . mysql_error());
while ($row = mysql_fetch_array($result))
{
// return
if ($zeilenzaehler != 1)
{
$content.= ",";
}
$content.= "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
return $content;
// Variable now on 2
$zeilenzaehler = 2;
}
}
}
?>
Everything else looks like its working fine. Many thanks for the help
You return the first found result in your while-loop. That is why you have just one result. Also as mysql_* functions are depreceted consider switching to
mysqli_* or PDO.
I am adding code from your request:
<?php
class custom_class2
{
var $charts; // reference to the calling object.
function customfunction2($content,$conf)
{
global $TSFE;
$TSFE->set_no_cache();
// do whatever you want here
// db connection
$mysqli = new mysqli("hostname", "username", "password", "database name");
if ($mysqli->connect_error) {
// your error handling here
}
//db abfrage
$query = "
SELECT
YEAR(datetime) AS dy,
MONTH(datetime) -1 AS dm,
DAY(datetime) AS dd,
HOUR(datetime) AS th,
MINUTE(datetime) AS tm,
temp,
hum,
pressure
FROM stock1
ORDER BY datetime
";
// NEW: Variable definition
$zeilenzaehler = 1;
// output of the rows
$result = $mysqli->query($query);
if (FALSE === $result) {
// you can put different error handling here
echo 'Error: ' . $query . ' ' . $mysql->error);
die();
}
$total = array();
while (NULL !== ($row = $result->fetch_array()))
{
// return
if ($zeilenzaehler != 1)
{
$content.= ",";
}
$content.= "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
// return $content;
// if you not return the first result you can gather results in array, so array will contain every row in result, $total[0], $total[1]...:
// $total[] = $content; or:
$total[] = "{date: new Date(" . $row['dy'] . "," . $row['dm'] . "," . $row['dd'] . "," . $row['th'] . "," . $row ['tm'] . "),t:" . $row['temp'] . ",h:" . $row['hum'] . ",p:" . $row['pressure'] . "}";
// Variable now on 2
$zeilenzaehler = 2;
}
$result->free();
return $total; // return all rows
}
}
?>

Date is not saving to database

I'm creating an appointment plugin, in that for already members and new members are there. in already member area the date entry is not entring into db. but when displaying the variale contains the date. i'm have been checking this from morning but didn't get what is the error. my code is:
$source = mysql_real_escape_string(trim($_POST['apdatetime']));
$datetime = explode(',', $source);
$dates = $datetime[0];
$app_time = $datetime[1];
if($app_time < 12){
$app_session = 'am';
}
else{
$app_session ='pm';
}
$splitdatet = explode('/', $dates);
$yyear = $splitdatet[2];
$mmonth = $splitdatet[1];
$ddate = $splitdatet[0];
$app_date = $yyear . "-" . $mmonth . "-" . $ddate;
if ($_POST['isnewpatient'] == "false") {
//$cSql = "select * from " . WP_contact . " where appointments_c_patientid='" . trim($_POST['ptntid']) . "' ";
$cSql = "select * from " . WP_eemail_TABLE_SUB . " where eemail_patient_id='" . trim($_POST['ptntid']) . "' ";
$data = $wpdb->get_results($cSql);
if (empty($data )) {
$err = 1;
echo "<div id='message' class='aerror'>No such patient ID exists....</div>";
} else {
#$mobile = htmlspecialchars(stripslashes($data[0]->eemail_mobile_sub));
#$email = htmlspecialchars(stripslashes($data[0]->eemail_email_sub));
#$name = htmlspecialchars(stripslashes($data[0]->eemail_name_sub));
$sqlss = "insert into " . WP_Appointments .
" (`appointments_patient_id`,`appointments_date`,`appointments_time`,`appointments_session`,`appointments_reg_date`) VALUES ('" .
mysql_real_escape_string(trim($_POST['ptntid'])) . "','" .
$app_date . "','" .
$app_time . "','" .
$app_session . "',CURRENT_TIMESTAMP() )";
$dd=$wpdb->get_results($sqlss);
var_dump($dd);
echo 'Date:'.$app_date;
// return $suc;
echo "<div id='message' class='asuccess' >Request has been sent for appointment</div>";
}
}
The output of the var_dump is array[0] and $app_date is Date:2014-10-22
The db entry is
appointments_id :393
appointments_patient_id : 9999999999
appointments_date : 0000-00-00
appointments_time : 9:00
appointments_session : am
appointments_reg_date : 2014-09-25 14:21:35
could anyone please point out the mistake in the code if any??
You should convert your string into date object like this:
$app_date = date('Y-m-d',strtotime($app_date));

Uknown column error i have tired multpul things

Im getting a Unknown column error and i cant seem to find a topic that seems to help me.. here the code but when i seem to remove the WHERE username = $user in the $query or replace $user with a quote it seems to work just fine. (FYI Im like a total noob at php)
<?PHP
$id = "";
$username = "";
$email = "";
$nick = "";
$isMod = "";
$rank = "";
$joinDate = "";
$ip = "";
$coins = "";
$curHead = "";
$curFace = "";
$curNeck = "";
$curBody = "";
$curHands = "";
$curFeet = "";
$curPhoto = "";
$curFlag = "";
$curColor = "";
$db = mysql_connect("localhost","root","");
mysql_select_db("opencp", $db);
$user = $_GET['user'];
$query = "SELECT * from game_users WHERE username = ". $user. "";
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error());
}
echo "<?xml version=\"1.0\"\n";
echo "<products>\n";
while($line=mysql_fetch_array($result)){
echo "<item>" . $line['id'] . "</item>\n";
echo "<item>" . $line['username'] . "</item>\n";
echo "<item>" . $line['email'] . "</item>\n";
echo "<item>" . $line['nickname'] . "</item>\n";
echo "<item>" . $line['ismoderator'] . "</item>\n";
echo "<item>" . $line['rank'] . "</item>\n";
echo "<item>" . $line['joindate'] . "</item>\n";
echo "<item>" . $line['ips'] . "</item>\n";
echo "<item>" . $line['coins'] . "</item>\n";
echo "<item>" . $line['curhead'] . "</item>\n";
echo "<item>" . $line['curface'] . "</item>\n";
echo "<item>" . $line['curneck'] . "</item>\n";
echo "<item>" . $line['curbody'] . "</item>\n";
echo "<item>" . $line['curhands'] . "</item>\n";
echo "<item>" . $line['curfeet'] . "</item>\n";
echo "<item>" . $line['curphoto'] . "</item>\n";
echo "<item>" . $line['curflag'] . "</item>\n";
echo "<item>" . $line['colour'] . "</item>\n";
}
echo "</products>";
mysql_close($db);
?>
Change it to,
$query = "SELECT * from game_users WHERE username = '". $user ."'";
$result = mysql_query($query);
You should start with PHP Strings.
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
username is a string so it should be in single quotes.
$user = $_GET['user'];
$query = "SELECT * from game_users WHERE username = '". $user. "'";
$result = mysql_query($query);
There are a couple answers here already but I thought I'd point out that since your string is in double quotes you can make it less confusing by not using the concatenation (period) style:
$query = "SELECT * from game_users WHERE username = '$user ' ";
Variables are replaced inside double quotes in php, but not within single quoted strings.

xml parser using php from a link

i have the following code in PHP
$link ="http://ws.audioscrobbler.com/2.0/?method=&user=xgayax" .
"&api_key=b25b959554ed76058ac220b7b2e0a026";
$xml = #simplexml_load_file($link);
$tracks = $xml->recenttracks->track;
for ($i = 0; $i < 3; $i++) {
$playingnow = $tracks[$i]->attributes()->nowplaying;
$name = $tracks[$i]->name;
$artist = $tracks[$i]->artist;
$url = $tracks[$i]->url;
$date = $tracks[$i]->date;
$img = $tracks[$i]->children();
$img = $img->image[0];
echo "<a href='" . $url . "' target='TOP'>";
if ($nowplaying == "true") {
echo "Now playing: ";
}
echo "<img src='" . $img . "' alt='album' />
$artist . " - " . $trackname . " # " . $date . "
</a>
";
}
and i got the following error
Parse error: syntax error, unexpected '#', expecting ',' or ';' on line 31
any solution for this problem???
Your last lines have a error, the correct code is:
echo "<img src='" . $img . "' alt='album' />" .
// ^^^ missing
$artist . " - " . $trackname . " # " . $date . "
</a>
";

Categories