I just finished writing this script and getting it to work but I need to use it a total of 8 times on 1 page. It works fine the first time but the second time I get: Fatal Error cannot redeclare get_names(). I've been told the way around this is to use include_once but I can't seem to figure out how exactly I'm supposed to do that. I've tried cutting both of the get_names parts out of the code and putting them into separate php files then using the include_once command. I got it to work but once again I got the same error after trying to use the script twice. I also tried putting the whole script into a php file and then using the include_once("scriptname.php") command and the same thing happened. So my questiion is how exactly do I cut this script up so I don't get this error anymore?
<?php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
if ($row['pool'] % 2) {
echo "<h4>Result 1</h4>";
$names = get_names(1);
foreach($names as $name) {
echo $name . "<br/>";
}
} else {
echo "<h4>Result 2</h4>";
$names = get_names(0);
foreach($names as $name) {
echo $name . "<br/>";
}
}
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
} ?>
put getNames function in afile.php and include that once at the start. take getNames function out of your current file.
so things goes like this
in first php file (say) you have this code - filea.php
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
}
you second file will have fileb.php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
..... rest of source code excluded. Make sure you get rid of getNames in this file
Now just include as per normal
include 'filea.php'; // include it once only
include 'fileb.php'; // as many times as your wish
or just wrap your code in a function and call that instead
If you are using this script 8 times, then put the entire thing inside a function and call that function 8 times instead of copy pasting.
Related
Ok so I am trying to select values from a table in mysql using a $_post. Below I have included a basic php file without post that seems to be working fine and returns json as expected with the value of username just manually set.
echo "connection";
$connection = mysqli_connect("localhost","root","","simplifiedcoding") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
echo "statement";
$sql = "select * from volley where username = 'cmac '";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
But then when I try to set the value of username with $_Post in another tester file it doesnt work. The value is not being set as seen below. The code is meant to check if the username has been set, then execute the function using the set data.I really dont know where this is going on and I appreciate that this is a common subject matter but I have no idea what is causing this to not be set.
require_once 'connection.php';
class Get_game
{
private $db;
private $connection;
function __construct()
{
$this->db = new DB_Connection();
$this->connection = $this->db->get_connection();
echo "connected";
}
public function get_game_id($username)
{
echo "query";
//$query = "select * from volley";
$query = "select game_id from volley WHERE username = '".$username."'";
echo "result";
$result = mysqli_query($this->connection, $query) or die ("Error in Selecting " . mysqli_error($this->connection));
//create an array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
return json_encode($emparray);
//close the db connection
mysqli_close($this->connection);
}
}
echo "class";
$game = new Get_game();
if (isset($_POST['username'])) {
$username = $_POST['username'];
echo "set";
if (!empty($username)) {
$game->get_game_id($username);
} else {
echo("error");
}
}
I have looked on previous answers on here but nothing seems to work. It is also quite annoying that I have other files with the same syntax but different variables to $_post that are working fine. I included a couple of echos to see where the code was failing as no errors are showing. The code creates the class fine but wont set the values. I will include a file that works fine with the same syntax below. I just can't figure out why one piece of code works fine in one instance and seems to not work at all in another with barely anything being changed.The first snippet of code works fine but I want to be able to execute the querying with a $_post value. I have tried different ways of doing this and none of them seem to work. The code is meant to return json and display it. The first snippet of code does this perfectly. I know that there is something wrong withh the $_post and issett() but i cannot figure it out
i'm trying to connect mysql database server xampp to android studio,i wrote php code and when i run the code ,the result not showing anything.
here is my code:
connection.php
<? php
define ('hostname','localhost');
define ('user','root');
define ('password','1993');
define ('dbname','mat');
$connect = mysqli_connect(hostname,user,password,dbname);
$mysqli->query("set character_set_server='utf8'");
$mysqli->query("set NAMES 'utf8'");
?>
php to fetch data from database:
show.php
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
include 'connection.php';
ShowMat();
}
function ShowMat()
{
global $connect;
$query = "Select * from mat;";
$result = mysqli_query($connect, $query);
$number_of_rows = mysqli_num_rows($result);
$temp_array = array();
if($number_of_rows > 0) {
while ($row = mysqli_fetch_assoc($result))
{
$temp_array[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode(array("mata"=>$temp_array));
mysqli_close($connect);
}
How can I solve this?
I think your REQUEST_METHOD is GET so your code :
if($_SERVER["REQUEST_METHOD"]=="POST"){
so this condition will fail that is why you are not getting any echo.
You can use POSTMAN to test your apis give it a try its really useful.
You change this line mysqli_fetch_assoc to this line while ($row = mysqli_fetch_array($result))
This line is creating problem :if($_SERVER["REQUEST_METHOD"]=="POST").Check what type of data are you sending.Are you sending raw data or structured data.Try isset($_REQUEST['']). Example :
$action=isset($_REQUEST['action'])?$_REQUEST['action']:"";
switch($action)
{
case "ShowMat":
ShowMat();
}
function ShowMat()
{
// code
}
I would like to use custom functions that are all located in one file called functions.php that resides in the includes folder.
A custom function inside functions.php is below and it seems to be working when I remove function nos_check () {} and load up functions.php alone.
function nos_check() {
require_once ('config.php');
mysql_connect($hostname,$dbusername,$dbpassword);
#mysql_select_db($dbname) or die ("Unable to select database");
$sql = mysql_query("SELECT number_of_sites FROM sites WHERE user = '$currentUsername' ");
$row = mysql_fetch_array($sql);
// Assign how many sites the user has into a variable
$how_many = $row['number_of_sites'];
mysql_close();
if ($how_many == 0) {
echo 'You have no sites yet';
} else {
echo 'You have more than one site';
}
}
The file account.php is what's going to call that function:
include "includes/functions.php";
nos_check();
I think I am probably calling the function incorrectly or perhaps I am including the functions file wrong?
SOLUTION:
After hours of messing around and reading more about mysqli etc. I realized that the only problem I actually had was that the script had no idea what $currentUsername was because it was a global variable and functions are not including them automatically in php.
So the error could have been fixed easily by putting global $currentUsername; inside the function nos_check()
Below is a rewritten and hopefully better looking code as well:
function nos_check() {
require 'config.php';
$con = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
global $currentUsername;
$query = "SELECT number_of_sites FROM sites WHERE user = '$currentUsername' ";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
mysqli_free_result($result);
mysqli_close($con);
if ($row[0] == 0) {
echo 'You have no sites yet';
} else {
echo 'You have more than one site';
}
}
So I am trying to create a way of searching my website. I've created a search bar on my index page. You can find this page here: http://seersvillage.com/v1.2/
My search form looks like this:
<form method="post" action="search.php">
<input type="text" name="search" class="search" value="Skeleton" onFocus="this.value=''">
</form>
and I have a functions.php file attatched and this page is also connected to my mysql database. I have content available to be read / searched for all ready.
Here is my search function on functions.php:
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'") or die("Could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'there was no search results!';
} else {
while($row = mysql_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$output .= '<div>'.$eName.' '.$eDesc.'</div>';
}
}
}
}
And the only thing on my search.php (excluding your usual html layout) is as follows:
<?php
include('includes/functions.php');
if(!isset($_POST['search'])) {
header("Location:index.php");
}
?>
and further down in the tags.
<?php print("$output");?>
Now I am pretty new to PHP and MySQL. However I am getting no error on my error.log file, making troubleshooting a little hard for a first timer. Any suggestions? I'm sure it's a very simple mistake, probably just misspelt something, but I just can't see it.
it seems that your php.ini file is set to not display errors. Add these lines of code at the beginning of your code and retry:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
Your doSearch function does not return anything.
return $output;
But $output is only declared within the function. So you'll need to use
print(doSearch());
Either that or declare $output as a global variable, but we don't want to do that :)
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'") or die("Could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'there was no search results!';
} else {
while($row = mysql_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$output .= '<div>'.$eName.' '.$eDesc.'</div>';
}
}
//make sure your function returns $output
return $output;
}
Make sure your function returns the output and then echo out the function:
<?php echo doSearch(); ?>
This is because of how PHP variables are scoped.
...then of course we need to add in all the standard provisos ... don't use the mysql_ library it's almost as dead as a Norwegian Blue. If you use mysqli or PDO you can bind the parameters/values to a prepared statement and not only will that improve efficiency but it'll ensure your input is properly sanitised (far better than that odd ad-hoc preg_replace you're using).
You don't want to kill your script (die) when the query fails - that's just a bit weird, handle the error properly.
There are far better ways to do searches in SQL such as FULLTEXT searches.. or if you can, perhaps implement Apache Solr rather than trying to roll your own.
i am trying to get get the following working nothing is happen when i use the function i am trying to get it to display images
class ItemRes {
//items DB
var $img="";
}
function ShowItemImage($index,$res_a){
if(sizeof($res_a) > $index){
if($res_a[$index] != NULL) {
$cimg = $res_a[$index]->img;
return "<img src='$cimg' width='70' height='70' style='cursor:pointer'></img>";
}
}else{
return "<center class='whitetxt'><strong>Empty</strong></center>";
}
}
$res_array = array();
$idx=0;
$result21 = mysql_query("SELECT * FROM photos WHERE eid='$eid' ORDER BY id DESC") or die (mysql_error());
while ($row21 = mysql_fetch_array($result21)) {
$img_path = $row21['path'];
$obj = new ItemRes();
$obj->img = $img_path;
$res_array[$idx] = $obj;
$idx++;
}
ShowItemImage(0,$res_array)
ShowItemImage(1,$res_array)
Thhere are many issues with this code, so I'll just take them one at the time.
Assuming you initiate the database connection somewhere else the first issue is
the line:
$result21 = mysql_query("SELECT * FROM photos WHERE eid='$eid' ORDER BY id DESC") or die (mysql_error());
Prior to this line you do not set the variable $eid and thus this will only fetch items with eid = ''
Second:
You do not end the last two rows with a semicolon, thus this will produce a fatal error.
Third:
Probably the reason to why you get 'nothing is happen' (wich I interpet as a blank page)
In your function ShowItemImage you return strings but you do nothing with them.
You need to change this:
ShowItemImage(0,$res_array)
ShowItemImage(1,$res_array)
to:
echo ShowItemImage(0,$res_array);
echo ShowItemImage(1,$res_array);
and you will probably start noticing some things on the screen.