MySQL Select Query & use it globally(Multiple PHP pages) - 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 !

Related

Print a Conditioned COUNT query with PHP

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

Php postgresql error, prepared statement already exists

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.

Migrating to MYSQLI : How to fitch result of query in while(list()) method instead of foreach() method?

I have very large PHP website, about 3000+ PHP files, all files are linked to main class named (lib.inc.php) which includes :
config.inc.php
users.inc.php
mysql.inc.php
I am doing quick migration from MYSQL to MYSQLI , and I am planning to do very minimal changes in MYSQL part, I did found many MYSQLI Classes which I can replace it with my old mysql.inc.php , but thats was not the big part of the job ... The big part is I have to change the code of the queries in almost each PHP file, I have around 3 to 5 MYSQL Queries which is currently in the following format structure :
$query = "
SELECT USER_ID,USER_NAME,USER_EMAIL,USER_LEVEL,USER_REG_DATE,USER_LAST_ACCESS,USER_LAST_IP
FROM USERS_TBL
LIMIT 0,20
";
$sth = $dbh -> do_query($query);
while (list($USER_ID,USER_NAME,USER_EMAIL,USER_LEVEL,USER_REG_DATE,USER_LAST_ACCESS,USER_LAST_IP) = $dbh -> fetch_array($sth)) {
// Do some thing with the result and print it
}
IN mysql.inc.php : I have the following Functions related to the above code :
function do_query($query) {
$this->sth = mysql_query($query,$this->dbh);
return $this->sth;
}
function fetch_array($sth) {
$this->row = mysql_fetch_array($sth);
return $this->row;
}
My question is :
How to migrate the above code from MYSQL to MYSQLI keeping in mind that I dont want to change the structure of loop part , as I want to all my while loops remain the same in all 3000+ PHP files , specially this part :
while (list($USER_ID,$USER_NAME,$USER_EMAIL,$USER_LEVEL,$USER_REG_DATE,$USER_LAST_ACCESS,USER_LAST_IP) = $dbh -> fetch_array($sth)) {
// Do some thing with the result and print it
}
In the current MYSQLI classes which I found in the net , all statements witch dealing with fetching array it has the following structure:
/**
* Retrieve results of a standard query
*/
$query = "SELECT USER_ID,USER_NAME,USER_EMAIL,USER_LEVEL,USER_REG_DATE,USER_LAST_ACCESS,USER_LAST_IP
FROM USERS_TBL
LIMIT 0,20";
$results = $database->get_results( $query );
foreach( $results as $row )
{
$USER_ID = $row['USER_ID'];
$USER_NAME = $row['USER_NAME'];
$USER_EMAIL = $row['USER_EMAIL'];
$USER_LEVEL = $row['USER_LEVEL'];
$USER_REG_DATE = $row['USER_REG_DATE'];
$USER_LAST_ACCESS = $row['USER_LAST_ACCESS'];
$USER_LAST_IP = $row['USER_LAST_IP'];
}
Notice that in mysqli version I have to assign each variable to another one so I can use them in different places in the code, but in my old code , I just need to type the variable inside the while (list(....)) methods .. instead of making each variables in separate line....changing the while(list()) methods to foreach() method will cost me hundreds of hours to apply this changes in my whole codes of 3000+ PHP files 600,000 lines of code .
So , How to apply current methods code in mysqli version ???
if I can get example of fetching result in while(list()) way using MYSQLI ,I will be much appreciated.

Problems getting MySql data into an index using Zend_Search_Lucene

