Display mysql data in php function - php

Ok i got a problem now i want to display a data from the database and display it through a function now how do i do that??
like i have fetched a row from the database and its name is $row_field['data']; and it is correct now i have assigned a variable to it like this $data = $row_field['data']; now if i call it in a function it shows undefined variable even after i assigned it global in the function like this
function fun(){
global $data;
echo $data;
}
but if i assign it a value like 1 or 2 or anything it gets displayed without any error why is that so??

If it displays if you assign it a value like 1 or 2 while still in the global scope, then I can only assume that your database did not return the result you thought it did. Does the database value display if you echo it out outside of the function?

Global is evil. I dont know what you are trying to do, but why dont you just do the query in the function itself?

If you have a column named data and your php call was something like
$result = mysql_query("SELECT data FROM mytable");
while ($row_field = mysql_fetch_assoc($result, MYSQL_NUM)) {
...
}
Then you could replace ... with print $row_field['data'].
Else please provide a snippet of your code where you query the db and retrieve the result.

When learning php try to start with simple things. For example in order to get some data from a database follow the examples from php website.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
If all this goes well go a little further change a little the while loop.
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$myArray[] = $row;
}
mysql_free_result($result);
// now you can start playing with your data
echo $myArray[0];
Small steps...

Related

How to use the same variable in a loop

I have set up a MySql database containing several tables (needed for uploading tons of data that is entered in excel). I would like to use each table name as a variables that automatically updates each time a new table is added to the database. However, I don't know how to prevent PHP from overwriting my $tableName variable in loops. This is what I got so far:
<?php
if (!mysql_connect($host, $username, $password)) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $database";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
$tableName = $row[0];
include('../design.php');
}
?>
In other words: On the frontpage of the website I would like to include data from every single database table. I have organized a framework for extracting that data and presenting it neatly in design.php. However, this file makes use of the $tableName variable for extracting the data and I think that variable is being overwritten at each loop causing the error (only the number one table will be displayed).
Instead, if I just separate the code in their own php objects, then everything works just fine:
<?php
$tableName = tablename1;
include('../design.php');
?>
<?php
$tableName = tablename2;
include('../design.php');
?>
etc..
Can anyone explain to me how this works? Or if there is some smarter way of doing things?
Thanks in advance!
include the design.php file at the beginning of the script. Inside this file, define a function.
function doSomethingWithTableName ($table)
{
// do something with it
}
Then, in your frontend file, you would do this:
$sql = "...";
$result = mysql_query ($sql);
while ($row = mysql_fetch_row($result))
{
$processed_data = doSomethingWithTableName ($row[0]);
// do something with $processed_data
}
Hope this helps.
I've no idea what's inside design.php but instead of including it inside the loop I'd create a function, something like:
function designFunction($tableName){
//put the design.php here
return $something;
}
Now use the designFunction inside your loop
while ($row = mysql_fetch_row($result)) {
$tableName = $row[0];
$someResult = designFunction($tableName);
//etc...
}

PHP: Retrieving two most recent mySQL table entries and storing each in a different variable

Please see the below code.
I am trying to retrieve the most recent two "element_value"s from my database table and then put them into a different table, with one column each. I can do this part with a mysql insert statement if I can get them into variables within the PHP, at the moment I have them being echoed out to the screen instead.
Does anyone know please how I can get them into two separate variables instead?
Thanks!
//Connect to database
$con=mysqli_connect("localhost","user","pass","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL database: " . mysqli_connect_error();
}
//Query the database
$result = mysqli_query($con, 'SELECT element_value FROM wp_formmaker_submits ORDER BY id DESC LIMIT 2;');
//Process the results
if (mysqli_num_rows($result) > 0) {
while ( $dataValue = mysqli_fetch_row($result))
echo "<p>".$dataValue[0]."</p>";
}
Change :
while ($dataValue = mysqli_fetch_row($result))
echo "<p>".$dataValue[0]."</p>";
To this :
$values = null;
while ($dataValue = mysqli_fetch_assoc($result))
{
$values[] = $dataValue['element_value'];
}
print_r($values);
This will store your values in an array, I've added print_r at the end just so you can see the resulting data structure.
If you want to display them in an array again, you can do this :
foreach ($values as $value)
{
echo "<p>".$value."</p>";
}
I've changed your fetch_row method for fetch_assoc, an explanation can be found here : https://stackoverflow.com/a/9540590/2483649

