I need some help with PHP, i wanna print a value from a COUNT(*) query but it's conditioned, my code:
<?php
require ('../login/conexion.php');
session_start();
if(!isset($_SESSION["id_usuario"])){
header("location: ../login/");
}
//I wanna do this
$consulta_OD = '';
function query_()
{
global $conexion, $consulta_OD;
$sql = 'SELECT COUNT(*) as total from gok_registro WHERE estado=3';
return $conexion->query($sql);
}
$consulta_OD = query_OD();
$costo_OD = $consulta_OD->fetch_assoc();
echo $costo_OD['total'];
?>
By the way, the connection to a BD is good since my code works, without the lines after the "//i wanna do this" comment. The query also works in the console.
The last line is to print the query in another part of the document, any help?
Your SQL request looks good.
But:
the function query_ is never call
the function query_OD not exist
global $consulta_OD; is not used in the function query_ so useless
If you rename query_ by query_OD your code should work
Related
Am getting an error of prepared statement "my_query7" already exists, i call this function each time a user tries to update table leader_info in the database, i have gone through the documentation for pg_prepare and i don't understand what is meant by it should only be run once. code snippets will be of help. Thanks.
function add_leader_country($user_id,$l_country)
{
global $connection;
$query = pg_prepare($connection,"my_query7","update leader_info set l_country = $1 where user_id = $2 and status < 9");
$result = pg_execute($connection,"my_query7",array($l_country,$user_id));
if(!$result)
{
echo pg_last_error($connection);
}
else
{
echo "Records created successfully\n";
}
$row = pg_affected_rows($result);
return $row;
}
Prepare execute does not permit duplicate naming, so that is your error.
A query should only be prepared once, for example, in a cycle for the preparation state must be set out of the for and its execution in the for.
$result=$pg_prepare($connection,"my_query7",$query);
for($id=1;$id<3;$id++){
$result=pg_execute($connection,"my_query7",array($l_country,$user_id));
...
}
In your case using a functio that use the prepare and execute multiple times it's a problem.
What are you trying to accomplish with this function dispatches more code like where you are calling the function. This way I might be able to help you.
If you want to use functions I would use this method
Exemple from https://secure.php.net
<?php
function requestToDB($connection,$request){
if(!$result=pg_query($connection,$request)){
return False;
}
$combined=array();
while ($row = pg_fetch_assoc($result)) {
$combined[]=$row;
}
return $combined;
}
?>
<?php
$conn = pg_pconnect("dbname=mydatabase");
$results=requestToDB($connect,"select * from mytable");
//You can now access a "cell" of your table like this:
$rownumber=0;
$columname="mycolumn";
$mycell=$results[$rownumber][$columname];
var_dump($mycell);
If you whant to use preaper and execute functions try to create a function that creates the preparations only once in a session. Do not forget to give different names so that the same error does not occur. I tried to find something of the genre and did not find. If you find a form presented here for others to learn. If in the meantime I find a way I present it.
I have a function to process info from a database. This is called multiple times in a page. And I don't want to query the database every time. So I put the query outside. If I do that, the function doesn't work. I know this can be done because, there was a similar question somewhere in SO. But that addressed a different situation. I don't know what is wrong here. Any help will be greatly appreciated.
If I put all this code into a separate test file including the conn file and query, it works. But in my main page, where I have the functions.php included first, then conn.php and then the query and then the display code called by js fadein event, the $result refuses to work inside the function
EDIT : This code has been cleaned up as per comments received (globals replaced with variables passed to the function and variable names rationalised)
function total($item,$result,$val){
global $totRate;
while($getRates=$result->fetch_assoc()){
$gotItem= strtolower(preg_replace('/[^(\x20-\x7F)]*/',"",$getRates['item']));
$gotItem=str_replace(array("_"," ","/"),"",$gotItem);
if($item==$gotItem){
$rate= $getRates['rate'];
$totRate=$val*$rate;
return $totRate;
}
}
}
The Result Call PHP file
$query = "SELECT * FROM rates ORDER BY item";
$result = $orderdb->query($query)
if (isset($_POST[$itemname]) && !empty($_POST[$itemname])) {
$val=$_POST[$itemname];
total($itemname);
echo $totprate;
} else {
echo "0";
}
I am writing this with the assumption that your SQL is working but are having problems displaying what you want - this may help. The code below saves your $result variable from your query and then passes it into the total function as a second parameter. Previously you were returning $totprate from total but you were not saving it anywhere - it is now saved to the $totprate variable.
Note: I cannot see $orderdb anywhere in your code, I'm assuming you have that in your file and that it is working.
function total($item, $result){
global $val;
global $pid;
global $pitem;
global $prate;
global $totprate;
global $gotitem;
global $getratess;
// global variable for $result removed so it doesn't overwrite variable passed to function
while($getratess=$result->fetch_assoc()){
$gotitem= strtolower(preg_replace('/[^(\x20-\x7F)]*/',"",$getratess['item']));
$gotitem=str_replace(array("_"," ","/"),"",$gotitem);
if ($item==$gotitem) {
$pid=$getratess['id'];
$pitem= $getratess['item'];
$prate= $getratess['rate'];
$totprate=$val*$prate;
return $totprate;
}
}
}
$query = "SELECT * FROM rates ORDER BY item";
$result = $orderdb->query($query);
if (isset($_POST[$itemname]) && !empty($_POST[$itemname])) {
$val=$_POST[$itemname];
$totprate = total($val, $result); // pass itemname as first parameter and result array as second parameter and save it to the $totprate variable
echo $totprate;
} else {
echo "0";
}
Let me know if this helps.
I am creating a library for PHP scripts and I want to be able to show php code on a html webpage.
I have looked at using highlight_file(); but this will show the whole page
For example, If I have a page called code.php which has an sql query on ( select code from table where sequence = $_GET["id"] ) - example then I use
Highlight_file('code.php?id=123');
This will work but will also show the select query which I do not want to show. I would just want to show the code from the database (code column)
How can I display just the code from the database with the correct colours and formatting etc
UPDATE:
<?php
$conn=mysql_connect("localhost","charlie_library","Pathfinder0287");
mysql_select_db("charlie_library",$conn);
function highlight_code_with_id($id, $conn)
{
$query = "select * from library_php where sequence = '$id' ";
$rs = mysql_query($query,$conn);
$code = mysql_fetch_array($rs);
echo highlight_string($code["code"]);
}
// and, use it like this:
highlight_code_with_id($_GET['id'], $conn);
?>
I have tried the above code, which is just displaying the code in plain text
use highlight_string function, like this:
<?php
highlight_string($code);
?>
where $code is the code you have obtained from your SQL query.
You can create a function around this (something along the following lines):
<?php
function highlight_code_with_id($id, $mysqli) {
$query = $mysqli->query("select code from table where sequence = '$id'");
$code = current($query->fetch_assoc());
return highlight_string($code);
}
// and, use it like this:
echo highlight_code_with_id($_GET['id'], $mysqli);
UPDATE:
Your code is a bit incorrect, you can use:
<?php
$conn=mysql_connect("localhost","charlie_library","Pathfinder0287");
mysql_select_db("charlie_library",$conn);
function highlight_code_with_id($id)
{
$query = "select * from library_php where sequence = '$id' ";
$rs = mysql_query($query);
$code = mysql_fetch_assoc($rs); // change is in this line
echo highlight_string($code["code"]);
}
// and, use it like this:
highlight_code_with_id($_GET['id']);
?>
Note that you do not need to include $conn in your function, it can be ommitted. Also, note that you should use mysqli->* family of functions, since mysql_* family has been deprecated.
Perhaps this would work for you.
This post is originally for HTML, but the answer linked above shows an example using PHP.
I'm currently pulling the data from MySQL Database with the current code Example 1
function User_Details($uid){
$uid = mysql_real_escape_string($uid);
$query = mysql_query("SELECT uid,password,email,nickname,username,profile_pic,friend_count FROM users WHERE uid='$uid' AND status='1'");
$data = mysql_fetch_array($query);
return $data;
}
I'd like to use this query across multiple PHP pages without having to write a foreach loop for every PHP file.
Currently I have it inside a class called class Wall_Updates { }, and I try to print it with the following code: Example1 : < ?php echo $data['username']; ? >.
The class Wall_Updates is being called on the header which should also include the User_Details, so the only issue is how do I print with just the following PHP example I gave above without the need of a loop.
The class words with single fielded queries such as Example 2 $face = $Wall->Profile_Pic($msg_uid); and if I echo $face it'll show my current Profile_Pic which is a single query.
Example 3 of how I don't want to do as it's very messy.
<?php
if ($uid) {
$updatesarray = $Wall->Updates($uid);
}
if ($updatesarray) {
foreach ($updatesarray as $data) {
$username = $data['username'];
?>
#HTML CODE GOES HERE
<?php } ?>
So I'd like my query to pull multiple fields from users and use it across any page without a foreach.
PS: I'm sorry if it's not making sense, I've been complained a lot for not showing what I've tried and I hope to not get complained about it this time, I appreciate for looking at my question.
you need to issue the "or die" sql command EVERYWHERE otherwise you have no idea why it failed.
http://pastie.org/7897405
you have a column name wrong (look at the last line of the pastie
also, get off of the mysql_ stuff and get into pdo. you should know better chump !
I am trying to write a PHP function which gets the sum of values in 1 column of a table. MY SQL statement works just fine. However, when I write my function and attempt to echo the variable into my HTML code, it returns '0'.
Here is my function:
function get_asset_value($org_ID) {
global $db;
$query = "SELECT SUM(asset_value) FROM assets
WHERE org_ID = '$org_ID'";
$asset_sum = $db->query($query);
$asset_sum = $asset_sum->fetch();
return $asset_sum;
In my HTML, I have the following:
<?php echo $asset_sum; ?>
I'm not sure if this has to do with the "fetch" portion of my function. I really don't know what fetch does but I tried copying/modifying this piece of code from a working function (which doesn't return the sum, but it is a select statement).
Thank you!
In addition to
SELECT SUM(asset_value) AS the_sum FROM assets WHERE ord_ID = '$ord_ID';
...
return $asset_sum['the_sum']
by Brad,
you better do
$safer = mysql_real_escape_string($org_ID);
then do,
SELECT SUM(asset_value) AS the_sum FROM assets WHERE ord_ID = '$safer';
...
return $asset_sum['the_sum']
SELECT SUM(asset_value) AS the_sum FROM assets WHERE ord_ID = '$ord_ID';
...
return $asset_sum['the_sum'];
The issue is, you are returning an entire record, rather than just the field you want.
Also, judging by the way you are inserting that ID in your query, I suspect you are open to SQL injection. You should really learn to do prepared queries with PDO.