Trying to use Zend_Search_Lucene to search a MySql database and display the results. Running the following code and can't figure out why I'm not getting any info into my index. Quite new with PHP, MySql and Zend but I've spent the last week trying to figure this out on my own and have exhausted every resource I could find. Anyway, I echoed what's coming out of my database to make sure my query worked which seems to be OK. It also creates the index files just fine but when I've taken a look at it with the Luke Toolbox I get nothing but a list of the fields created filled with gooseggs. Just to make sure I'm using that correctly I found some code using Zend_Feed and ran that through Lukes and got all kinds of results. Also able to get results from that same code on my result test page but getting 0 when using the code below. Seems I can't get the database info indexed although the count tells me that 5 documents have been indexed (which is the number of rows I have in my database table) and I'm not getting any errors. The library script is just an autoloader script and where I set up my db connection which I've confirmed works as well. Although it's likely I'm missing the obvious or demonstrating what a novice I truly am, any help would be much appreciated.Thanks.
<?php>
require_once('scripts/library.php');
require_once ('Zend/Search/Lucene.php');
$index = Zend_Search_Lucene::create('./docindex');
$sql = ('SELECT * FROM news');
foreach ($db->query($sql) as $row){
echo $row ['author'];
echo $row['headline'];
echo $row ['source'];
}
foreach ($row as $document){
$document = new Zend_Search_Lucene_Document ();
$document->addField(Zend_Search_Lucene_Field::Text ('author', $docAuthor));
$document->addField(Zend_Search_Lucene_Field::Text ('headline', $docHeadline));
$document->addField(Zend_Search_Lucene_Field::Text ('source', $docSource));
$document->addField(Zend_Search_Lucene_Field::Unstored ('contents', $docStory));
$index->addDocument($document);
}
$index->commit();
echo $index->count()." documents have been indexed.\n";
?>
It looks like you had an extra foreach() that wasn't really doing anything and I couldn't see where your data variables were assigned, try this it should be pretty close:
<?php
require_once('scripts/library.php');
require_once ('Zend/Search/Lucene.php');
$index = Zend_Search_Lucene::create('./docindex');
$sql = ('SELECT * FROM news');
foreach ($db->query($sql) as $row) {
echo $row ['author'];
echo $row['headline'];
echo $row ['source'];
$document = new Zend_Search_Lucene_Document ();
//you use an unindexed field for the id because you want the
//id to be included in the search results but not searchable
$document->addField(Zend_Search_Lucene_Field::unIndexed('id', $row['id']));
$document->addField(Zend_Search_Lucene_Field::Text('author', $row ['author']));
$document->addField(Zend_Search_Lucene_Field::Text('headline', $row['headline']));
$document->addField(Zend_Search_Lucene_Field::Text('source', $row ['source']));
$document->addField(Zend_Search_Lucene_Field::Unstored('contents', $row['docStory']));
$index->addDocument($document);
}
$index->commit();
echo $index->count() . " documents have been indexed.\n";
?>

Strange error "sqlsrv_fetch_array(): 16 is not a valid ss_sqlsrv_stmt resource" since ReturnDatesAsStrings

I am using the sqlsrv driver for IIS so I can connect to a MS SQL server in PHP.
I've managed to convert a lot of my original mysql_ code and all going well, until I tried to SELECT some DateTime fields from the database. They were coming back as Date objects in PHP rather than strings, I found the fix which is adding this to the connection array:
'ReturnDatesAsStrings'=>1
Since doing that though my code is broken when trying to populate my recordset:
function row_read($recordset) {
if (!$recordset) {
die('<br><br>Invalid query :<br><br><bold>' . $this->sql . '</bold><br><br>' . sqlsrv_error());
}
$rs = sqlsrv_fetch_array($recordset);
return $rs;
}
The error is: sqlsrv_fetch_array(): 16 is not a valid ss_sqlsrv_stmt resource
There is such little amount of help on that error in Google so this is my only shot! I just don't get it.
row_read is called from within a While: while ($row = $db->row_read($rs)) {
Any ideas?
Just to add more code and logic - I do a simple SELECT of all my orders, then as it loops through them, I do another 2 SELECT's on the orders table then the customer table. It's falling down when I try these extra 2 'gets':
$this->db->sql = "SELECT * FROM TicketOrders";
$rs = $this->db->query($this->db->sql);
$this->htmlList->path("skin/search.bookings");
if ($this->db->row_count != 0) {
while ($row = $this->db->row_read($rs)) {
// Load the order row
$this->TicketOrders->get($this->db, $row['Id']);
// Load the customer row
$this->Customers->get($this->db, $row['CustomerId']);
Did you pass this resource variable by another function? If yes, you can try by executing the sqlsrv_query and executing sqlsrv_fetch_array in one function; don’t pass the ss_sqlsrv_stmt resource by another function. Hope that it will help.
Does your program involves a nested query function?
If so, the next question is: are you opening the same database in the inner query function?
Try these changes:
comment out the lines that open the database, including the { and } that enclose the function,
change the name of connection and array variables between the outer loop and the inner loop.
In other words, the outer loop may have:
$tring = sqlsrv_query($myConn, $dbx_str1);
while( $rs_row1 = sqlsrv_fetch_array($tring, SQLSRV_FETCH_ASSOC))
and the inner loop would have:
$tring2 = sqlsrv_query($myConn, $dbx_str2);
while( $rs_row2 = sqlsrv_fetch_array($tring2, SQLSRV_FETCH_ASSOC))
sqlsrv_fetch_array need a ss_sqlsrv_stmt resource. There must be something wrong with your SQL.

Categories