I'll try to be as specific as possible.
I have a database table from which I'm going to print information. The easiest way to do this is by doing something like this:
$con=mysqli_connect("server","user","pass","dbname");
$users_result = mysqli_query($con,"SELECT * FROM table blabla");
while($row = mysqli_fetch_array($users_result))
echo $row['column_to_echo'];
}
mysqli_close($con);
If this query returned one row, with an address, the outcome on the screen would be something like this "My street 14" Right? And that's how it works as well. So that's great. Exactly what I want.
HOWEVER:
I need to have these SQL queries in functions, because the queries are dynamic based on who's loading the page.
So a function like that looks something like this;
function getUserAddress($userid)
{
$con=mysqli_connect("server","user","pass","dbname");
$users_result = mysqli_query($con,"SELECT * FROM table blabla");
while($row = mysqli_fetch_array($users_result)) {
return $row['column_to_echo'];
}
mysqli_close($con);
}
And I use it by doing this:
<?php $address = getUserAddress(current_user_id); echo $address; ?>
So in this case, we can safely assume that the string being returned by the function is the same string as used in my first example, right? (given the correct ID is being sent into the function).
This is NOT the case.. I would only get the first word on my screen. Meaning the function isn't returning the full string, and I have no idea why.
On my screen it would appear as "My", instead of "My street 14". And that is my problem.
Does anyone have any clue as to why this is happening?
Rewrite your function like this
function getUserAddress($userid)
{
$con=mysqli_connect("server","user","pass","dbname");
$users_result = mysqli_query($con,"SELECT * FROM table blabla");
while($row = mysqli_fetch_array($users_result)) {
$str.=$row['column_to_echo']." ";
}
mysqli_close($con);
return($str);
}
Problem :
You were actually making use of a return inside the while loop which just returned the first value.
Try this instead:
function getUserAddress($userid)
{
$con=mysqli_connect("server","user","pass","dbname");
$users_result = mysqli_query($con,"SELECT `column` FROM table blabla");
$row = mysqli_fetch_row($users_result)
mysqli_close($con);
return $row;
}
Let me know if that works.
Related
I have a table wherein I need to get all the data in one column/field, but I can't seem to make it work with the code I have below:
$con=mysqli_connect("localhost","root","","database");
$result = mysqli_query($con,"select * from client");
$row = mysqli_fetch_array($result111);
echo $row['name'];
With the code above, it only prints one statement, which happens to be the first value in the table. I have 11 more data in the table and they are not printed with this.
You need to loop through the recordsets .. (A while loop will do) Something like this will help
$con=mysqli_connect("localhost","root","","database");
$result = mysqli_query($con,"select * from client");
while($row = mysqli_fetch_array($result))
{
echo $row['name'];
}
The mysqli_fetch_array() function will return the next element from the array, and it will return false when you have ran out of records. This is how you can use while loops to loop through the data, like so:
while ($record = mysqli_fetch_array($result)) {
// do something with the data...
echo $record['column_name'];
}
I've got several queries I want to run on a single page. I obviously don't want to put the actual queries in my template file, so I think what I want to do is construct a function and call it wherever I want the query results to show up. Right?
So, for example, I'll have <?php sidebar_query()?> in the sidebar, <?php footer_query()?> in the footer, etc.
So, I just make a file called functions.php, do PHP include, and put something like this in there?
<?php
function sidebar_query(){
$query = ("SELECT sidebarposts FROM table;");
return $query;
}
?>
or do you use echo and not return anything?
<?php
function sidebar_query(){
$query = ("SELECT sidebarposts FROM table;");
echo $query;
}
?>
Along the exact same line, I'd like to count the results that get returned, and display a 'There were X posts returned!' message below. Seems like it would make sense to put this in a function too. How would I make a 'generic' function that I could reuse for each query?
<?php
function number_of_results(){
$num_rows = mysql_num_rows();
echo $num_rows;
}
?>
I'd be extremely grateful if someone could give me the theoretical gist of what I should be trying to achieve here.
Thanks for helping a beginner.
Terry
I think I get what you mean.
Return the value instead like this
function sidebar_query(){
$rValue = "";
$query = ("SELECT sidebarposts FROM table;");
$result = mysql_query($query);
if ($row = mysql_fetch_array($result)){
$rValue = $row['sidebarposts'];
}
return $rValue;
}
Now you can echo sidebar_query(); or whatever you want to do with it.
By doing ("SELECT sidebarposts FROM table;")you're not actually doing anything, you just have a string stored as a variable.
A simple example is
function sidebar_query()
{
$query = mysql_query("SELECT title,post FROM table;"); //query the db
$resArr = array(); //create the result array
while($row = mysql_fetch_assoc($query)) { //loop the rows returned from db
$resArr[] = $row; //add row to array
}
return $resArr;
}
Then to use it you can do
$sideBarPosts = sidebar_query(); //get the result array
foreach($sideBarPosts as $post) { //loop the array
echo '<h1>'. $post['title']. '</h1>';
echo '<p>'. $post['post']. '</p>';
}
EDIT. I see you want to let the function print it directly, you can do that instead of returning the array, if you like.
function sidebar_query(){
$query = mysql_query("SELECT * FROM table;");
$result = $conn->query($query);
$resArr = array(); //create the result array
while($row = $result->fetch_assoc()) { //loop the rows returned from db
$resArr[] = $row; //add row to array
}
return $resArr;
}
and that :
$sideBarPosts = sidebar_query(); //get the result array
foreach($sideBarPosts as $post) { //loop the array
echo '<h1>'. $post['title']. '</h1>';
echo '<p>'. $post['post']. '</p>';
}
// Set Connection with database
$conn = mysql_pconnect($servername,$username,$password) or die("Can not Connect MySql Server!");
// Select database you want to use
mysql_select_db($databasename,$conn) or die("Can not select Data Base!");
// When you want to query SQL inside php function, you need to pass connection($conn) to the function as below.
function sidebar_query($condb)
{
$strSql = "SELECT sidebarposts FROM table";
$result = mysql_query($strSql,$condb);
return $result;
}
// Call function
sidebar_query($conn);
This is work for me as i use with my webpage.
Read the php doc on how to run mysql query.
Yay you have the query, now you need to do something with it:
mysql_query($query); for example might work for you :-)
You want to run the query and return the result in whatever format you want to use in your template.. so for the raw number you want to return an integer, for the sidebar posts return an array of posts OR the mysql result.
You should make the "'There were X posts returned!' " thing a completely different function which you can pass in an integer an an optional string. This way you can reuse it for a ton of stuff. for example:
function format_nb_records($nb_records, $format = 'There were %s posts returned!'){
return sprintf($format, $nb_records);
}
Although in this case i dont think there is really enough extra logic to warrant wrapping it in a function. I would probably just do this directly in my template.
A good example of where something like this is useful is if you want to do "time in words" functionality like "Yesterday" or "10 minutes ago" then you would pass in the time calculate which string to use, format it and return it.
Although in this case i dont think there is really enough extra logic to warrant wrapping it in a function. I would probably just do this directly in my template.
A good example of where something like this is useful is if you want to do "time in words" functionality like "Yesterday" or "10 minutes ago" then you would pass in the time calculate which string to use, format it
You need to pass database connection name to function like this,
You already have a connection name, mine is $connect_name
$connect_name= mysql_connect( 'host', 'user', 'password');
function getname($user,$db){
$data= mysql_query("SELECT $user...", $db);
//your codes
//return bla bla
}
echo getname("matasoy",$connect_name);
This work for me.
I also use this for medoo.min sql system. You can use medoo with functions like this;
function randevu($tarih,$saat,$db){
$saat_varmi = $db->count("randevu",array("AND"=>array("tarih"=>$tarih,"saat"=>$saat)));
if($saat_varmi>0)
return 3;
else
return 2;
}
have a nice day, Murat ATASOY
I'm writing a PHP file which will putt from multiple table rows, data which it must echo on one page.
I wrote a function command because I a loop wont work as the information isn't outputting in the same manner every time.
here is how it looks so far.
include("dbconnect.php");
function get_table_data($id)
{
$row = mysql_query('SELECT row FROM table WHERE id = '.$id.'');
$row2 = mysql_fetch_array($row);
};
$sss = 18; // this is the ID
echo get_table_data($sss);
My issue is that nothing echos and I have no errors
first of all, you need to return something:
function get_table_data($id) {
$row = mysql_query('SELECT row FROM table WHERE id = '.$id.'');
return mysql_fetch_array($row);
}
then, you need to access the row:
$result = get_table_data($sss);
echo $result['row'];
Hope this helps!
Your function get_table_data should return some value to be echoed in your statement echo get_table_data($sss);
I use a mysql database. When I run my query I want to be able to put each row that is returned into a new variable. I dont know how to do this.
my current code:
<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");
$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$solution=$row['solution'];
}
?>
The thing is that check num rows can return a row of an integer 0-infinity. If there are more solutions in the database how can I assign them all a variable. The above code works fine for 1 solution, but what if there are more? Thanks.
You can't give each variable a different name, but you can put them all in an array ... if you don't know how this works I suggest looking at a basic tutorial such as http://www.w3schools.com/php/php_arrays.asp as well as my code.
A very simple way (obviously I haven't included mysql_num_rows etc):
$solutions = array()
while($row = mysql_fetch_assoc($result)) {
$solutions[] = $row['solution'];
}
If you have three in your result solutions will be:
$solutions[0] -> first result
$solutions[1] -> second
$solutions[2] -> third
<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");
$solution = array();
$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$solution[]=$row['solution'];
}
?>
How can I avoid duplicate return data with MYSQL with autosuggest with this code?
Thank you so much for helping
<?php
include('conn.php');
$str = strtolower($_GET['content']);
if(strlen($str))
{
$sel = mysql_query("select * from Streams where title like '".trim($str)."%'");
if(mysql_num_rows($sel))
{
echo "<table border =\"0\" width=\"100%\">\n";
if(mysql_num_rows($sel))
{
echo "<script language=\"javascript\">box('1');</script>";
while($row = mysql_fetch_array($sel))
{
$country = str_ireplace($str,"<b>".$str."</b>",($row['title']));
echo "<tr id=\"word".$row['title']."\" onmouseover=\"highlight(1,'".$row['title']."');\" onmouseout=\"highlight(0,'".$row['title']."');\" onClick=\"display('".$row['title']."');\" >\n<td>".$country."</td>\n</tr>\n";
}
}
echo "</table>";
}
}
else
{
echo "<script language=\"javascript\">box('0');</script>";
}
?>
What I can see in your code is that there is only a single field - title - from the SQL resultset that you are using in the PHP code. So why not instead write your query as:
"SELECT DISTINCT `title`
FROM Streams
WHERE title like '".trim($str)."%'"
Or perhaps if you can't change the query, you may store the title in a PHP array and then run array_unique on it to avoid duplicates before writing them to HTML.
From looking at your code, it seems like you're only using the "title" field from your database. You could do this:
$sel = mysql_query("SELECT DISTINCT title FROM Streams WHERE title LIKE '".mysql_real_escape_string(trim($str))."%'");
As per the MySQL documentation:
The [...] DISTINCT options specify
whether duplicate rows should be
returned. [...] DISTINCT specifies
removal of duplicate rows from the
result set. It is an error to specify
both options.
Ideally you need to select distinct elements
mysql_query("SELECT DISTINCT(title) FROM Streams WHERE title LIKE '".mysql_real_escape_string(trim($str))."%'");
Ofcourse if any reason you cant do that,
Put the data in a array and check if it was previously added to prevent duplication, define array outside the while
$data = array()
if (!in_array($row["title"], $data)){
\\do your thing
array_push($data, $row["title");
}