Improving if statements in sql query - php

I've written some code that works fine, but is extremely verbose and would like a pointer on how to make it more efficient. I'm running different SQL queries because a single one returns too many results;
$sql1 = "select blah blah blah";
$sql2 = "select blah blah blah";
$sql3 = "select blah blah blah";
$response1 = $client->executeSQLQuery(array("sql"=>$sql1));
$response2 = $client->executeSQLQuery(array("sql"=>$sql2));
$response3 = $client->executeSQLQuery(array("sql"=>$sql3));
if( is_array($response1->return->row) )
{
foreach($response1->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response1->return->row->dnorpattern . "<br>";
$count++;
}
if( is_array($response2->return->row) )
{
foreach($response2->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response2->return->row->dnorpattern . "<br>";
$count++;
}
if( is_array($response3->return->row) )
{
foreach($response3->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response3->return->row->dnorpattern . "<br>";
$count++;
}
So, I would like to change the if statements to be a single if statement like this;
if( is_array($response1->return->row) )
{
foreach($response1->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response1->return->row->dnorpattern . "<br>";
$count++;
}
The integer for $sql and $response is predictable, so I should be able to use a for statement
for($x=1, $x<=3, $x++)
{
if( is_array($response[$x]->return->row) )
{
foreach($response[$x]->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo $response[$x]->return->row->dnorpattern . "<br>";
$count++;
}
}
But this does not work, can someone explain how I can increment the integer properly?

You can use curly braces syntax:
for($x=1; $x<=3; $x++)
{
if( is_array(${'response' .$x}->return->row) )
{
foreach(${'response' .$x}->return->row as $numbers)
{
echo $numbers->dnorpattern . "<br>";
$count++;
}
}
else
{
echo ${'response' .$x}->return->row->dnorpattern . "<br>";
$count++;
}
}
OR save your three response objects in an array, and use your original syntax:
$response = [];
$response[1] = $client->executeSQLQuery(array("sql"=>$sql1));
$response[2] = $client->executeSQLQuery(array("sql"=>$sql2));
$response[3] = $client->executeSQLQuery(array("sql"=>$sql3));
Though you could probably just write a better SQL query and vastly simplify things

Related

PHP while numbers in each row

<?php
$result10=mysql_query("SELECT * FROM blog_articles WHERE fk_semikatagori_id = 9") or die(mysql_error());
?>
<?php
$index = 1;
while($row10 = mysql_fetch_array($result10)) {
if($index%2==0) {
echo "<span class=\"f\">";
echo $row10['english_navn'];
echo "</span><br />";
}
else {
echo "<p><span class=\"f\">";
echo $row10['english_navn'];
echo "</span></p><br />";
echo "<p>";
echo $row10['english_tekst'];
echo "</p><br />";
}
$index++;
}
?>
Any ideas how I can display the number for each row?
I want it to start from 1.
I cant display the id from Mysql because it doesnt start from 1.
You could for example use a for() loop instead of a while() loop,
for ($index = 0; $row10 = mysql_fetch_array($result10); $index++)
{
...
echo $index;
}
Then the counter would be echoed.
$index = 1;
while( $row = mysql_fetch_array($result) )
{
// display the number for each row
echo $index;
// other code...
// increment number
$index++;
}
Thanks everyone for the help, it worked.
Here is the code if anyone else can use it.
<?php
$index = 1;
for ($index2 = 1; $row10 = mysql_fetch_array($result10); $index2++)
{
if($index%2==0)
{
echo "<span class=\"f\">";
echo $row10['english_navn'];
echo $index2;
echo "</span><br />";
}
else
{
echo "<p><span class=\"f\">";
echo $row10['english_navn'];
echo "</span></p><br />";
echo "<p>";
echo $index2;
echo $row10['english_tekst'];
echo "</p><br />";
}
$index++;
}
?>
I think the best solution that you can get are the follow:
Make a for statement:
<?php
for($idx=1; $row = mysql_fetch_array($result10); $idx++) {
...
}
?>
as said before or use the follow:
<?php
$idx = 1;
while($row = mysql_fetch_array($result10)) {
...
$idx++;
}
?>
I would recommend you to make a like upgrade in your select statement to get a faster result (if you start get many rows as result):
from: SELECT * FROM blog_articles WHERE fk_semikatagori_id = 9
to:
SELECT
english_navn
, english_tekst
FROM blog_articles
WHERE
fk_semikatagori_id = 9
Because you are using just these 2 columns into your loop but you are making MySQL engine get all columns from this table.
I hope it help you.

How to bring array values out of foreach loop?

I have a foreach loop like this.
if ( is_object($res_two)) {
if($res_two->num_rows() == 0) {
echo "No Records Found";}
else if( $res_two->num_rows() > 0) {
foreach ($res_two->result() as $row ) {
echo $row->js_id."\t". $row->designation."\t".$row->full_name."\t".$row->location."\t".$row->graduated_in."\t";
$mail2 = $row->email;
echo $mail2 ;
?> Download Resume <br/><br/> <?php
}
}
}
?>
Now I want to extract $mail2 details. However echoing $mail2 out of the code giving only one value instead of an array(if foreach loop iterates, it should have multiple values?).
How to get the multiple values of $mail2 outside the code?
<?php
if (is_object($res_two)) {
if ($res_two->num_rows() == 0) {
echo "No Records Found";
} else if ($res_two->num_rows() > 0) {
foreach ($res_two->result() as $row) {
echo $row->js_id . "\t" . $row->designation . "\t" . $row->full_name . "\t" . $row->location . "\t" . $row->graduated_in . "\t";
$mail2[] = $row->email;
?> Download Resume <br/><br/> <?php
}
}
}
print_r($mail2);
?>

php/mysql array or query with some values

Hello I have this query
$upit = "SELECT id from usluga";
$rezultat = mysql_query($upit);
while($red = mysql_fetch_object($rezultat))
{
echo "<li>{$red->id}</li>";
}
I want on exit to get this:
<li>1,2,3,4,5,6</li>
<li>7,8,9,10,11,12</li>
<li>13,14,15,16,17,18</li>
<li>19,20,21,22,23,24</li>
and so on..
Any help?
You can use the mod operator(%) or use array functions to achive this
$upit = "SELECT id from usluga";
$rezultat = mysql_query($upit);
while ($red=mysql_fetch_object ($rezultat)) {
$t[] = $red->id;
}
$chunks = array_chunk($t, 6);
foreach ($chunks as $chunk) {
echo "<li>" . join(",", $chunk) . "</li>";
}
try this..
$upit="SELECT id from usluga";
$rezultat=mysql_query($upit);
$i=0;
$liflag=0;
while ($red=mysql_fetch_assoc($rezultat))
{
if($i<6)
{
$liflag=1;
if($i==0)
{
echo "<li>$red->id";
$i++;
continue;
}
else
{
echo ",$red->id";
$i++;
continue;
}
}
else
{
echo ",$red->id</li>";
$i=0;
$liflag=0;
continue;
}
}
if($liflag==1)
{
echo "</li>";
}

foreach loop does not work with include

Would someone of you know why I'm not able to use a (long)piece of code within a foreach loop?
The code in the foreach loop is only executed once.
This code at topictweets.php works fine on its own but I want to repeat it for each forum.
The foreach loop works fine without the include. I also tried to have the code from topic tweets.php plainly in the foreach loop, this didn't work either of course.
The code it includes is used to get topics of a forum from the database and find related tweets, and save those in the database.
Is there some other way to do this?
foreach ($forumlist as $x => $fID) {
echo 'id:'.$fID.'<br>';
include 'topictweets.php';
/////////
////////
}
online version: http://oudhollandsedrop.nl/webendata/FeedForum/fetchtweets.php
bunch of code in topic tweets.php
<?php
//?/ VVVV ---- SELECT TOPICS FOR CURRENT FORUM ----- VVVV ////
echo $fID;
$sql = "SELECT Topics_TopicID
FROM Topics_crosstable
WHERE Forums_ForumID = '$fID'";
$result = mysql_query($sql);
if (!$result) {
//echo 'The topiclist could not be displayed, please try again later.';
} else {
if (mysql_num_rows($result) == 0) {
// echo 'This topic doesn′t exist.';
} else {
while ($row = mysql_fetch_assoc($result)) {
//display post data
// echo $row['Topics_TopicID'];
// echo': ';
$topic = "SELECT Name
FROM Topics
WHERE TopicID = " . mysql_real_escape_string($row['Topics_TopicID']);
$topicname = mysql_query($topic);
if (!$topicname) {
// echo 'The topic could not be displayed, please try again later.';
} else {
if (mysql_num_rows($topicname) == 0) {
// echo 'This topic doesn′t exist.';
} else {
while ($row = mysql_fetch_assoc($topicname)) {
//display post data
// echo $row['Name'];
// echo'<br>';
$topiclist[] = $row['Name'];
}
}
}
}
}
}
foreach ($topiclist as $key => $value) {
$terms .= "" . $value . ",";
}
//echo'<p>';
//echo rtrim($terms, ",");
//echo'<p>';
//echo'<p>';
//echo $terms;
//$terms="vintage";
//Twitter account information
$username = "Username";
$password = "Password";
while (true) {
//$terms="vintage";
//echo "search terms: " . substr_replace($terms, "", -1) . "\n";
$url = "https://stream.twitter.com/1/statuses/filter.json";
$cred = sprintf('Authorization: Basic %s', base64_encode("$username:$password"));
$param = "track=" . urlencode(substr_replace($terms, "", -1));
$opts = array(
'http' => array(
'method' => 'POST',
'header' => $cred,
'content' => $param,
'Content-type' => 'application/x-www-form-urlencoded'),
'ssl' => array('verify_peer' => false)
);
$ctx = stream_context_create($opts);
$handle = fopen($url, 'r', false, $ctx);
//var_dump($handle);
$content = "";
$flag = true;
while ($flag) {
$buffer = fread($handle, 100);
//$buffer = stream_get_line($handle, 1024, "\n");
$a = explode("\n", $buffer, 2);
$content = $content . $a[0];
#var_dump($a);
if (count($a) > 1) {
#echo $content;
#echo "\n";
$r = json_decode($content, true);
#var_dump($r);
// echo '<p>';
// echo "text: " . $r["text"];
// echo '<br>';
// echo "\nrceated_at: " . $r["created_at"];
// echo '<br>';
// echo "\nuser screen name: " . $r["user"]["screen_name"];
// echo '<br>';
// echo "\nuser id: " . $r["user"]["id"];
// echo '<br>';
// echo "\nid : " . $r["id"];
// echo '<br>';
// echo "\nin_reply_to_status_id: " . $r["in_reply_to_status_id"];
// echo '<p>';
// echo "\n\n";
$created_at = $r["created_at"];
$created_at = strtotime($created_at);
$mysqldate = date('Y-m-d H:i:s', $created_at);
//
// echo'<p>';
foreach ($topiclist as $key => $value) {
// echo'getshere!';
//$whichterm = $r["text"];
$whichterm = '"' . $r["text"] . '"';
//echo $whichterm;
if (stripos($whichterm, $value) !== false) {
// echo 'true:' . $value . '';
//find topicid
$whattopic = "SELECT TopicID
FROM Topics
WHERE Name = '$value'";
//var_dump($whattopic);
$tID = mysql_query($whattopic);
//var_dump($tID);
if (!$tID) {
// echo 'topic id not found.';
} else {
if (mysql_num_rows($tID) == 0) {
// echo 'This topic doesn′t exist.';
} else {
while ($rec = mysql_fetch_assoc($tID)) {
$inserttweets = "INSERT INTO
Tweets(Topics_TopicID, AddDate, Tweetcontent)
VALUES('" . mysql_real_escape_string($rec['TopicID']) . "',
'" . mysql_real_escape_string($mysqldate) . "',
'" . mysql_real_escape_string($r["text"]) . "')";
//WHERE TopicID = " . mysql_real_escape_string($row['Topics_TopicID'])
}
}
$addtweet = mysql_query($inserttweets);
if (!$addtweet) {
//something went wrong, display the error
//echo 'Something went wrong while adding tweet.';
//echo mysql_error(); //debugging purposes, uncomment when needed
} else {
echo 'Succesfully added tweet';
}
}
}
}
die();
$content = $a[1];
}
}
fclose($handle);
}
?>
"Pasting" a bunch of code inside a loop isn't a great practice. In fact, what you're looking for is a function or the use of a defined class. So, if you can, define a function in your topictweets.php that will contain your code and use it in your loop:
include 'topictweets.php';
foreach ($forumlist as $x => $fID) {
echo 'id:'.$fID.'<br>';
processYourForums($fID);
/////////
////////
}
try include_once()
however, why not have a loop within topictweets.php?
you can do the query, etc.. in this page, but then loop through it in the include
This should work fine:
include 'topictweets.php';
foreach ($forumlist as $x => $fID) {
echo 'id:'.$fID.'<br>';
}
You only need to include once.

If statement with 2 conditions

I was practising statements and ran into a problem. I'm trying to make it so that if $child3 is available, then it will echo all three children, like how when $child2 is available, it echos Kim & Pom. What did I do wrong?
$child = "Kim";
$child2 = "Pom";
$child3 = "Rob";
if($child2) {
echo $child; echo " "; echo $child2;
} elseif($child3) {
echo $child; echo " "; echo $child2; echo " "; echo $child3;
} else {
echo $child;
}
Try reversing the conditions:
$child = "Kim";
$child2 = "Pom";
$child3 = "Rob";
if($child3){
echo $child . " " . $child2 . " " . $child3;
}else if($child2){
echo $child . " " . $child2;
}else{
echo $child;
}
You might also like the wonderful string concatenation operator ..
elseif only executes if none of the preceding ifs or elseifs executed. So you'll want to move it above the other if:
if($child3) {
echo $child; echo " "; echo $child2; echo " "; echo $child3;
} elseif($child2) {
echo $child; echo " "; echo $child2;
} else {
echo $child;
}
Probably you want something like this:
$child = 1; // Or $child = 2; Or $child = 3;
if ($child == 1) {
echo 'Kim';
} elseif ($child == 2) {
echo 'Pom';
} else {
echo 'Rob';
}
But I recommend switch() as soon as you have elseif.
$child = "Kim";
$child2 = "Pom";
$child3 = "Rob";
if($child3){
echo $child; echo " "; echo $child2; echo " "; echo $child3;
}elseif($child2){
echo $child; echo " "; echo $child2;
}else{
echo $child;
}
How about this?
if ($child) {
echo "{$child} ";
}
if ($child2) {
echo "{$child2} ";
}
if ($child3) {
echo "{$child3} ";
}
If that's your actual code, you'll only ever get Kim Rob, as $child2 will always be true, thereby bypassing your else clauses.
Also, you can combine your echos into:
echo "$child $child2 $child3";
It makes it far easier to read that way.
Here's how I would do it. I agree with Dragon that a switch would be clearer/better.
switch (true)
{
case (isset($child,$child2,$child3)) :
echo $child . ' ' . $child2 . ' ' . $child3;
break;
case (isset($child, $child2)) :
echo $child . ' ' . $child2;
break;
case (isset($child)) :
echo $child;
break;
}

Categories