multiple sql queries into one small and better query - php

I am using these queries in my php page and I think there is a better way to do the same thing.
$cms1 = getRow("select * from cms where cmsID=1");
$cms2 = getRow("select * from cms where cmsID=2");
$cms3 = getRow("select * from cms where cmsID=3");
$cms4 = getRow("select * from cms where cmsID=4");
$cms5 = getRow("select * from cms where cmsID=5");
I am printing the data from these queries like
<?=$cms['content']?>
<?=$cms2['content']?>
<?=$cms3['content']?> ....
Is there a better way to do this or to get all this data in one single query? I think I might get the result by using AS key in the query but I have no idea how.
function getRow($query)
{
$rs = mysql_query($query) or die(mysql_error());
$result = array();
if(mysql_num_rows($rs))
{
$row = mysql_fetch_assoc($rs);
return $row;
}
}

This can also be best achieved using
BETWEEN
in mysql
SELECT * FROM cms WHERE cmsID BETWEEN 1 AND 5;
For more information on Between clause, you can visit this Link
$arrData = array();
$result = mysql_query($query) or die(mysql_error());
while($row = $result->fetch_array()) {
array_push($arrData,$row);
}
print_r($arrData);

First of All change your function
function getRow($query)
{
$rs = mysql_query($query) or die(mysql_error());
$result = array();
if(mysql_num_rows($rs))
{
while($row = mysql_fetch_assoc($rs))
{
$record[$row['cmsID']] = $row;
}
return $record;
}
}
Then change your query
$output = getRow(select * from cms where cmsID in (1,2,3,4,5));
Then echo your output.
print_r($output);

use mysql IN
select * from cms where cmsID in (1,2,3,4,5)
You can use IN clause to replace many OR conditions
$sql = "select * from cms where cmsID in (1,2,3,4,5)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['cmsID'].' '.$row['content'];//output like :- 1 content
}

for($i=1;$i<=5; $i++) {
$cms1 = getRow("select * from cms where cmsID='".$i."'");
}

Related

Is using a function to Select, Update, Delete and Insert to DB safe?

I'm working on a project, I decided to use a function to select,... from db ,
my question is, Is using a function like this function safe to use?
if not do you have any better idea?
function selectFromDB($tbl,$id) {
include("connect.php");
$sql = "SELECT * FROM ".$tbl." WHERE ID = '$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$GLOBALS['selectFromDB'] = $row;
}
}
}

return multiple row with same clones name mysql-php

I want to get all users from NY city by this codes:
$result = mysql_query("select * from tbl_city WHERE city='ny'");
while ($row = mysql_fetch_object($result)) {
$a="$row->username";}
echo $a;
But it just returns the first one. How can I get more rows?
You have written echo $a outside the loop, please modify your code with this:
$result = mysql_query("select * from tbl_city WHERE city='ny'");
while ($row = mysql_fetch_object($result))
{
$a=$row->username;
echo $a;
}
If you just want to display the username, then there is no need to use extra variable. You can do as follows:
$result = mysql_query("select * from tbl_city WHERE city='ny'");
while ($row = mysql_fetch_object($result))
{
echo $row->username;
}
Although,mysql_query() is deprecated. Hence, I'll suggest you to use mysqli->query() instead as follows:
$result = mysqli->query("select * from tbl_city WHERE city='ny'");
while ($row = $result->fetch_object())
{
printf ("%s\n", $row->userame);
}
Hope it helps!

How to reuse the resulted variable after executing a mysql query

I am executing a query like this (PHP + MySQL):
$query = "SELECT * FROM tablename WHERE 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
// PHP Statement
}
I want to use the same result again on the same page then i need to execute query again like this:
$query = "SELECT * FROM tablename WHERE 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
// PHP Code
}
then it works. But if I use only
while($row = mysql_fetch_array($result))
{
// PHP Code
}
Then it doesn't work. Is there any other way to use the result many times on the same page without executing query every time?
I know i can use the same result to make an array. but is there any other way?
I believe mysql_data_seek will do this for you.
<?php
function mysql_pointer_position($result_set) {
$num_rows = mysql_num_rows($result_set);
$i = 0;
while($result = mysql_fetch_array($result_set)) {
$i++;
}
$pointer_position = $num_rows - $i;
//Return pointer to original position
if($pointer_position <= $num_rows - 1) {
mysql_data_seek($result_set, $pointer_position);
}
return $pointer_position;
}
?>

PHP - how to use array in function?

I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function

Web page not loading with PHP-MySQL code while outputting JSON

I am using the code below to get information from a database and make it into JSON (it may be wrong).
Unfortunately it won't load in my web browser, it just says it's loading but it doesn't finish. Please can you tell me what I am doing wrong.
$query = mysql_query("SELECT * FROM Posts ORDER BY date DESC") or die(mysql_error());
$array = array();
while ($row = mysql_fetch_assoc($query)) {
$array[] = $row;
$postID = $row['id'];
while ($ra = mysql_fetch_assoc(mysql_query("SELECT * FROM Comments WHERE postID = '$postID'"))) {
$array['comments'] = $ra;
}
while ($rd = mysql_fetch_assoc(mysql_query("SELECT * FROM Likes WHERE postID = '$postID'"))) {
$array['likes'] = $rd;
}
}
echo json_encode($array);
You are executing mysql_query in the infinite loop:
on each iteration you query the database, and fetch the first row. Change it to
$res = mysql_query("SELECT * FROM Comments WHERE postID = '$postID'");
if (!$res)
{
// handle error
}
while ($ra = mysql_fetch_assoc($res))
{
....
}
And the same for your second query.

Categories