How to include variables inside a php file created via fopen - php

I am trying to create a php file with the fopen() function. The content of the php file(s) that will be created need to be built so that they can be executed at a later date to update a mysql db. So if the php file is created, it should show include to a config.php and a way to connect to the db and execute a query.
So for example, the file that will be created will look something like:
<?php
include_once 'config.php';
$updateSQL = "update table set is_active = 1 where id = 10";
$conn = mysqli_connect("$dbhost","$dbuser","$dbpass","$usedb");
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
} else {
mysqli_query($conn,$updateSQL );
}
?>
Creating an empty php file is simple but I don't know whether it is possible to show variables in the file that will be created.
FYI, the file will consist of other tasks such as creating a directory which I can do, this is the part I am stuck on so any suggestions?

this my solve your query
<?php
$text = "hi Amar";
$var_str = var_export($text, true);
echo $var = "\n\n\$text = $var_str;\n\n";
?>
Result: $text = 'hi Amar';

Related

How to fetch from MySql Database when using Include connection?

I'm using include connection file to connect to the database. My challenge is how do I fetch from the database this is where am stuck.
include 'connection.php';
$sql = 'SELECT * FROM country';
$results = mysqli_query($sql);
assume your connection.php contain
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
So the in your file, you're using include 'connection.php' to get the connection. By using include its act like single page now. Then you've to use it like below
require_once 'connection.php';
$sql= 'SELECT * FROM country';
$results = mysqli_query($con, $sql); # add connection string to query
Explanation
when you add this include 'connection.php'; then whatever the data on parent(connection.php) file (ex: variable, Functions, etc ..) will come to child.
Links to refer
In PHP, how does include() exactly work?
Are PHP include paths relative to the file or the calling code?
include, include_once, require or require_once?

PHP->JSON Encoding not working