Retrieve MySQL multiple Query with PHP and Process

So far I have this code:
<?php
include('config.php');
$sql = "SELECT senderID as receiverID, msg, time
FROM msg
WHERE senderID = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["receiverID"];
echo $row["msg"];
echo $row["time"];
}
mysql_free_result($result);
?>
Now this simply fetch's the info and stuff, it works the only problem is the processing part. See, I can probably do this so easily in Python, but I am new in PHP, so, if someone could help me, because this is a example of the thing I get returned:
1Hello! How are you?!?!?!876765981admin to user 3574769
Now, I actually was wondering how I would be able to serperate these into its own variable or just print seperately, I am not quiet sure, this is how its suppose to look for a python thing:
firstRow = ['1','Hello! How are you?!?!?!','876765981']
secondRow = ['1','admin to user 3','574769']
Now, I am not so sure about the php structure or code for this.
In php,what you got was:
[
1 => ["receiverId"=>'1',
"msg"=>'Hello! How are you?!?!?!',
"time"=>'876765981'],
2 => ["receivedId"=>'1',
"msg"=>'admin to user 3',
"time"=>'574769']
]
To get the first row
$firstrow = $result[1]
To print it
echo $firstrow["msg"];
The $result is a nested associative array

Not enter while loop after mysql_fetch_assoc

please take a look at this code :
$sql = "SELECT * FROM shop";
$result = mysql_query($sql);
echo $result;
echo "before lop";
while ($xxx = mysql_fetch_assoc($result)) {
echo "inside lop";
echo $xxx['column_name'];
}
echo "after lop";
When I run such code i receive :
Resource id #244
before lop
after lop
It did not enter while lop, and I really don't know why :(
I used before such code and there were no problems.
Can someone help me?
$sql = "SELECT * FROM shop";
$result = mysql_query($sql) or die(mysql_error());
echo mysql_num_rows($result);
Check how many records are present in your shop table. I think shop table is empty.That is why not entering in the while loop.
You can do like this
$count = mysql_num_rows($result);
if($count > 0) {
while ($xxx = mysql_fetch_assoc($result)) {
echo $xxx['column_name'];
}
}
I would guess that the call to mysql_fetch_assoc() has returned false, possibly due to no results being returned from the database, this would cause the while loop to not execute even once. I would check the output of var_dump(mysql_fetch_assoc($result)) to ensure that data has been returned.

PHP - Why is looping between WHILE and DO-WHILE give different results in mysql fetching?

I have one record in a table in my mysql database. I use the following PHP code to retrieve data:
$result = mysql_query($query = "SELECT realname FROM t_user");
if($result)
{
while($data=mysql_fetch_assoc($result)){
echo $data['realname'];
}
}
the results do not appear, but when I use a do-while loop like below:
if($result)
{
$data=mysql_fetch_assoc($result);
do{
echo $data['realname'];
} while($data=mysql_fetch_assoc($result));
}
the results appear, then I tried to add one more record to the table, in the while loop, only shows one data record (the first record), and the do-while loop displays all the data. Why is that? Is it because there is my code wrong?
The code you have shown can't possibly exhibit this problem, so the logical explanation is this:
$result = mysql_query($query = "SELECT realname FROM t_user");
if($result)
{
// Something fetched a row from $result before this statement is run
while($data=mysql_fetch_assoc($result)){
echo $data['realname'];
}
}
Seeing how you're comparing two similar codes, you may have accidentally written something in between the two:
if($result)
{
mysql_fetch_assoc($result);
while($data=mysql_fetch_assoc($result)){
echo $data['realname'];
}
}
$result = mysql_query($query = "SELECT realname FROM t_user");
if($result) { while($data=mysql_fetch_assoc($result)){
echo $data["realname"]; } }
$result = mysql_query($query = "SELECT realname FROM t_user");
var_dump($data);die;
see the result array in your browser. the above while loop should work. check your result.

Categories