Having a MYSQL query within a PHP fwrite function - mysql

basically I am try to get the php file to create another php file which has XHTML, PHP and MYSQL within it. I am trying to include a MYSQL query but the problem is that the apostrophe (') that I use to start the fwrite string get confused when it reaches a MYSQL query because it too also has an apostrophe but I just want that string to continue not end. What should I do for this to work? Thanks in advance for any help.
The code (just the relevant bit):
$filename = "websites/".$firstpage.".php";
$filehandle = fopen($filename, 'w') or die("error opening file");
$datawrite = '
$query = "SELECT websitetitle FROM $weblist WHERE webID='$webID'";
$result = mysql_query ($query);
$row = mysql_fetch_array( $result );
echo $row['webID'];
';
fwrite($filehandle, $datawrite);
fclose($filehandle);

You should escape the ' in the query with \' This will not exec and end the string
$filename = "websites/".$firstpage.".php";
$filehandle = fopen($filename, 'w') or die("error opening file");
$datawrite = '
$query = "SELECT websitetitle FROM $weblist WHERE webID=\'$webID\'";
$result = mysql_query ($query);
$row = mysql_fetch_array( $result );
echo $row[\'webID\'];
';
fwrite($filehandle, $datawrite);
fclose($filehandle);
Check this out for reference
http://php.net/manual/en/language.types.string.php

Just use proper escaping and place a \ before the apostrophe.
$datawrite = '
$query = "SELECT websitetitle FROM $weblist WHERE webID=\'$webID\'";
$result = mysql_query ($query);
$row = mysql_fetch_array( $result );
echo $row[\'webID\'];
';

Related

Turkish character problems json encode - Mysql

I output with the json_encode method. It does not show Turkish characters in the output I have received. What should I do to show Turkish characters? I am using mysql. Collation of the table = utf8_turkish_ci
<?php
$con=mysqli_connect(...);
header('Content-Type: text/html; charset=utf-8');
mysql_set_charset('utf8', $con);
$formID = $_POST['formID'];
$query = "SELECT ADI_SOYADI ...";
$result = mysqli_query($con,$query);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$apptADI = $r['ADI_SOYADI'];
$results = Array("ADI_SOYADI" => $apptADI);
}
echo json_encode($results);
mysqli_close($con);
?>
It seems that prior to use json_encode()you should use utf8_encode()
https://www.geeksforgeeks.org/php-utf8_encode-function/
echo json_encode(utf8_encode($results));
There is also the parameter JSON_UNESCAPED_UNICODE that you can add to json_encode()

SQL to JSON converts my int to string

I have this in my PHP.
$sql="select * from defaulttime";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result)){
$row_set[] = $row;
}
echo trim(json_encode($row_set));
In my SQL some columns are Integer. but in JSON it shows as String.
can someone please tell me what I am doing wrong?
when I run the PHP, I get the below results. (Note Hour and Minute should be Integers)
[{"name":"Test","Hour": "6" ,"Minute":"45"}],
I want it to show string as string and Int as Int.
{"name":"Test","Hour": 6 ,"Minute":45}
You have to use JSON_NUMERIC_CHECK option in order to get numerics value,
look here: https://lornajane.net/posts/2011/php-returning-numeric-values-in-json
echo trim(json_encode($row_set,JSON_NUMERIC_CHECK));
Thanks all,
I got it working by using this code:
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result)){
$row_set[] = $row;
}
$json=json_encode($row_set,JSON_NUMERIC_CHECK);
echo $json;

Inserting a table in a database without knowing prefix

