Why this if else condition is not working properly? - php

I am using if else condition with foreach loop to check and insert new tags.
but both the conditions(if and alse) are being applied at the same time irrespective of wether the mysql found id is equal or not equal to the foreach posted ID. Plz help
$new_tags = $_POST['new_tags']; //forget the mysl security for the time being
foreach ($new_tags as $fnew_tags)
{
$sqlq = mysqli_query($db3->connection, "select * from o4_tags limit 1");
while($rowq = mysqli_fetch_array($sqlq)) {
$id = $rowq['id'];
if($id == $fnew_tags) { //if ID of the tag is matched then do not insert the new tags but only add the user refrence to that ID
mysqli_query($db3->connection, "insert into user_interests(uid,tag_name,exp_tags) values('$session->userid','$fnew_tags','1')");
}
else
{ //if ID of the tag is not matched then insert the new tags as well as add the user refrence to that ID
$r = mysqli_query($db3->connection, "insert into o4_tags(tag_name,ug_tags,exp_tags) values('$fnew_tags','1','1')");
$mid_ne = mysqli_insert_id($db3->connection);
mysqli_query($db3->connection, "insert into user_interests(uid,tag_name,exp_tags) values('$session->userid','$mid_ne','1')");
}
}
}

i think you are inserting
$r = mysqli_query($db3->connection, "insert into o4_tags(tag_name,ug_tags,exp_tags)
values('$fnew_tags','1','1')");$mid_ne = mysqli_insert_id($db3->connection);
and then you are using while($rowq = mysqli_fetch_array($sqlq))
which now has records you just inserted therefore your if is executed

I'm pretty sure the select query below will always return the same record.
$sqlq = mysqli_query($db3->connection, "select * from o4_tags limit 1");
I think most of the time it will goes to the else, which execute the 2 insert.
Shouldn't you write the query like below?
select * from o4_tags where id = $fnew_tags limit 1

Related

this particular part of code is not working

my code :
$Query = mysql_query("INSERT INTO employee SET firstname='".$firstname."',lastname='".$lastname."',gender='".$gender."',
email='".$email."',mobile='".$mobile."',empid='".$empid."',address='".$address."',dob='".$dob."',photo='".$photo."',
password='".$password."',sales_manager='".$sales_manager."',designation='".$designation."',reg_date='".$reg_date."',
res_manager='".$res_manager."',lead_limit='".$lead_limit."',lead_cycle='".$lead_cycle."',qualification='".$qualification."',
experience='".$experience."',target='".$target."',c_delete='N',status='Active'");
}
else
{
$Query = mysql_query("INSERT INTO employee SET firstname='".$firstname."',lastname='".$lastname."',gender='".$gender."',
email='".$email."',mobile='".$mobile."',empid='".$empid."',address='".$address."',dob='".$dob."',
password='".$password."',sales_manager='".$sales_manager."',designation='".$designation."',reg_date='".$reg_date."',
res_manager='".$res_manager."',lead_limit='".$lead_limit."',lead_cycle='".$lead_cycle."',qualification='".$qualification."',
experience='".$experience."',target='".$target."',c_delete='N',status='Active'");
}
//this is for photo..
//this is used for chatting...usr_roll='".$usr_roll."'
$qch = mysql_query('SELECT * FROM stud_data order by desc');
$qch_rs=mysql_fetch_array($qch);
if(isset($qch_rs['id']))
{
$usr_roll=$qch_rs['usr_roll']+1;
echo $usr_roll;
$Query = mysql_query("INSERT INTO stud_data SET usr_name='".$firstname."',
usr_roll='".$usr_roll."',usr_unique_id='".$empid."'");
echo "HELLO";
echo $Query;
}
//this is used for chatting...
if($Query)
{
$_SESSION[MESSAGE_TEXT]="Employee Added Successfully ...";
$_SESSION[MESSAGE_TYPE] = "msgsuccess";
header("location:index.php?p=".$_REQUEST['p']."");
exit();
}
else
{
$_SESSION[MESSAGE_TEXT]="Record did not Insert...";
$_SESSION[MESSAGE_TYPE] = "msgerror";
header("location:index.php?p=".$_REQUEST['p']."");
exit();
}
}
your query is missing order by id
$qch = mysql_query('SELECT * FROM stud_data order by desc');
use
$qch = mysql_query('SELECT * FROM stud_data order by id desc');
As per your given code you should use the variables to take the values and then make a insert statement for example you are using 2 insert statement instead of that you can take the values in variable and then insert like :
$firstname = $_POST['first_name];
etc. by this way you don't need to create 2 insert satement.
Apart from that
$qch = mysql_query('SELECT * FROM stud_data order by desc');
whenever you use order by clause this always take a column name in it so use id or name whatever you want to order by.
Hope this helps.
Thanks
Randheer

How to run query until one record is found?

This is what i am trying right now but no luck
$bid = $next - 2;//This subtracts 2 from the number, this number is also auto generated
$preid = $bid;
$query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$query) or die(mysqli_error($conn));
while(mysqli_num_rows($sql) !=0) {
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
--$preid;
}
whats suppose to happen is that if a record does not exist it subtracts 1 from preid and runs the query again with the new preid and keeps happening until a record it found but cant figure out how to do it.
I am assuming that you are constantly checking database for new values. However, on a large scale application thi is an highly inefficient way to constantly ping the database.
You have made a variable $preid but you are not using it anywhere.
This is how i would do it if i were to go according to your way
$bid = $next - 2;//This subtracts 2 from the number, this number is also auto generated
$preid = $bid;
$query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$query) or die(mysqli_error($conn));
while(mysqli_num_rows($sql) !=0 || !$preid) { //notice here i added the condition for preid.
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
--$preid;
}
now what happens is that the loop will run as long as either of the two condition stays true ie either a row is returned from the database or it will keep searching until preid is not 0.
If you want to test for an empty set, your while should run while mysqli_num_rows == 0
while(mysqli_num_rows($sql) == 0) {
$select_query = "SELECT * FROM images where imageid = '$preid'";
$sql = mysqli_query($conn,$select_query) or die(mysqli_error($conn));
$preid--;
}
As #DarkBee has mentionend in his comment, this code is highly vulnerable for an infinite loop which will take down your script, as soon as there are no entries for anything.

If nothing is found for field, create new field

PHP newbie here
I have a mysql table called "topics", and i'm pulling information from the table for a page based on a result from a form (in the URL through GET)
If the URL doesn't exist, i'd like to be able for the table to create a new entry with the topic name from the URL filled in
$topic_name would be what i'd be putting in the new topicname field
My code so far:
$topic_name = strtolower(mysql_real_escape_string($_GET['t']));
//look for info
$topic_info = mysql_query("SELECT * FROM topics WHERE topicname = '$topic_name' LIMIT 1");
if (mysql_numrows($topic_info)<=0) {
//insert record
$SQL='insert into topics (topicname) values ("'.$topic_name.'")';
mysql_query($SQL);
$t_desc='NEW TOPIC : '.$topic_name;
}
else {
//do as normal (without unnessecary loop)
$g=mysql_fetch_array($topic_info);
$t_desc = $g['desc'];
}
EDIT: Sorry, I don't think i explained well, the result is from a GET from a form, so url.com/topic?=BLAH
blah would be the name of the field i'd want to create if it doesn't exist.
The table has an Auto incrementing 'ID' (primary key)
If i understand you correct :
$topic_name = (isset($_GET['t'])) ? strtolower(mysql_real_escape_string($_GET['t'])) : '';
//look for info
$topic_info = mysql_query("SELECT * FROM topics WHERE topicname = '$topic_name' LIMIT 1");
if (mysql_num_rows($topic_info)<=0) {
//insert record
//UPDATE
//$SQL='insert into topics (topicname) values ("'.$topic_name.'")';
$SQL='insert into topics (topicname, `desc`) values '.
'("'.$topic_name.'", "NEW TOPIC DESC")';
mysql_query($SQL);
$t_desc='NEW TOPIC : '.$topic_name;
} else {
//do as normal (without unnessecary loop)
$g=mysql_fetch_array($topic_info);
$t_desc = $g['desc'];
}
Try as below
$topic_info = mysql_query("SELECT * FROM topics WHERE topicname = '$topic_name' LIMIT 1");
$count = mysql_num_rows($topic_info);
if($count <= 0){
// do insert query
}
else {
// loop through you result and display record
while($g = mysql_fetch_array($topic_info)){
$t_desc = $g['desc'];
}
}
Note: Better to use PDO or Mysqli lib for new development and prevent mysql injection attack

Updating records If ipAddress and playerName match

At the moment im sending scores and data to my database from my flash game, though every level completed is a new record.
feilds are set out like l1Score,l2Score,l3Score
im trying to figure out how to update records if the field ipAddress and playerName match the current $varibles.
UPDATE highscores SET l2Score = '$l2Score' WHERE ipAddress = "$ipAddress" && playerName = '$playerName'
I was thinking somthing along these lines, but could someone point me in the right direction please!
First you want to perform a query to check if there is already a score in place for that user & IP.
$sql = "SELECT * FROM highscores WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
$result = mysql_query($sql, $con);
$row = mysql_fetch_assoc($result);
Now, if $row is empty then you want to insert a new record, else you want to update a previous record.
if($row == "")
{
$query = "INSERT INTO highscores (l2score, ipAdress, playerName) VALUES ('$l2score', '$ipAdress', '$playerName'";
} else {
$query = "UPDATE highscores SET l2Score = '$l2Score' WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
You may need to edit this to fit with the specific query that you need.

How can I query the mysql database for a variable, if exists create another variable, if not insert?

say I have a variable
$id = mt_rand();
how can I query the mysql database to see if the variable exists in the row id, if it does exist then change the variable $id, once the variable is unique to all other stored ids, then insert it into the database?
Thanks you guys.
$con = mysql_connect("<host>","<login>","<pass>");
if ($con) {
mysql_select_db('<schemata>', $con);
$found = false;
while (!$found) {
$idIamSearching = mt_rand();
$query = mysql_query("SELECT count(*) FROM <table> WHERE <idColumnName>='".$idIamSearching."'");
$result = mysql_fetch_row($query);
if ($result[0] > 0) {
mysql_query("INSERT INTO <table> (<column>) VALUES ('".$idIamSearching."')");
$found = true;
}
}
mysql_close($con);
}
Your description is hard to understand, so, this is something that could give you pointers...
'SELECT COUNT(*) as count from table where row_id="'.$variable.'" LIMIT 1'
make sure to escape the variable if it's user input or if it's going to have more than alphanumeric characters
then fetch the row and check if count is 1 or greater than 0
if one, then it exists and try again (in a loop)
although, auto increment on the id field would allow you to avoid this step
$bExists = 0;
while(!$bExists){
// Randomly generate id variable
$result = mysql_query("SELECT * FROM table WHERE id=$id");
if($result){
if(mysql_num_rows($result) > 0){
$bExists = 1;
} else {
// Insert into database
$bExists = 1;
}
}
1 Randomly generate id variable
2 Query database for it
2.1 Result? exit
2.2 No result? Insert

Categories