I'm working on a PHP script to make a catalog. The relevant columns in my database are Vid, banner, category and Scategory. Vid is the primary key, banner is the path to my img files, and category and Scategory are both numbers for the their respective ID. Everything is over simplified as I'm just testing the scripts. There is currently 20 records in the table.
<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<?php
require "config.php";
$sql = "SELECT Vid,banner,category,Scategory FROM display";
$result = $conn->query($sql);
$row = $result;
$min = 10;
$max = 20;
while ($row = mysqli_fetch_assoc($result)) {
implode ('', $row);
$vid = $row['Vid'];
$banner = $row['banner'];
$cid = $row['category'];
$sid = $row['Scategory'];
if ($cid = 2 && $sid = 1){
echo
'
<div style="display:inline-block;">
<div style="border-color:blue; border-style:solid;">
<a href="#test'.$vid.'">
<img src="'.$banner.'" />
</div>
</div>';
echo $vid;
echo $cid;
echo $sid;
if ($vid % 2 == 0){
echo '<br>';
}
}
}
require'close.php';
?>
</body>
</html>
Now the code runs just fine, but it gets strange I use $cid and $sid as conditions in that IF loop. Given there is 20 records, both $cid and $sid have half their values as '1' and half as '2, so when I set the IF conditions I figured it would return 5 records, but it instead returned all 20. When I echo $vid $cid and $sid, it returns the proper $vid, but $sid returns as whatever condition I set it to. For example conditions set to $cid=1 and $sid=2 returns 1:1:2, 2:1:2, 3:1:2 etc.
Now here is where it gets really strange, regardless of the condition set for $cid it returns as '1', if I set it '7' it still returns as '1'. Whereas $sid returns as whatever number is set. Also when I set either condition to null it returns nothing.
So my question is why it's acting the way it is or how it should be written if I'm writing it wrong.
Also as a side question, when I put <a> before <img> it returns the proper ID that's linked to the <img>. But when I put <a> directly after <img>, it returns the ID of the next iteration's row, and the first iteration returns blank. Anyone happen to know why that happens since regardless of their position in the statement it's still part of the same loop iteration?
You are using a single equal and assign the value to the variable. To compare values you have to use == or ===!
What is the difference between == and ===?
See the following condition to see the difference:
2 == "2" -> Equal
2 == 2 -> Equal
2 === "2" -> Not Equal
2 === 2 -> Equal
How you can avoid this on future? - Yoda condition
You can change your conditions to the following to make sure you are using the conditions on the right way. You only shoud use this for equal comparison not for >, <, <=, >=.
//throws an error
if (0 = $isNull) { ... }
//the right one
if (0 == $isNull) { ... }
== not = in your if statement.
implode line does nothing
Use double-equals instead of singles. Not:
if( $foo = 2 )
...but:
if( $foo == 2 )
Your code is changing the values instead of testing them.
Change if ($cid = 2 && $sid = 1) with if ($cid == 2 && $sid == 1). I think you did it only by mistake, since your other if is fine!
In your if statement you're using a single equals operator it needs to be == or ===
Related
I am currently working on the title of a website where I have defined a function to give result from the database to show on the title section it works fine for condtion 1 & 2, however when I need it to display 'Home' i.e. when condition 1 or 2 are not set or empty it doesn't return 'Home'. I am hoping to have done something wrong with the 3rd condition but not sure where.
P.s: get_path() is a function that extracts url parameters to compare them with database values.
<?php
function title($dbc){
$path_info = get_path();
$title_prod= $path_info['call_parts'][0];
$title_cat = $path_info['call_parts'][1];
if(isset($title_cat))
{
$query = "SELECT * FROM prdct_categories WHERE slugs = '$title_cat'";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_assoc($result);
$titleslug = $row['subgroup'];
} elseif(isset($title_prod))
{
$query1 = "SELECT * FROM prdct_categories WHERE product = '$title_prod'";
$result1 = mysqli_query($dbc, $query1);
$row = mysqli_fetch_assoc($result1);
$titleslug = $row['product'];
} elseif(!isset($title_prod) OR !isset($title_cat) OR isset($title_prod)=='' OR isset($title_cat)=='')
{
$titleslug = 'Home';
}
return $titleslug;
mysqli_close($dbc);
}
?>
<title><?php echo title($dbc); ?></title>
Thanks in advance for looking into it.
I'm guessing isset($title_prod)=='' should be $title_prod == '' and
isset($title_cat)=='' should be $title_cat == ''.
You can't compare isset to a empty string as you did here:
OR isset($title_prod)=='' OR isset($title_cat)==''
isset returns a boolean.
You should do this instead on that if:
elseif(!isset($title_prod) OR !isset($title_cat) OR $title_prod=='' OR $title_cat=='')
There is a slight mistake in your third condition:
elseif(!isset($title_prod) OR !isset($title_cat) OR isset($title_prod)=='' OR isset($title_cat)=='')
isset() returns a boolean value which means that one of these conditions will never be true isset($title_prod)=='' OR isset($title_cat)==''
I think you meant the following: [...] OR $title_pord == "" OR $title_cat == ""
I fixed it with below change with title tag;
<title><?php if(title($dbc) != null){echo title($dbc)." | ".'Upperbit';}else echo "Home" ." | ".'Upperbit'; ?></title>
Along with above changes as suggested. Perhaps I don't require a 3rd condition
Assuming you have changed the script according to correct isset syntax in this way:
elseif(!isset($title_prod) OR !isset($title_cat) OR $title_prod=='' OR $title_cat=='')
your script however has unexpected result because if, i.e., $title_cat=='', the first if statement is evaluated as True:
if( isset($title_cat) )
You have to change your code in this way:
if( $title_cat )
{
(...)
}
elseif( $title_prod )
{
(...)
}
else
{
(...)
}
I have written from a tutorial, the code below which gets the content from a table in the db but the divs that the content are in are hard coded into the html file.
How can I turn this code into something that will create as many divs as necessary depending on the quantity of the content.
I mean, the code below separates the content in to 10 rows per div and then creates the next div. I want to keep this structure but have the code created dynamically so that if there are 22 rows in the db then it will need to produce 3 divs, if there are 50 rows it will need 5 divs etc etc. For each div it needs to not repeat the same 10 but start from the next row for each div.
Can anyone help?
Thanks
<div class="down_col">
<?php
$startAt = empty($_GET['startAt']) ? 0 : $_GET['startAt'];
require_once 'functions.php';
printDownTrans($startAt, 10);
?>
</div>
<div class="down_col">
<?php
require_once 'functions.php';
printDownTrans($startAt + 10, 10);
?>
</div>
<div class="down_col">
<?php
require_once 'functions.php';
printDownTrans($startAt + 20, 10);
?>
</div>
EDIT
This is the main part of the functions.php which retreive the data from db and concat some data together:
if (mysqli_connect_errno($link)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit(0);
}
// Retrieve the rows from sampleTable table.
$query = "SELECT * FROM sampleTable ORDER BY Data1, Data2 LIMIT $startAt,$amount";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_row($result)) {
$data1Data2 = $row[1] . ' - ' . $row[2];
echo '<p>' . $data1Data2 . '</p>';
Hope this helps to understand. Thanks
I suggest rewriting (at least) that part of the code as I believe (database) logic and output should be separated.
However, in your code it is not separated, so why even separate the div from it? If you wouldn't, the database logic inside the function can easily be used to achieve what you want.
// new function parameters:
// $maxCols maximum number of divs default=NULL
// $colSize how many rows in one col default=10
if ($maxCols !== NULL)
$limit = ','.$maxCols * $colSize;
else
$limit = '';
$query = "SELECT * FROM sampleTable ORDER BY Data1, Data2 LIMIT ".$startAt.$limit;
if ($result = mysqli_query($link, $query)) {
$currentRow = 1;
echo '<div class="down_col">';
while ($row = mysqli_fetch_row($result)) {
if ($currentRow % $colSize == 0)
echo '</div><div class="down_col">';
$data1Data2 = $row[1] . ' - ' . $row[2];
echo '<p>' . $data1Data2 . '</p>';
$currentRow++;
}
echo '</div>';
}
Now you can simply call the function once like this
$startAt = empty($_GET['startAt']) ? 0 : intval($_GET['startAt']);
// version 1: print all rows in cols of size 10
printDownTrans($startAt);
// version 2: print maximum of 3 cols of size 10
printDownTrans($startAt, 3);
// version 3: print maximum of 5 cols of size 8
printDownTrans($startAt, 5, 8);
You can never trust user input! Especially when you are working with a database, this is a great vulnerability. When set, $_GET['startAt'] will be used in the query with no escaping whatsoever (maybe in the parts you didn't post?) - intval is the easy solution here, since you always expect an integer.
Since you are new to PHP, you might not know the modulo operator %. I hope this example helps:
(1 % 10 == 0) -> (1 == 0) -> false
(4 % 10 == 0) -> (4 == 0) -> false
(10 % 10 == 0) -> (0 == 0) -> TRUE
(11 % 10 == 0) -> (1 == 0) -> false
(20 % 10 == 0) -> (0 == 0) -> TRUE
You said the code you post is not from yours, isn't? Anyway, answering your question, I would do as follows:
Execute the query to database to get all the rows.
Inside the while loop, store the rows in a multidimensional array, which has the structure you want to print after: you will have two counters (one for the rows and one for the groups), when the rows counter reaches 10, you increase the groups counter and reset the rows counter to zero.
Do a foreach to go through the array, printing the html code.
This is a suggested structure for your array:
Array( group_num => Array( row_num => Array( row parameters ) ) )
You can use ceil function here is your sample code
$sql = "SELECT * FROM eh_patient WHERE site_id =3 ORDER BY id_patient";
$result_fatch = mysqli_query($link, $sql) or die(mysqli_error($link));
$row = mysqli_num_rows($result_fatch);
$max = ceil($row/10);
for($i=0; $i<$max; $i++) {
?>
<div class="down_col">
<?php
$startAt = empty($_GET['startAt']) ? 0 : $_GET['startAt'];
require_once 'functions.php';
printDownTrans($startAt, 10);
?>
</div>
<?php
}
?>
I'm using the same while loop on two pages where the only difference is a different SQL call on each page. The first works as it should, grabbing the contents from the query and displaying it in an image slider:
<?php
$qry = mysql_query(sprintf("SELECT * FROM manageme WHERE element IN ('%s')", $element));
$i = 0;
while (($t = mysql_fetch_array($qry)) != null && $i < 52) { $i++;?>
<li>
<a href="">
<img src="<?php print $t['fileLocation']; ?>";
title="<?php print $t['element_name']; ?>";
name="<?php print $t['clickLocation']; ?>";
alt="wat"
class="btnshow" />
</a>
</li>
<?php } ?>
This works as it should stepping through the loop and grabbing the contents from the query so long as there are less than 52 entries returned, ending when each record has displayed once.
Upon implementing the same while loop with a different SQL call, the problem occurs.
<?php
$qry = mysql_query(sprintf("SELECT u.username, us.user_id, us.service_id,
s.imageID, s.title, s.clickLocation, s.fileLocation, s.element_name
FROM user u, user_service us, manageme s
WHERE us.user_id = %s
AND s.imageID = us.service_id", $_COOKIE['user_id']));
$i = 0;
while (($t = mysql_fetch_array($qry)) != null && $i < 52) { $i++;?>
<li>
<a href="">
<img src="<?php print $t['fileLocation']; ?>";
title="<?php print $t['element_name']; ?>";
name="<?php print $t['clickLocation']; ?>";
alt="wat"
class="btnshow" />
</a>
</li>
<?php } ?>
Instead of grabbing from the array and ending the while loop when the contents have displayed once, it continues to loop the contents in the image slider until 52 entries have been displayed. So for instance, if the SQL call only finds 4 records to display in the image slider, the set of 4 displays 13 times (52/4) before ending the loop.
Can anyone help me figure out how to end this loop after it has displayed each record from my database once and only once? Thanks in advance!
Try adding LIMIT 52 to your query, and do the while loop as,
while ($t = mysql_fetch_array($qry)) {
//do something
}
Major problems:
1) Vulnerable to SQL injection attacks. Enjoy having your server
destroyed.
2) Terminology: you're not fetching "from an array". You're fetching a row of data from a result set, returning that row AS an array.
3) Your loop should terminate after 52 records OR no more records are avaialble, even though you're using some ugly syntax in the while() condition. Check that your query is actually fetching the right records, in the order/format you're expecting. There's nothing in your code that'd cause PHP to output "duplicate" rows.
use mysql_num_rows($qry) to terminate the loop in addition to < 52
Something like:
(($t = mysql_fetch_array($qry)) != null && ($i < mysql_num_rows($qry) || $i < 52))
From the manual it seems that your call to mysql_fetch_array($qry) will never return null. At the end of the result set you will get a false return. If you change your conditional to check for this you should be able to terminate the loop
Get rid of the $i < 52 check. Instead add LIMIT 52 to the end of your SQL query. Then change the while loop to:
while ($t = mysql_fetch_array($qry)) {
....
}
I am working on Moodle but have a php-mysql related doubt which is turning out to be complicated, thanks to the lack of my knowledge.
I have a query which returns the output fine. Using IF-ELSe condition I need to check if there is a combination of one of the fields containing a string and one of the field containing a number.
The fields I m checking are of the following type in the database table.
element - varchar(255)
value - longtext
This is my query which returns the o/p as mentioned below:
Query
$scormstatus = $DB->get_records_sql("SELECT sc.*, s.name AS activityname FROM mdl_scorm_scoes_track AS sc JOIN mdl_scorm AS s ON s.id = sc.scormid WHERE sc.scormid = '" .$activityid. "' AND sc.userid = '" .$userid. "' AND sc.attempt = '".$scormattempt->attempt."'");
foreach($scormstatus as $status)
{
echo "<br/>".$status->element."**".$status->value."<br/>";
if(is_numeric($status->value))
{
if($status->element = 'cmi.core.score.raw' && $status->value != '0')
{
echo "<br/>Score";
}
else
{
if($status->element = 'x.start.time' && $status->value != '0')
{
echo "<br/>Started";
}
}
}
}
Output:
cmi.core.lesson_location**2
Score
cmi.core.lesson_status**incomplete
cmi.core.score.max**50
Score
cmi.core.score.min**0
cmi.core.score.raw**0
cmi.core.total_time**00:00:22.00
x.start.time**1334767290
Score
Now as you would have seen that even though I'm checking for a condition which is a combination of 'cmi.core.score.raw' and value greater than 0 it still prints 'Score' for all records and never goes in the else part.
Ideally the output I'm looking forward to see is something like this
IDEAL O/P:
cmi.core.lesson_location**2
cmi.core.lesson_status**incomplete
cmi.core.score.max**50
cmi.core.score.min**0
cmi.core.score.raw**0
cmi.core.total_time**00:00:22.00
x.start.time**1334767290
Started
My guess is that it isn't recognizing the value field which is a number in my IF--ELSE case and hence always ends up going in the wrong IF part.
Any guesses as to what is happening. Thanks in advance
This code:
if($status->element = 'cmi.core.score.raw'
needs to be:
if($status->element == 'cmi.core.score.raw'
A single = is for assignment, while two == is for comparison.
I have a while loop from a query called $result.
Inside this while loop I have two other queries $anchors1 and $anchors2
The first one retrieves the first 2 rows;
The second one should retrieve the following ones using an offset.
For some reason the queries seem to interact one another, not displaying the 3 row and pulling a duplicate row which should not be there.
Is there any way this queries would interfere?
If I delete the first one, the second query works. Same vice versa.
The platform is Wordpress.
while($slice = mysql_fetch_assoc($result)){
$i++;
if($enable_position1 == 'y' && $i == $position[0]):
$anchors1 = mysql_query("SELECT * FROM anchors WHERE site_url = '$site_current' LIMIT 3");
while($anc = mysql_fetch_assoc($anchors)){
$site_anchor = $anc['site_anchor'];
$site_current = $anc['site_current'];
echo '<li>'.$site_anchor.'</li>';
}
elseif($enable_position2 == 'y' && $i == $position[1]):
$anchors2 = mysql_query("SELECT * FROM anchors WHERE site_url = '$site_current' LIMIT 999 OFFSET 3");
while($anc2 = mysql_fetch_assoc($anchors2)){
$site_anchor2 = $anc2['site_anchor'];
$site_current2 = $anc2['site_current'];
echo '<li>'.$site_anchor2.'</li>';
}
else:
the_post();
endif;
}
Ty very much!
In the second query, you're using the variable $site_current, which is set in the first query's block. Depending on how your application is designed, that could be causing the interference. I think you meant to put $site_current2 there.