I have a small script that will insert two tables in a database, which works fine unless the user has changed the default prefix. I am wondering how I can call and use the "prefix" from the config file. Here is my code.
<?php
include("../../Config/config.php");
$link = mysql_connect($CONFIG['host'], $CONFIG['login'], $CONFIG['password'];
$db = ($CONFIG['database']);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("$db", $link);
$sql = 'INSERT INTO settings '.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';
$exec = mysql_query($sql, $link);
if (!$exec) die(mysql_error());
mysql_close($link);
?>
You can see that I call "config.php" to get the database info. That would also work to get the prefix but I'm not sure how to implement the "prefix" with the rest of the code.
FYI: I'm a newbie :)
Thanks.
I got it, here's what worked.
<?php
require_once ("../../Config/config.php");
$link = mysql_connect($CONFIG['host'], $CONFIG['login'],$CONFIG['password']);
$table_prefix = ($CONFIG['prefix']);
$db = ($CONFIG['database']);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("$db", $link);
$sql = 'INSERT INTO ' . $table_prefix . 'settings'.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';
$exec = mysql_query($sql, $link);
if (!$exec) die(mysql_error());
mysql_close($link);
?>
Thanks for the help BK435
Welcome!
I am assuming you can get the prefix and store it in variable. When calling your sql add this to your code ' . $TABLE_PREFIX . '. so your above insert would look something like:
$sql = 'INSERT INTO ' . $TABLE_PREFIX . 'settings '.
'(id, field, value) '.
'VALUES ("NULL", "show_thumbs_down", "1")';

Cannot fetch sorted data from mysql database by perl

I am trying to create a cgi based on perl to display my album and now I am working on the sorting function on photos. I stored the information of each photo in mysql. To display all photos, I have to fetch the information first.
Here is the problem: I am expecting the fetched data from mysql is sorted by the file size of each photos, however the result from the fetchrow_array() is the data sorting according to the time being inserted into mysql.
In mysql shell, I tested
SELECT * FROM album ORDER BY filesize;
which gives the expected result sorted by the file size. Here is part of my source code:
#!/usr/bin/perl -w
use strict;
use CGI;
my $sort = 'filesize';
# Connect the database
my $dbh = do 'db.pl';
# Prepare to print out the pictures
my $query;
$query = $dbh->prepare("SELECT * FROM album ORDER BY ?") or die $DBI::errstr;
$query->execute($sort) or die $DBI::errstr;
# Print out all pictures
while( my #data = $query->fetchrow_array() ){
# Process fetched data
(my $id, my $user, my $filepath, my $filename, my $filesize, my $uploadtime, my $description, my $tfilepath, my $sessioninfo) = #data;
print '<fieldset>';
# Display thumbnail
print '<img src="', $tfilepath, '" title="', $description, '">';
# Display filename
print '</br>';
print $filename;
print '</fieldset>';
}
# Finish printing out all fetched pictures
$query->finish;
Am I using the wrong command? Or I am using a wrong approach to do the sorting function?
Thanks for helping!
ORDER BY takes a field name, not an expression.
my $query = "SELECT * FROM album ORDER BY ".$dbh->quote_identifier($sort);
my $sth = $dbh->prepare($query);
$sth->execute();
By the way, you have have bugs on the output side too. What if $description contains """, "&" or "<"? You need some escaping.
sub text_to_html {
my ($s) = #_;
$s =~ s/&/&/g;
$s =~ s/</</g;
$s =~ s/>/>/g;
$s =~ s/"/"/g;
$s =~ s/'/&apos;/g;
return $s;
}
By the way,
(my $id, my $user, my $filepath, my $filename,
my $filesize, my $uploadtime, my $description,
my $tfilepath, my $sessioninfo) = #data;
can be written as
my ($id, $user, $filepath, $filename,
$filesize, $uploadtime, $description,
$tfilepath, $sessioninfo) = #data;

Perl DBD error FUNCTION dbName.GLOB does not exist

I am starting to write some Perl scripts for some cron jobs that will query the database and send out reminders about upcoming events. I'm quite new to database access in Perl as most of my work thus far has been on the web end using PHP. Anyway, the first query is working fine to generate a temporary output file and then I'm reading back in that output file to loop thru the results querying to find the specific events for the users discovered in the first query.
The problem that I am running into now is getting the following error:
./remind.pl
DBD::mysql::st execute failed: FUNCTION dbName.GLOB does not exist at ./remind.pl line 41.
SQL Error: FUNCTION dbName.GLOB does not exist
This is my Perl code
$host = 'localhost';
$database = 'dbName';
$user = 'user';
$password = 'password';
use POSIX qw(strftime);
use List::MoreUtils qw(uniq);
use Mail::Sendmail;
use DBI;
$dt = strftime("%Y%m%d%H%M%S", localtime(time));
$List30 = "../tmp/queries/30DayUserList.$dt";
open my $UserList30Day, ">> $List30" or die "Can't create tmp file: $!";
$dbh = DBI->connect('dbi:mysql:dbName',$user,$password) or die "Connection error: $DBI::errstr\n";
$sql = "SELECT DISTINCT user FROM shows WHERE initial_date BETWEEN CURDATE() AND CURDATE() + INTERVAL 30 DAY";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while (#jeweler = $sth->fetchrow_array()) {
print $UserList30Day "$user[0]\n";
}
close $UserList30Day;
open my $UserIDList, "< $List30" or die "Can't open temp file: $List30";
while ($id = $UserIDList) { # Read in User ID from temp file as $id
# Query for show information for next 30 days
my $sql = "SELECT shows.initial_date, shows.initial_time, shows.hostess_key, hostess.hostess_fname, hostess.hostess_lname, hostess.primary_phone, hostess.address1, hostess.address2, hostess.city, hostess.zipcode, hostess.state
FROM shows, hostess
WHERE shows.user = $id
AND initial_date BETWEEN CURDATE() AND CURDATE() + INTERVAL 30 DAY
AND shows.hostess_key = hostess.hostess_key";
my $sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
# Iterate thru query results to create output data
while (#row = $sth->fetchrow_array()) {
$content = "Reminder: You have a show for $row[3] $row[4] coming up on $row[0] at $row[1].\n";
$content .= "Location: $row[6] \n";
if ($row[7] != '') {
$content .= " " . $row[7] . "\n";
}
$content .= " $row[8], $row[10] $row[9] \n";
$content .= "Phone: $row[5] \n";
}
%mail = (To => 'email',
From => 'email',
Subject => 'Just another test',
Message => $content
);
# sendmail(%mail) or die $Mail::Sendmail::error;
print %mail;
}
close $UserList30Day;
Thanks in advance for any assistance.
while ($id = $UserIDList) {
should be
while ($id = <$UserIDList>) {
chomp;