I am working in php in which i am using mysql.
This is my function which is returning result in json format.
function getTiming($placeId) {
$sql = "SELECT * from place_timing where placeId='$placeId'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
echo '['.json_encode(array('placeId' => 0)).']';
//this is for null result
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
echo json_encode($records); //this concerts in json
}
}
output of this function is like this:-
[{"placeId":"31","sun_open_time":"00:00:00","sun_close_time":"00:00:00","mon_open_time":"00:00:00","mon_close_time":"23:00:00","tue_open_time":"00:00:00","tue_close_time":"00:00:00"}]
But I want to show only hour:minutes. means I don't want to show seconds.
please suggest me how can I change my above function so I can show only hour:minutes.
Thank you in advance.
There are many ways to do it, the "cleanest" would be to specify the columns in the SELECT clause and pass the dates with DATE_FORMAT() like this: DATE_FORMAT(sun_open_time, '%H:%i').
Adjust your query to select the actual fields, rather then * and then use TIME_FORMAT() on the time fields, like:
SELECT TIME_FORMAT(`sun_open_time`, '%H %i') AS `opentime`;
That will return the desired values directly from the query without any PHP hacks.
It seems your fields of table place_timing (sun_open_time, sun_close_time and so on..) have only hh:mm:ss formated time. so you have to use SUBSTRING() function of MySql.
So you query could be as follows.
$sql = "SELECT SUBSTRING(sun_open_time,1,5),
SUBSTRING(sun_close_time,1,5), SUBSTRING(mon_open_time,1,5),
SUBSTRING(mon_close_time,1,5),
SUBSTRING(tue_open_time,1,5),SUBSTRING(tue_close_time,1,5) from
place_timing where placeId='$placeId'";
Related
I am trying to get the values using the below code
$query="select document_id from certificate_documents where certificate_id=$certificate_id";
$res = db_query($query);
$row_count = db_num_rows($res);
$doc_id=array();
for($j=1;j<=$row_count;$j++){
$document_copy = db_fetch_object($res);
$doc_id[$j]=$document_copy->document_id;
print "$doc_id[$j]";
}
But the above code print nothing.
I have to use this value into another query . How can i get this? please help.
You can try this:
$query="select document_id from certificate_documents where certificate_id=$certificate_id";
$res = db_query($query);
$doc_id=array();
while($document_copy = db_fetch_object($res)) {
$doc_id[]=$document_copy->document_id;
}
print_r($doc_id);
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.
I have a table in SQL, it contains around 100 rows.
I select it within PHP with SELECT * FROM table.
I didn't use offset nor limit. My question now is, is there are way to manipulate the returned result using only PHP to display only like 24 rows from the table?
What should I try?
The general format for getting rows from the DB looks like this:
while ($row = mysql_fetch_assoc($rs)) {
echo $row['column_name'] . "\n";
}
You'll want to modify it like this:
$limit = 24;
while ($limit-- && $row = mysql_fetch_assoc($rs)) {
echo $row['column_name'] . "\n";
}
Well, I guess now that the oracle tag was added, I'll add the oracle answer.
$rows = array(row, row, row, ...); // from oracle sql results
$first_24_rows = array_slice($rows, 0, 24);
You can control the number of rows return in the oracle SQL itself. Put something like this in the where clause:
and rownum <= 23
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
Ok I have a table with a few fields. One of the fields is username. There are many times where the username is the same, for example:
username: bob
password: bob
report: 1
username: bob
password: bob
report: 2
I did a SQL statement to select * where username='bob'; but when I do the following PHP function, it will only return the last result:
$thisrow = mysql_fetch_row($result);
I need to get every field from every row. How should I go about doing this?
$mainsection="auth"; //The name of the table
$query1="select * from auth where username='$user'";
$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query
$thisrow=mysql_fetch_row($result);
echo "Study: " . $thisrow[1] . " - " . $thisrow[5];
Sorry for such a dumb question. I can't seem to get the while loops of more than one field working for the life of me.
mysql_fetch_row fetches each row one at a time. In order to retrieve multiple rows, you would use a while loop like this:
while ($row = mysql_fetch_row($result))
{
// code
}
Use a loop, and use mysql_fetch_array() instead of row:
while($row = mysql_fetch_array($result)) {
echo "Study: " . $row[1] . " - " . $row[5];
// but now with mysql_fetch_array() you can do this instead of the above
// line (substitute userID and username with actual database column names)...
echo "Study: " . $row["userID"] . " - " . $row["username"];
}
I suggest you to read this:
http://www.w3schools.com/php/php_mysql_select.asp
It will give you an overview idea of how to properly connect to mysql, gather data etc
For your question, you should use a loop:
while ($row = mysql_fetch_row($result)){//code}
As said by htw
You can also obtain a count of all rows in a table like this:
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM table"));
$count = $count["count"];
You can also append a normal WHERE clause to the select above and only count rows which match a certain condition (if needed). Then you can use your count for loops:
$data = mysql_query("SELECT * WHERE username='bob'");
for ($i = 0; $i
Also, mysql_fetch_array() is usually a lot easier to use as it stores data in an associative array, so you can access data with the name of the row, rather than it's numeric index.
Edit:
There's some kind of bug or something going on where my second code block isn't showing everything once it's posted. It shows fine on the preview.
I like to separate the DB logic from the display. I generally put my results into an array that I can call within the HTML code. Purely personal preference; but here's how'd I'd approach the problem: (I'd take the $sql out of the error message in production)
<?php
$sql="
SELECT *
FROM auth
WHERE username='$user';
";
$result = mysql_query($sql)
or die("Failed Query : ".mysql_error() . $sql); //do the query
while ($ROW = mysql_fetch_array($result,MYSQL_ASSOC)) {
$USERS[] = $ROW;
}
?>
HTML CODE
<? foreach ($USERS as $USER) { ?>
Study: <?=$USER['dbFieldName'];?> - <?=$USER['dbFieldName2'];?>
<? } //foreach $USER ?>
$qry=mysql_query(select * where username='bob');
if(mysql_num_rows($qry))
{
while($row=mysql_fetch_array($qry,MSQL_NUM))
{
echo $row[0]." ".$row[1]." ".$row[2]."<br>";
}
}