The code below is part of an ajax script. Everything else is working perfectly except what is below.
I have no idea why this is happening :
$q_e = mysqli_query($sqllink,"SELECT * FROM events_parent WHERE id='$id_parent'");
$r_e = mysqli_fetch_array($q_e);
if($id_cure == $r_e['id_cure']){
$same = 1;
}else{
$same = 2;
}
if($same == 1){ //condition A
# cure is the same
mysqli_query($sqllink,"UPDATE events_parent ... ")
}elseif($same == 2){ // condition B
# cure is changed
mysqli_query($sqllink,"UPDATE events_parent ...")
}
No matter what the value of $same is, the my code still goes into condition A when it should just go into condition B. Even if i stop the script like this :
if($id_cure == $r_e['id_cure']){
$same = 1;
}else{
$same = 2;
}
echo "same : $same";
exit();
It outputs "same : 2", it does the mysql update correctly set in condition B but it also does the update set in condition A.
What am I doing wrong ? I tried using "===" instead of "==" but not result... Does anyone has an idea ?
Related
ok
so I have been stuck on this problem for a while and I'm sure there is a more elegant way of doing it.
I have 3 columns in a database -
Stand1 | Stand2 | Stand3
each column will either have a stand number (i.e D30) or 'Not Assigned'
What I need to do is count how many stands have been assigned to that customer.
For example :
D30 | not assigned | not assigned would = 1
D30 | B30 | E30 = 3
The code I have so far is
if ($row["stand1"] == 'Not Assigned') {
$stand1 = '0';
}
else {
$stand1 = '1';
}
if ($row["stand2"] == 'Not Assigned') {
$stand2 = '0';
}
else {
$stand2 = '1';
}
if ($row["stand3"] == 'Not Assigned') {
$stand3 = '0';
}
else {
$stand3 = '1';
}
I then thought I could try and count how many stand were assigned :
$standcount = $stand1 + $stand2 + $stand3
But when I print this out (everything else is in an array so loops through every customer) all I get is the total 3 for every customer.
I tried saving the data into an array like:
$standcount = array($stand1, $stand2, $stand3);
But I get the same result. I thought a foreach loop may work but not sure how to do it.
I would suggest you to:
Set the columns' default value to NULL, so that if no value is provided in an entry you'll have a null value instead of a string (that can contains different letters, as in your case). After that you can simply perform the isset() check against each value.
Use a function to avoid code repetition (the main source of errors), something like:
function check($value) {
return (isset($value)) ? 1 : 0;
}
$stand_1 = check($row["stand1"]);
$stand_2 = check($row["stand2"]);
$stand_3 = check($row["stand3"]);
If you instead want to use a string as "Not Assigned" or "NA", you can perform a case-insensitive check with strcasecmp() between the strings in case, for any reason, a value contains an extra space or a lower-case letter.
In this case the check function would be:
function check($str) {
return (strcasecmp($str, "NA") == 0) ? 0 : 1;
}
$stand_1 = check($row["stand1"]);
$stand_2 = check($row["stand2"]);
$stand_3 = check($row["stand3"]);
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
{
(...)
}
Hello i am writing a module for inserting data in MySQL table. It is very easy but in my module i am receiving four mobile number. The first one is user's mobile no and other three are reference mobile number. User's mobile no is mandatory field but reference are not. this time i am checking each reference mobile no by using isset() and empty() function in PHP.
but i have to write multiple if-else block. like
if(isset($_POST['mobileno_1']) && !empty($_POST['mobileno_1'])){
$mobileno1 = $_POST['mobileno_1'];
}else{
$mobileno1 = 0;
}
if(isset($_POST['mobileno_2']) && !empty($_POST['mobileno_2'])){
$mobileno2 = $_POST['mobileno_2'];
}else{
$mobileno2 = 0;
}
if(isset($_POST['mobileno_3']) && !empty($_POST['mobileno_3'])){
$mobileno3 = $_POST['mobileno_3'];
}else{
$mobileno3 = 0;
}
$sql = "INSERT INTO refferencemobile(mobileno, mobile1, mobile2, mobile3) VALUES($mobileno, $mobileno1, $mobileno2, $mobileno3)";
is there any optimized way to do this.so that it can reduce number of if-else block.
empty already checks if a variable isset so this simplifies the if statments.
You can also use ternary conditions. These look like:
$someCondition ? 'a' : 'b';
Which will evaluate to 'a' if $someCondition is true and 'b' otherwise.
Putting this together we can get:
//If $_POST['mobileno_1'] isset and has a non false value use $_POST['mobileno_1']
$mobileno1 = !empty($_POST['mobileno_1']) ? $_POST['mobileno_1'] : 0;
$mobileno2 = !empty($_POST['mobileno_2']) ? $_POST['mobileno_2'] : 0;
$mobileno3 = !empty($_POST['mobileno_3']) ? $_POST['mobileno_3'] : 0;
As user1281385 pointed out in the comments you are using posted values directly in a query. You need to make sure these are sanitised or, better yet, use prepared statements.
Something like this perhaps:
$mobileno3 = (isset($_POST['mobileno_3']) && !empty($_POST['mobileno_3']))
? $_POST['mobileno_3']
: 0;
You can even turn it into a function.
function GetMobileNo($mobileNo)
{
return (isset($mobileNo) && !empty($mobileNo)) ? $mobileNo : 0;
}
$mobileno3 = GetMobileNo($_POST['mobileno_3']);
sample/test code here http://codepad.org/5ybUcmcN
$mobileno1 = getMobileNo($_POST['mobileno_1']);
$mobileno2 = getMobileNo($_POST['mobileno_2']);
$mobileno3 = getMobileNo($_POST['mobileno_3']);
/* example
$mobileno1 = getMobileNo('abc');
$mobileno2 = getMobileNo('111');
$mobileno3 = getMobileNo('');
*/
$sql = "INSERT INTO refferencemobile(mobileno, mobile1, mobile2, mobile3) VALUES($mobileno, $mobileno1, $mobileno2, $mobileno3)";
function getMobileNo($mobileNo){
// check for if its set or not OR empty OR not an integer
if(!isset($mobileNo) || empty($mobileNo) || !is_int($mobileNo)){
return 0;
}
return $mobileNo; // valid number
}
I am trying to achieve the following: I ask my SQL database a query using SELECT * FROM subjects. After doing that I ask for the array using mysqli_fetch_assoc. Until that point all is fine. The problem now is that when I try to modify in each loop the value of $genero depending if it's 1 or 0. But the value of $genero never changes, it's always 1 and I am sure that the array is fetching 0 and 1. Any idea while the values of $genero are not changing through the loop?
while ($subject = mysqli_fetch_assoc($result)) {
if ($subject["sexo"] = 1) {
$genero = "<img src='images/hombre.png' />";
} else {
$genero = "<img src='images/mujer.png' />";
}
echo $genero;
}
Your comparison operator is wrong. You're using = which is an assignment operator. In your example it will always be true. You need to use == which is a comparison operator.
if ($subject["sexo"] = 1) {
should be
if ($subject["sexo"] == 1) {
In if statement you should use double equal sign: if (a == b)
I need to use the goto operator in my code as I can't seem to think of a way around it. However the problem is my host only has PHP version 5.2.17 installed.
Any ideas?
Below is my code:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
goto skip;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
skip:
There are a few anti-patterns in your code. Let's clean it up. I'll explain what's been changed in a jiffy.
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
}
}
First things first: There is no need to perform a query, fetch all of the results, then loop through those results (in_array) looking for a specific value. Let the database do that for you by expressly looking only for rows where inserted is the string literal "n".
Because we know that we're only getting "n" records back, we just need to check if there are any results. If so, run the query. If there are no "n" records, the UPDATE isn't run.
If you need to know that the UPDATE ran, add a check for it:
$ran_update = false;
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
$ran_update = true;
}
}
if($ran_update) {
// ...
}
You want to use the correct control word to break from the loop:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
break;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
The break keyword will do exactly what you want: End the execution of the while loop. Never ever ever use a goto!
As a direct response to the title of this post:
do{
if (!$condition){
break;
}
// Code called if conditions above are met
}while(0);
//Code always called
In some circumstances, this, or a goto, can make for very tidy and readable code.
First, you could use a break to exit your initial loop. Second, if you need to test for anything, set a variable (must be global not local) as a flag or indicator before calling break, then do a conditional test statement where your skip line is to perform any additional steps you need.