I know this has been asked like a million times now.
I tried several solutions I found here but still it doesn't work for me.
What i want to do is SELECT Values out of a simple MySQL Table.
The Values are inserted every five minutes by a program I have written.
I catches all mp3 files in a selected folder and inserts its ID3 Tags into the Table tb_song.
These files should then be SELECTED with the PHP Script and an Android App should Play these files with their URL.
The Database and PHP Code works.
If I just echo all selected values it works fine.
But converting and printing out the encoded array just throws an blank screen.
Could it be that JSON Objects are limited to size?
I've got about 500 entries in tb_song.
Here's my code.
<?php
require_once('config.php');
$connection=new mysqli($server,$user,$password,$database);
$songs=array();
$sql=("SELECT Title,Artist,Album FROM tb_song");
$result=$connection->query($sql);
while($row=$result->fetch_assoc())
{
$temp=array();
$temp['Title']=$row['Title'];
$temp['Artist']=$row['Artist'];
$temp['Album']=$row['Album'];
array_push($songs,$temp);
}
json_encode($songs);
echo(json_encode($songs));//just for testing purposes
$connection->close();
?>
You can distil your code down to this. Plus adding some error checking!
<?php
/* add next 2 lines while testing,
especially if you are using a live hosting site
where error reportinf will be turned off
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'config.php';
$connection = new mysqli($server,$user,$password,$database);
// Check connection is good
if ($connection->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $connection->connect_error);
}
$songs=array();
$sql = 'SELECT Title,Artist,Album FROM tb_song';
$result = $connection->query($sql);
if ( ! $result ) {
echo $connection->error;
exit;
}
while($row=$result->fetch_assoc()) {
$songs[] = $row;
}
$jstring = json_encode($songs);
if ( json_last_error() > 0 ) {
file_put_contents('json-output.txt', json_last_error_msg());
}
echo $jstring;
//add this line for testing
file_put_contents('json-output.txt', $jstring);
exit;
?>
I finally figured it out.
I guess this is not the standard which's happening to all people but anyway.
Before I'll post my code I want to say a few things for people who are running into the same problem:
Make sure you're only passing strings without 'ä','ü' or whatever letter that is not in the english alphabet.
You need to give your JSON Object a Name, otherwise it could cause problems.
<?php
require_once 'config.php';
$connection = new mysqli($server,$user,$password,$database);
if ($connection->connect_error) {
die('Connect Error (' . $connection->connect_errno . ') '
. $connection->connect_error);
}
$songs=array();//Create Array
$sql = 'SELECT * FROM tb_song';
$result = $connection->query($sql);
while($row=$result->fetch_assoc()){
array_push($songs,$row);//Insert $row in $songs
}
echo json_encode(array('Songs'=>$songs));//Giving JSON Object a proper Name and //encode
$connection->close();
?>

PHP to access to a .db file

I am new to PHP and trying to create a search field that searches through my database file. I am putting my database file rc3.db inside the same folder that contains my PHP file and trying to connect it with mysqlite, however I
Tried $con = mysqli_connect("localhost:8888","user","password","rc3.db"); but errors,I don't have a user nor a password. Also tried $con = mysqli_connect(); it works but I'm not sure if which database it is connecting to. I also did the single arguement with rc3.db as below, but it is probably mistaking that for the hostname, which is the the first parameter that the method takes in.
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
<?php
//connection to the database
$con = mysqli_connect("rc3.db");
echo "Connected to MySQL<br>";
?>
</body>
</html>
Warning: mysqli_connect(): (HY000/2005): Unknown MySQL server host 'rc3.db' (22) in /Applications/MAMP/htdocs/searchform.php on line 9
Call Stack
# Time Memory Function Location
1 0.0005 229848 {main}( ) ../searchform.php:0
2 0.0005 230072 mysqli_connect ( ) ../searchform.php:9
As I understand your database is not a mysql db but a sqlLite database.
If that so, you can use the sample code bellow to access the data.
$db = new PDO('sqlite:rc3.db');
$query = $db->prepare("Your sql query here");
$query->execute();
while($row = $query->fetchObject())
{
//do your staff
}
Update 1
As #Sean pointed correctly in the comments as an alternative you can use sqlite_open
$con = sqlite_open('rc3.db', 0666, $error))
The connection to the database using the extension mysqli.
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
use PDO like in code below. And read this https://renenyffenegger.ch/notes/development/web/php/snippets/sqlite/index
It really helped me
<?php
$db = new PDO("sqlite:tg.db"); // file tg.db in local folder
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $db -> query('SELECT * FROM tgdata'); // select all data from my table 'tgdata'
foreach ($query as $row) {
var_dump($row);
}

Getting data from sql into drop down list(select\option in html)

I am trying to build a drop down element in html, and to add the values according to user pre-choice.
Lets say I have table with one col is game type ans second is a name field.
So if the user first drop down choice is basketball - so another drop down list is opened with all the basketball fields as options.
so I have my html file which has inside this php lines:
$game_type = $_POST['gameType'];
$con = mysql_connect("localhost", "root", "Jbtraining1");
if (!$con)
die('Could not connect: ' . mysql_error());
$db_selected = mysql_select_db("test_sport",$con);
$sql = ("SELECT * FROM fields WHERE game_type = '$game_type'");
$result = mysql_query($sql,$con);
while($row = mysql_fetch_array($result))
echo "<option value='".$row['field_name_en']."'>" . $row['field_name_en'] . "</option>";
?>
</select>
but this lines does not work. I think most of the lines work well cause if i chage this line:
$game_type = $_POST['gameType'];
to let say to this line -
$game_type = "basketball";
It does work just fine.
Thanks
Change your file extension from .html to .php
Hope this helps
Use
echo $_POST['gameType'];
to see if the variable is send.
It sounds like it isn't send because you say it works when you use:
$game_type = "basketball";
If the echo is empty something gos wrong when you send the variable.
If that is the case post the code you use to post the variable.

INSERT IGNORE In mySQL

I wonder whether someone can help me please.
I'm trying to put together a PHP script that takes data from an xml file and places the data in a mySQL data. I've been working on this for a few days and I'm still can't seem to get this right.
This is the code that I've managed to put together:
<?
$objDOM = new DOMDocument();
$objDOM->load("xmlfile.xml");
$Details = $objDOM->getElementsByTagName("Details");
foreach( $Details as $value )
{
$listentry = $value->getElementsByTagName("listentry");
$listentrys = $listentry->item(0)->nodeValue;
$sitetype = $value->getElementsByTagName("sitetype");
$sitetypes = $sitetype->item(0)->nodeValue;
$sitedescription = $value->getElementsByTagName("sitedescription");
$sitedescriptions = $sitedescription->item(0)->nodeValue;
$siteosgb36lat = $value->getElementsByTagName("siteosgb36lat");
$siteosgb36lats = $siteosgb36lat->item(0)->nodeValue;
$siteosgb36lon = $value->getElementsByTagName("siteosgb36lon");
$siteosgb36lons = $siteosgb36lon->item(0)->nodeValue;
//echo "$listentrys :: $sitetypes :: $sitedescriptions :: $siteosgb36lats :: $siteosgb36lons <br>";
}
require("phpfile.php");
//Opens a connection to a MySQL server
$connection = mysql_connect ("hostname", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
mysql_query("INSERT IGNORE INTO scheduledsites (listentry, sitetype, sitedescription, siteosgb36lat, siteosgb36lon) VALUES('$listentrys','$sitetypes','$sitedescriptions','$siteosgb36lats','$siteosgb36lons') ")
or die(mysql_error());
echo "Data Inserted!";
?>
I can pull the data from the xml file, but it's the part of the script that sends the data to my database table that I'm having trouble with.
The script runs but only the last record is saved to the database.
I can parse the fields from the xml file without any problems and the check I'm trying to put in place is, if there is a 'listentry' number in the new data that is matched to one already in the table then I don't want that record to be added to the table, i.e. ignore it.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Many thanks
You are only calling mysql_query once. So it will only insert one row.
The sql needs to be inside the loop.

Categories