I'm currently working on making a few amendments to a website.
The way the website currently works is that the page calls for a require once for the config.inc.php page. The config page also has the SQL call for the what is required to show from the database. While this works fine, I need to create a new page that shows the same table, but the SQL has changed to show different data.
The trouble I’m having is that the config.inc.php page has the SQL data on it that pulls in what is wanted. I want to show a different result on a different page, but the website requires the config.inc.php to show everything. I changed the SQL query to test if what I wanted to show will work and it works a charm, but how do I get this to show without having to mess around with the original SQL command.
Here's the original code;
$config = require_once 'link to admin section';
$db_username = $config['components']['db']['username'];
$db_password = $config['components']['db']['password'];
$db_link = mysql_connect('nosey', $db_username, $db_password) or die(mysql_error());
mysql_select_db('nosey', $db_link);
if ( $_SERVER['REQUEST_METHOD'] == 'GET' ) {
if ( isset($_GET['id']) && $_GET['id'] ) {
$selectSqlJSONString = 'SELECT * FROM vacancies WHERE id = '.$_GET['id'].' ORDER BY created ASC LIMIT 1';
$jsonResult = mysql_query($selectSqlJSONString, $db_link);
$jsonRow = mysql_fetch_object($jsonResult);
if ( !isset($_SERVER['HTTP_X_FANCYBOX']) )
include 'details_ajax_header.php';
include 'filename.php';
if ( !isset($_SERVER['HTTP_X_FANCYBOX']) )
include 'details_ajax_footer.php';
exit;
}
}
$region = '1';
if ( isset($_GET['region']) && $_GET['region'] ) {
$region .= ' AND ' . sprintf('county LIKE "%%%s%%"', mysql_real_escape_string(str_replace('-', ' ',$_GET['region']), $db_link ));
}
$selectSqlString = 'SELECT * FROM vacancies WHERE '.$region.' ORDER BY created DESC';
$result = mysql_query($selectSqlString, $db_link) or die(mysql_error());
$vacancies = array();
while ($row = mysql_fetch_object($result)) {
$vacancies[] = $row;
}
and here's what I would to show only on another page to show a different set of results.
$config = require_once 'link to admin section';
$db_username = $config['components']['db']['username'];
$db_password = $config['components']['db']['password'];
$db_link = mysql_connect('nosey', $db_username, $db_password) or die(mysql_error());
mysql_select_db('nosey', $db_link);
if ( $_SERVER['REQUEST_METHOD'] == 'GET' ) {
if ( isset($_GET['id']) && $_GET['id'] ) {
$selectSqlJSONString = 'SELECT * FROM vacancies WHERE id = '.$_GET['id'].' ORDER BY created ASC LIMIT 1';
$jsonResult = mysql_query($selectSqlJSONString, $db_link);
$jsonRow = mysql_fetch_object($jsonResult);
if ( !isset($_SERVER['HTTP_X_FANCYBOX']) )
include 'details_ajax_header.php';
include 'filename.php';
if ( !isset($_SERVER['HTTP_X_FANCYBOX']) )
include 'details_ajax_footer.php';
exit;
}
}
$region = '1';
if ( isset($_GET['region']) && $_GET['region'] ) {
$region .= ' AND ' . sprintf('county LIKE "%%%s%%"', mysql_real_escape_string(str_replace('-', ' ',$_GET['region']), $db_link ));
}
$selectSqlString = 'SELECT * FROM vacancies WHERE featured = "1" ORDER BY created DESC';
$result = mysql_query($selectSqlString, $db_link) or die(mysql_error());
$vacancies = array();
while ($row = mysql_fetch_object($result)) {
$vacancies[] = $row;
}
Notice how all I want to change is the SELECT * FROM vacancies WHERE featured = "1".
This is all I need! But I want to include this without having to alter the config.inc.php page! (which is where this information is coming from) How do I do it?
Related
I'm trying to get data from mysql and show them using while loop. But problem is inside while loop there is always one less data i'm getting.
Suppose there is two row in my db , but using this code i'm getting only one row. First row always missing. Cant figure out why ! Sharing some of the code.
tried var_dump() , it shows there is right number rows in db
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id");
echo mysql_error();
$data = mysql_fetch_array($ddaa);
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
You are fetching one row before using while loop which you are not using anywhere, thats why you are loosing one row.
$ddaa = mysql_query("SELECT * FROM coupons ORDER BY id") or die(mysql_error());
while ($data = mysql_fetch_array($ddaa))
{
echo $data['id'] ;
}
Try to remove this line:
$data = mysql_fetch_array($ddaa);
The server and database credentials are missing in your code try this one
$server = 'server_name';
$user = 'server_username';
$pass = 'server_password';
$db = 'database_name';
$connection = new mysqli($server, $user, $pass, $db);
$aa = "SELECT * FROM coupons ORDER BY id";
$dd = mysqli_query($connection,$aa); // $connection is the variable which contains server and database credentials;
while ($data = mysqli_fetch_assoc($dd)) {
echo $data['id'];
}
It Will Work For Me. Try This...
<?php
$con=mysql_connect('localhost','root','') or die("could not connect".mysql_error());
mysql_select_db('dbname');
$query = mysql_query("SELECT * FROM Student");
$num_rows = mysql_num_rows($query);
while($row = mysql_fetch_array($query))
{
echo $row['firstname'];
}
echo "<h3>Record Selected successfully\n</h3>";
mysql_close($con);
?>
I am trying to only allow a submission via the form only if a party_id exists in a table using empty, here is my code at the moment it is still allowing everything through even if there is no party_id.
Any help would be great.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='" . $party_id . "'";
$res = mysqli_query($link, $sql);
if(empty($party_id)) { #Were any records found?
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");
A simpler way might be to just check if the query returned any results like this.
if($_SERVER["REQUEST_METHOD"]== "POST") {
$party_id = (int)$_POST["partyid"];
$name = $_POST["name"];
$date = $_POST["date"];
$length = (int)$_POST["length"];
$sql = "SELECT * FROM `party` WHERE `party_id`='$party_id'";
$res = mysqli_query($link, $sql);
if ( mysqli_num_rows($res ) == 0 ) {
print '<p>No Parties with that ID found! please press the back button to select another party</p>';
} else {
$record = mysqli_fetch_assoc($res);
$party_name = $record["party_name"];
$price = $record["price"];
$cost = $price * $length;
$bookable = true;
$sql2 = "SELECT * FROM `reservations`" or die("Unable to connect to database");
So I've been working on a little automatic payment system, and I'm almost done! My customers will get their account upgraded automatically after payment, but I have a slight problem.
I'm currently manually adding their username to an array which changes their username style to distinguish their rank.
I would like to know how to make it retrieve and successful go into an array which will then be called and show their new username.
Here is my code for retrieving usernames and then putting into an array:
$db = new mysqli("localhost", "changed", "changed", "changed")or die(mysqli_error());
$listmembers = $db->query("SELECT * FROM members")or die(mysqli_error());
$names = array();
while($listnames = $listmembers->fetch_assoc()) {
$names[] = "'" . $listnames['username'];
}
$newname = explode("\", ", $names);
Okay and this is what my array code looks like
$members = array($newname);
And this is the code changing their rank:
if(in_array(strtolower($rows['received']), $members)) {
$user = "" . ucfirst($rows['received']) . "";
}
If anyone cold help me, i'd appreciate it.
Turn warnings on to see a few of your mistakes..
$db = new mysqli("localhost", "changed", "changed", "changed")or die(mysqli_error());
$listmembers = $db->query("SELECT * FROM members")or die(mysqli_error());
$names = array();
while($listnames = $listmembers->fetch_assoc()) {
$names[] = $listnames['username'];
}
and later something like this..
if(in_array(strtolower($rows['received']), $names)) {
$user = "<font color=\"lime\"><b>" . ucfirst($rows['received']) . "</b></font>";
}
why you don't fetch array directly from database?
$db = new mysqli("localhost", "changed", "changed", "changed")or die(mysqli_error());
$listmembers = $db->query("SELECT username FROM members")or die(mysqli_error());
$names = $listmembers->fetch_all();
and then:
foreach ( $names as $username ) {
if ( strtolower($rows['received']) == $username[0] ) {
$user = ucfirst($rows['received']);
break;
}
}
I must be missing something simple but I don't see it. The following code works great.
<?php
$res = mysql_connect("localhost", "newuser", "");
mysql_select_db("supplydb");
function filter($data)
{
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}
error_reporting(0);
require("../codebase/grid_connector.php");
$mask5 = filter($_GET["var1"]);
//Get Category ID
$cat = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id='$mask5'");
$rows = mysql_fetch_array($cat, MYSQL_ASSOC);
$array = filter($rows['category']);
//Get Manufactuer ID
$man = mysql_query("SELECT manufacturer_id FROM submissions WHERE submissions.submission_id='$mask5'");
$arows = mysql_fetch_array($man, MYSQL_ASSOC);
$array1 = filter($arows['manufacturer_id']);
function formatting($row)
{
$data = $row->get_value("fda_approved");
if ($data == 1)
$row->set_value("fda_approved", Yes);
else
$row->set_value("fda_approved", No);
}
$gridConn = new GridConnector($res, "MySQL");
function myUpdate($action)
{
$data6 = $action->get_id();
$cat_id = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id ='{$data6}'") or die("Error in query: $query. " . mysql_error());
$rows56 = mysql_fetch_array($cat_id, MYSQL_ASSOC);
$array = filter($rows56['category']);
$status = $action->get_value("approval_status");
$gridConn = new GridConnector($res, "MySQL");
mysql_query("UPDATE submissions SET approval_status='{$status}' WHERE submissions.submission_id='{$data6}'") or die("Error in query: $query. " . mysql_error());
$action->success;
}
$gridConn->event->attach("beforeUpdate", "myUpdate");
$gridConn->event->attach("beforeRender", "formatting");
$gridConn->render_sql("SELECT * FROM submissions JOIN products ON products.product_id = submissions.product_id and submissions.category='$array' and submissions.manufacturer_id='$array1' and submissions.approval_status='0'", "submission_id", "item_number,description,list_price,sugg_price,quantity_per_unit,fda_approved,gpo_contract_number, approval_status");
?>
This code does not
<?php
require("../site_globals/dbc_simple.php");
//$res = mysql_connect("localhost", "newuser", "");
//mysql_select_db("supplydb");
error_reporting(0);
require("../codebase/grid_connector.php");
$mask5 = filter($_GET["var1"]);
//Get Category ID
$cat = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id='$mask5'");
$rows = mysql_fetch_array($cat, MYSQL_ASSOC);
$array = filter($rows['category']);
//Get Manufactuer ID
$man = mysql_query("SELECT manufacturer_id FROM submissions WHERE submissions.submission_id='$mask5'");
$arows = mysql_fetch_array($man, MYSQL_ASSOC);
$array1 = filter($arows['manufacturer_id']);
function formatting($row)
{
$data = $row->get_value("fda_approved");
if ($data == 1)
$row->set_value("fda_approved", Yes);
else
$row->set_value("fda_approved", No);
}
$gridConn = new GridConnector($res, "MySQL");
function myUpdate($action)
{
$data6 = $action->get_id();
$cat_id = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id ='{$data6}'") or die("Error in query: $query. " . mysql_error());
$rows56 = mysql_fetch_array($cat_id, MYSQL_ASSOC);
$array = filter($rows56['category']);
$status = $action->get_value("approval_status");
$gridConn = new GridConnector($res, "MySQL");
mysql_query("UPDATE submissions SET approval_status='{$status}' WHERE submissions.submission_id='{$data6}'") or die("Error in query: $query. " . mysql_error());
$action->success;
}
$gridConn->event->attach("beforeUpdate", "myUpdate");
$gridConn->event->attach("beforeRender", "formatting");
$gridConn->render_sql("SELECT * FROM submissions JOIN products ON products.product_id = submissions.product_id and submissions.category='$array' and submissions.manufacturer_id='$array1' and submissions.approval_status='0'", "submission_id", "item_number,description,list_price,sugg_price,quantity_per_unit,fda_approved,gpo_contract_number, approval_status");
?>
The only difference is the include file at the top and all the include file is is:
<?php
$res = mysql_connect("localhost", "newuser", "");
mysql_select_db("supplydb");
?>
Im fairly new to php but this seems simple and I'm not sure what is getting lost in translation. This works fine on other pages by the way so it must have something to do with the $gridConn = new GridConnector($res, "MySQL"); but I dont know enough to see what. I'm using the DHTMLX javascript library. Could it have something to do with that? Ive tried everything here. Ideas?
Im getting: XML Parsing Error: XML or text declaration not at start of entity Location
Problem is not in the database connection itself, it works correctly and generates data, but result xml corrupted, because some output was started before connector's code.
Check ../site_globals/dbc_simple.php - probably it have some whitespaces|newlines after closing "?>" tag - delete them and it will fix the problem.
Such whitespaces|newlines will not cause harm for HTML pages, but for XML data any extra char at start of document can cause a problem.
I am trying to pass multiple variables in a URL in PHP to GET some info, but I don't think it's working.
$allowedFunctions = array(
'returnAllProducts',
'refreshCurrentProduct'
);
$IDNUM = $_GET[ 'idNum' ];
$functionName = $_GET[ 'func' ];
if( in_array( $functionName, $allowedFunctions ) && function_exists( $functionName ) )
{
$functionName();
}
Then I have the refreshCurrentProduct function:
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
$query = "SELECT `ID` FROM `PRODUCTS`";
$result = mysql_query($query) or die('Query failed:'.mysql_error());
$DB_STOCK = mysql_query("SELECT `STOCK` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_SHORT = mysql_query("SELECT `MYNAME` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_LONG = mysql_query("SELECT `DESCRIPTION` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_PRICE = mysql_query("SELECT `PRICE` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_SHIP = mysql_query("SELECT `SHIPPING` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$ID = mysql_result($result,$IDNUM,"ID");
$STOCK = mysql_result($DB_STOCK,$IDNUM,"STOCK");
$SHORT = mysql_result($DB_SHORT,$IDNUM,"MYNAME");
$LONG = mysql_result($DB_LONG,$IDNUM,"DESCRIPTION");
$PRICE = mysql_result($DB_PRICE,$IDNUM,"PRICE");
$SHIP = mysql_result($DB_SHIP,$IDNUM,"SHIPPING");
echo '
//echo $STOCK, $SHORT, etc....
';
}
The URL I am using is products.php?func=refreshCurrentProduct&idNum=4
In theory, that should display from the row with 4 in it, however, it only displays the info from the first row. If I do a $IDNUM=5 within the function, it will display the 5th row, so something is wrong with how I pass the information.
Also, how do I create (for instance) $STOCK without having to have so much code in $DB_STOCK? Seems like there has to be a better way...
Why don't you do (as others already mentioned , $IDNUM is not in the scope of the function):
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
// If $_GET['idNum'] is not a number use 0
$rowNumber = is_numeric($_GET['idNum']) ? $_GET['idNum'] : 0;
$query = "SELECT ID, STOCK, MYNAME, DESCRIPTION, PRICE, SHIPPING FROM `PRODUCTS`";
$result = mysql_query($query);
if(mysql_data_seek($result, $rowNumber)) {
// The result set has indeed at least $rowNumber rows
$row = mysql_fetch_assoc($result);
echo $row['ID'];
echo $row['STOCK'];
// ... etc ....
}
else {
echo "No such row!";
}
}
No need to hit the database six times! Of course you need to add error handling.
Btw. is the parameter idNum the same as the ID of the record in the database? If so, you can even further simplify:
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
// If $_GET['idNum'] is not a number use 0
$id = is_numeric($_GET['idNum']) ? $_GET['idNum'] : 0;
$query = "SELECT ID, STOCK, MYNAME, DESCRIPTION, PRICE, SHIPPING FROM `PRODUCTS` WHERE ID = $id";
$result = mysql_query($query);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print";
return;
}
$row = mysql_fetch_assoc($result);
echo $row['ID'];
echo $row['STOCK'];
// ... etc ....
}
Take a look at call_user_func.
$functionName = $_GET[ 'func' ];
if( in_array( $functionName, $allowedFunctions ) && function_exists( $functionName ) )
{
call_user_func($functionName);
}
Also, if I'm reading your code right, you could get all of the info in a single query:
$query = "SELECT `ID`,`STOCK`,`MYNAME`,`DESCRIPTION`,`PRICE`,`SHIPPING` FROM `PRODUCTS`";
$result = mysql_query($query) or die('Query failed:'.mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$ID=$row['ID'];
//etc.
}
Your $IDNUM variable is outside the scope of your function. You either need to pass that into your function as a variable or you should be able to set it within the function by setting it inside.
function refreshCurrentProduct() {
$IDNUM = $_GET[ 'idNum' ];
...
}