So recently I started a project where I need to load some files. In these files I have colors that come via SQL;
The Problem is, I can only include one color in a file where they'll be used. The first file to be included will work properly, but the second one will not.
The weirdest thing is that if I try to add some echo, all included files will echo it, but only the first one in the order of the import will actually work. It's kind of complicate to explain, but some code can help:
Portifolio.php (where I will use the colors)
<?php
error_reporting(E_ALL);
include_once ('php/db.php');
include_once ('php/colors/accent.php');
include_once ('php/colors/primary.php');
$page =
<<<HTML
// Long HTML code here
<nav class="$primarycolor">
// More code
<a class ="$accentcolor">
accent.php:
<?php
include ('../db.php');
$sql = "SELECT id, color FROM Colors WHERE id = 2";
$getcolor = mysqli_query($conn, $sql);
echo "Accent.php included";
if ($getcolor->num_rows > 0) {
while($row = $getcolor->fetch_assoc()) {
$accentcolor = $row['color'];
}
}
mysqli_close($conn);
?>
primary.php
<?php
include ('../db.php');
$sql = "SELECT id, color FROM Colors WHERE id = 1";
$getcolor = mysqli_query($conn, $sql);
echo "Primary.php has been included";
if ($getcolor->num_rows > 0) {
while($row = $getcolor->fetch_assoc()) {
$primarycolor = $row['color'];
}
}
mysqli_close($conn);
?>
db.php
<?php
$conn = mysqli_connect("localhost","mucap","pswd","webdata");
echo "DB included.";
if (mysqli_connect_errno())
{
echo "Error: " . mysqli_connect_error();
}
?>
In this case:
No errors are gonna be displayed.
$accentcolor will work
$primarycolor will simply pretend it does not exists
All files will echo what they were told to.
I did a lot of research and figured out it could be something with file paths, but I dont think so: Here goes (part of) my file structure:
I cant do [$DOCUMENT_ROOT] as this is not supposed to have a fixed path, long explanation.
What should I do?
Try replacing your statement with this:
if ($getcolor) {
while($row = $getcolor->fetch_assoc()) {
$primarycolor = $row['color'];
}
} else{
echo"no results in row";
}
The simple if check is possible because the results of a search return "FALSE" if there's no data in the results.
The else statement is required just for verification purposes.
If you only expect 1 result, you can do "LIMIT 1" as well as eliminate the while statement.
If you don't want the script to run at all, you should use require_once, not include_once
Related
guys currently I build a web site using PHP. I connect my website to the database using web services (url). The system is run as well. Then, I separate the web services by creating other PHP files, place the web services and include the PHP file to my web site. This is also running well. Below is the code:
add_factory.php
<?php
include("../../config/check.php");
if(isset($_POST['Submit']))
{
$Fac_ID = $_POST['Fac_ID'];
include("../../api/api_add_factory.php"); //include web services 1
if(empty($queryt)){
include("../../api/api2_add_factory.php"); //include web services 2
if(!empty($json2)){
header("Location:factory.php");
}else{
echo "
<script>alert('Something wrong, please try again')</script>
<script>window.location = 'factory.php'</script>
";
}
}
else{
echo "
<script>alert('The factory you want to add is already exist')</script>
<script>window.location = 'factory.php'</script>
";
}
}
?>
api_add_factory.php
<?php
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/selectFactory?Fac_ID=$Fac_ID";
$data = file_get_contents($url);
$json = json_decode($data);
$queryt = $json->factoryList;
?>
api2_add_factory.php
<?php
$url2 = "http://172.20.0.45/TGWebService/TGWebService.asmx/insertFactory?fac_id=$Fac_ID&fac_name=$Fac_ID";
$data2 = file_get_contents($url2);
$json2 = json_decode($data2);
?>
When you see at "add_factory.php", There's two include. Now, I want to use only single include that can call "api_add_factory.php" and "api2_add_factory.php". But I dont know how to do that since the "include" at "add_factory.php" is at different position.
Can anyone knows how to merge both include file into one and where i need to pu the include file at "add_factory.php"?
My suggestion would be to rewrite the contents of api_add_factory.php and api2_add_factory.php as functions.
This would allow you to control how and when they are called by the piece of code that includes them, rather than being executed immediately when the include is called.
Also, as a general rule of thumb, includes should all be called at the beginning of your file because otherwise they can become very difficult to keep track of.
So, I would say you can do something like this:
api_add_factory.php
<?php
function callApi1()
{
$url = "http://172.20.0.45/TGWebService/TGWebService.asmx/selectFactory?Fac_ID=$Fac_ID";
$data = file_get_contents($url);
$json = json_decode($data);
return $json->factoryList;
}
api2_add_factory.php
<?php
function callApi2()
{
$url2 = "http://172.20.0.45/TGWebService/TGWebService.asmx/insertFactory?fac_id=$Fac_ID&fac_name=$Fac_ID";
$data2 = file_get_contents($url2);
return json_decode($data2);
}
add_factory.php
<?php
include("../../config/check.php");
include("../../api/api_add_factory.php"); //include web services 2
include("../../api/api2_add_factory.php"); //include web services 2
if(isset($_POST['Submit']))
{
$Fac_ID = $_POST['Fac_ID'];
$queryt = callApi1();
if(empty($queryt)){
$json2 = callApi2();
if(!empty($json2)){
header("Location:factory.php");
}else{
echo "
<script>alert('Something wrong, please try again')</script>
<script>window.location = 'factory.php'</script>
";
}
}
else{
echo "
<script>alert('The factory you want to add is already exist')</script>
<script>window.location = 'factory.php'</script>
";
}
}
Actually, now that I am taking a look at my answer, I can see a possibility for a further improvement: since the contents of api_add_factory.php and api2_add_factory.php are actually the same apart from the url that gets called, you can do something like this:
api_add_factory.php
<?php
function callApi($url)
{
$data = file_get_contents($url);
return json_decode($data);
}
add_factory.php
<?php
include("../../config/check.php");
include("../../api/api_add_factory.php"); //include web services
$url1 = "http://172.20.0.45/TGWebService/TGWebService.asmx/selectFactory?Fac_ID=$Fac_ID";
$url2 = "http://172.20.0.45/TGWebService/TGWebService.asmx/insertFactory?fac_id=$Fac_ID&fac_name=$Fac_ID";
if(isset($_POST['Submit']))
{
$Fac_ID = $_POST['Fac_ID'];
$json1 = callApi($url1);
$queryt = $json1->factoryList;
if(empty($queryt)){
$json2 = callApi($url2);
if(!empty($json2)){
header("Location:factory.php");
}else{
echo "
<script>alert('Something wrong, please try again')</script>
<script>window.location = 'factory.php'</script>
";
}
}
else{
echo "
<script>alert('The factory you want to add is already exist')</script>
<script>window.location = 'factory.php'</script>
";
}
}
This way, we don't need to repeat the code of the function.
I'm in the process of doing a "mock" website for a class and I'm having issues getting the information from my database file, to the actual page in my site. I should mention that I'm a total php newb. Also there isn't any security yet.
I'm calling the connection from another file, so I didn't include that.
database function:
function GetProductsByCategory($categoryID) {
global $conn, $productsResult;
echo $categoryID;
$sql = "SELECT * FROM products WHERE prodCategory = '$categoryID'";
$productsResult = $conn->query($sql);
}
Website File:
//In the head of website file
<?php
$categoryID = "87";
if (isset($_GET['category'])) {
GetProductsByCategory($categoryID);
} else {
// Fallback behaviour goes here
}
?>
//In the body
<?php while ($row = $productsResult->fetch_assoc()) {
//Just trying to get information from the database file
echo '<div>'.$row["prodName"].'</div>';
}
?>
I should mention that nothing throws an error, It echos out the category ID at the top, but inside the <div> it just doesn't show anything.
Call the function and save the result in a variable:
$result = GetProductsByCategory($categoryID);
then inside the function:
$productsResult = $conn->query($sql);
return $productsResult;
then your while loop should use this returned result (i.e., $result):
while ($row = $result->fetch_assoc()) { ... }
I am trying to add image in MAMP server table & fetch it in PHP, and create json. But I am not getting how to add image in table and again it in file. I am new in PHP scripting. Please someone provide me right direction. I have added my PHP code & also MAMP table screenshot.
PHP Code file
<?php
$conn = mysql_connect("localhost:8888","asmita","asmita123") or die(mysql_error());
if($conn)
{
mysql_select_db("EmployeeInfo");
//echo "connected";
//echo $_SERVER['DOCUMENT_ROOT'];
}
else
{
echo "not connected";
mysql_error();
}
$selectQuery="select * from Emp";
$row=mysql_query($selectQuery);
while($result=mysql_fetch_array($row))
{
//echo $_SERVER['http://localhost:8888/images/index.jpg'];
//output need in JSON format for webservice ...
$empname= $result['Name'];
$empadd= $result['Address'];
$emppho= $result['Phone'];
$emppost= $result['Post'];
$empphoto=$result['Photo'];
$jsonArray[]=array("name"=>"$empname","address"=>"$empadd","phone"=>"$emppho","post"=>"$emppost","photo"=>"$empphoto");
}
echo json_encode($jsonArray);
?>
MAMP table data
Here I added image path. Is this correct? Thanks.
HTML Code
<input type="file" name="img_file" id="imageUpload">
PHP Code
$filename = $_FILES['img_file']['name'];
$src = $_FILES['img_file']['tmp_name'];
$folder = "/images/" ;
$move= move_uploaded_file($src,"$folder/".$image);
if($move!=false)
{
$pic = "http://localhost:8888/directoryName/images" .$filename; //This variable insert into Photo column
$query="Insert or Update Query for your table";
$rslt = mysql_query($query);
}
$data=array();
$selectQuery="select * from Emp";
$row=mysql_query($selectQuery);
while($result=mysql_fetch_array($row))
{
$data[] = $result;
}
echo json_encode($data);
I Dont think I wrote the code correctly. Can someone look at this? I am new to php!
<?php
// Create Connection
$connect = mysqli_connect('localhost','root','test123','joomla');
// Check Connection
if(mysqli_connect_errno($connect)) {
echo 'Failed to connect to DataBase| '. mysqli_connect_error();
}
?>
I added if(issets($_GET['rp_id'])) to the if rp_id does not exist in the url parameter - it just closes the database
<?php
if(issets($_GET['rp_id]')) {
$rp_id = htmlspecialchars($_GET["rp_id"]);
// open record with evdet_id =$rp_id
$result = mysqli_query($connect,"SELECT * FROM n0dap_jevents_vevdetail WHERE evdet_id =".$rp_id);
while($row = mysqli_fetch_array($result)):
$value = $row['google_map'];
echo $value;
endwhile;
}
$connect->close();
//if the rp_id does exist the go ahead and run the top otherwise close it.
} else {
$connect->close();
}
?>
if(issets($_GET['rp_id]))
Looks like you made a typo on isset().
Call to undefined function issets()
This means you're trying to call issets() as a function, which it is not.
The function that you are looking for is isset(). If you replace issets() with isset(), you will not longer get that error message.
I've written a method to set a header() to the appropriate file type of an upload stored in a database and then I would like to echo() the file.
The method is as follows inside a controller:
function view_upload( $id = 0 ) {
$id = $this->db->escape( $id );
$query = $this->db->query( "SELECT file_type FROM media WHERE id = $id" )->row();
$query2 = $this->db->query( "SELECT file FROM media WHERE id = $id" )->row();
header("Content-type: ".$query->file_type);
//die( "moo" );
echo( $query2->file );
}
Strangely as soon as I set the header() the rest of the method seems to be ignored, for example, if I uncomment the die() statement it doesn't die and it doesn't echo the image. If I remove the header() call I see the raw upload blob presented to the screen..
Is this something to do with CodeIgniter or have I made a PHP mistake?
EDIT:
I've changed the function and put it in a separate file outside of CodeIgniter but if I browse to it and pass in an $id it still doesn't display the image...
<?php
// just so we know it is broken
error_reporting(E_ALL);
// some basic sanity checks
if(isset($_GET['id']) && is_numeric($_GET['id'])) {
//connect to the db
$link = mysql_connect("localhost", "user", "pass") or die("Could not connect: " . mysql_error());
// select our database
mysql_select_db("database") or die(mysql_error());
$id = $_GET['id'];
// get the file from the db
$sql = "SELECT file FROM media WHERE id=$id";
// the result of the query
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
// get the file_type from the db
$sql = "SELECT file_type FROM media WHERE id=$id";
// the result of the query
$result2 = mysql_query("$sql") or die("Invalid query: " . mysql_error());
// set the header for the image
//ob_clean();
//die( mysql_result($result, 0) );
//header('Content-type:'.mysql_result($result2, 0));
header('Content-type: image/png');
//ob_clean();
echo mysql_result($result, 0);
// close the db link
mysql_close($link);
}
else {
echo 'Please use a real id number';
}
?>
die() on the two $result produces what I would expect but it's not displaying the page in the browser. Again if I add ob_clean() it says:
ob_clean() [<a href='ref.outcontrol'>ref.outcontrol</a>]: failed to delete buffer. No buffer to delete.
I've copied the code from here: http://www.phpriot.com/articles/images-in-mysql/8 if that helps at all..
It turns out that the image in the database was corrupt, and hence not displaying, because I had added addslashes() to the file contents (not really sure why, seem to remember reading it was useful in combating XSS vulnerabilities).
Removing that meant I had non-corrupt images stored and then they displayed okay.
First You need to start ob_start() just before on_clean() then you need to write like header().
Here is the follow.
ob_start();
ob_clean();
header ("Content-type: image/png");
?>
Try this let me know is this working or not hopefully it will help you.