Coding help: Combine Insert into and If/else statement!

This is a discussion on "Coding help: Combine Insert into and If/else statement!" within the PHP Forum section. This forum, and the thread "Coding help: Combine Insert into and If/else statement! are both part of the Program Your Website category.


 Subscribe in a reader

Go Back   Webforumz.com > Main Forums > Program Your Website > PHP Forum

Notices




Reply
 
LinkBack Thread Tools
  #1  
Old Jan 23rd, 2008, 15:00
Junior Member
Join Date: Jan 2008
Location: Reykjavik
Posts: 30
Thanks: 0
Thanked 0 Times in 0 Posts
Coding help: Combine Insert into and If/else statement!

Hi, I´m in need of coding help, again

The PHP file I´m working with has three <php ...?> sections.
#1 - First code is for a Captcha code.
#2 - Second code takes an image from the previous page, saves it to a directory and sends it´s path to a database.
#3 - Third code saves input data from the previous page to a database.

Right now, these ALL work separately. But when combined I´m having two issues (due to lack of knowledge).

Problem A)
I added a IF/ELSE statement to the #2 code that is not working ('if' @ line 22. 'else' @ line 27 and 'else' closes at line 194) .
That´s no surprise as I´m a beginner. What I want with this IF/ELSE statement is:

IF there is no image uploaded (if (empty($img_name)) then the string "No image" should be inserted into the database/table (column = Mynd).

ELSE continue with the code that possesses the image and insert it´s path to the database/table.


Problem B)
If I skip the IF/ELSE statement the image is uploaded correctly and the path is inserted into my database. But as a seperate INSERT function from #3.
So there are two lines that get inserted into the database instead of one. I know that in the below code I´m connecting TWICE to the database but I tried combining the connection and INSERT to table function with no luck.

Here is the code from my PHP file:
PHP: Select all

<html>
<head></head>
<body>

<!-- Athugun hvor captcha textinn sé rétt sleginn inn -->
<?php
require_once('recaptchalib.php');
$privatekey "private";
$resp recaptcha_check_answer ($privatekey,
                                
$_SERVER["REMOTE_ADDR"],
                                
$_POST["recaptcha_challenge_field"],
                                
$_POST["recaptcha_response_field"]);

if (!
$resp->is_valid) {
  die (
"Textinn til staðfestingar að þú sért manneskja var ekki rétt inn sleginn. Vinsamlegast smelltu farðu tilbaka og reyndu aftur. Allar upplýsingar ættu enn að vera til staðar." .
       
"(reCAPTCHA said: " $resp->error ")");
}
?>

<!-- Taka við ljósmyndinni, búa til minni útgáfu, vista á vefsvæði og senda slóð í gagnasafnið-->
<?php
if (empty($_FILES))
{
    
$thepath "No picture";
}
else
{
//define  a  maxim  size  for  the  uploaded  images
define  ("MAX_SIZE","20000");
//  define  the  width  and  height  for  the  thumbnail
//  note  that  theese  dimmensions  are  considered  the  maximum  dimmension  and  are  not  fixed,
//  because  we  have  to  keep  the  image  ratio  intact  or  it  will  be  deformed
define  ("WIDTH","200");
define  ("HEIGHT","200");


//  this  is  the  function  that  will  create  the  thumbnail  image  from  the  uploaded  image
//  the  resize  will  be  done  considering  the  width  and  height  defined,  but  without  deforming  the  image
function  make_thumb($img_name,$filename,$new_w,$new_h)
{
//get  image  extension.
$ext=getExtension($img_name);
//creates  the  new  image  using  the  appropriate  function  from  gd  library
if(!strcmp("jpg",$ext)  ||  !strcmp("jpeg",$ext))
$src_img=imagecreatefromjpeg($img_name);

if(! 
strcmp("png",$ext))
$src_img=imagecreatefrompng($img_name);

if(! 
strcmp("gif",$ext))
$src_img=imagecreatefromgif($img_name);

//gets  the  dimmensions  of  the  image

$old_x=imageSX($src_img);
$old_y=imageSY($src_img);

//  next  we  will  calculate  the  new  dimmensions  for  the  thumbnail  image
//  the  next  steps  will  be  taken:
//  1.  calculate  the  ratio  by  dividing  the  old  dimmensions  with  the  new  ones
//  2.  if  the  ratio  for  the  width  is  higher,  the  width  will  remain  the  one  define  in  WIDTH  variable
//  and  the  height  will  be  calculated  so  the  image  ratio  will  not  change
//  3.  otherwise  we  will  use  the  height  ratio  for  the  image
//  as  a  result,  only  one  of  the  dimmensions  will  be  from  the  fixed  ones
$ratio1=$old_x/$new_w;
$ratio2=$old_y/$new_h;
if(
$ratio1>$ratio2)   {
$thumb_w=$new_w;
$thumb_h=$old_y/$ratio1;
}
else  {
$thumb_h=$new_h;
$thumb_w=$old_x/$ratio2;
}

//  we  create  a  new  image  with  the  new  dimmensions
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

//  resize  the  big  image  to  the  new  created  one
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

//  output  the  created  image  to  the  file.  Now  we  will  have  the  thumbnail  into  the  file  named  by  $filename
if(!strcmp("png",$ext))
imagepng($dst_img,$filename);
else
imagejpeg($dst_img,$filename);

//destroys  source  and  destination  images.
imagedestroy($dst_img);
imagedestroy($src_img);
}

//  This  function  reads  the  extension  of  the  file.
//  It  is  used  to  determine  if  the  file  is  an  image  by  checking  the  extension.
function  getExtension($str)  {
$i  =  strrpos($str,".");
if  (!
$i)  {  return  "";  }
$l  =  strlen($str)  -  $i;
$ext  =  substr($str,$i+1,$l);
return  
$ext;
}

//  This  variable  is  used  as  a  flag.  The  value  is  initialized  with  0  (meaning  no  error  found)
//and  it  will  be  changed  to  1  if  an  errro  occures.  If  the  error  occures  the  file  will  not  be  uploaded.
$errors=0;



//  checks  if  the  form  has  been  submitted
if(isset($_POST['Submit']))
{
//reads  the  name  of  the  file  the  user  submitted  for  uploading
$image=$_FILES['image']['name'];
//  if  it  is  not  empty
if  ($image)
{
//  get  the  original  name  of  the  file  from  the  clients  machine
$filename  =  stripslashes($_FILES['image']['name']);

//  get  the  extension  of  the  file  in  a  lower  case  format
$extension  =  getExtension($filename);
$extension  =  strtolower($extension);



//  if  it  is  not  a  known  extension,  we  will  suppose  it  is  an  error,  print  an  error  message
//and  will  not  upload  the  file,  otherwise  we  continue
if  (($extension  !=  "jpg")  &&  ($extension  !=  "jpeg")  &&  ($extension  !=  "png") &&  ($extension  !=  "gif"))
{
echo  
'<h1>Því miður er aðeins tekið við *.jpg, *.jpeg, *.png eða *.gif ljósmyndum að svo stöddu!</h1>';

$errors=1;
}
else
{
//  get  the  size  of  the  image  in  bytes
//  $_FILES[\'image\'][\'tmp_name\']  is  the  temporary  filename  of  the  file  in  which  the  uploaded  file  was  stored  on  the  server
$size=getimagesize($_FILES['image']['tmp_name']);
$sizekb=filesize($_FILES['image']['tmp_name']);

//compare  the  size  with  the  maxim  size  we  defined  and  print  error  if  bigger
if  ($sizekb  >  MAX_SIZE*1024)
{
echo  
'<h1>Ljósmyndin er of stór! Vinsamlegast minnkaðu hana.</h1>';
$errors=1;
}

//we  will  give  an  unique  name,  for  example  the  time  in  unix  time  format
$image_name=time().'.'.$extension;
//the  new  name  will  be  containing  the  full  path  where  will  be  stored  (images  folder)
$newname="http://www.webforumz.com/images/images/".$image_name;
$copied  =  copy($_FILES['image']['tmp_name'],  $newname);
//we  verify  if  the  image  has  been  uploaded,  and  print  error  instead
if  (!$copied)
{
echo  
'<h1>Ekki tókst að hlaða inn ljósmyndinni. Gerðu svo vel að reyna aftur eða aðra mynd.</h1>';
$errors=1;
}
else
{
//  the  new  thumbnail  image  will  be  placed  in  http://www.webforumz.com/images/thumbs/  folder
$thumb_name='images/thumbs/thumb_'.$image_name;
//  call  the  function  that  will  create  the  thumbnail.  The  function  will  get  as  parameters
//the  image  name,  the  thumbnail  name  and  the  width  and  height  desired  for  the  thumbnail
$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
}}  }}

// (Bíða með þetta) If  no  errors  registred,  print  the  success  message  and  show  the  thumbnail  image  created
//if(isset($_POST['Submit'])  &&  !$errors)
//{
//echo  "<h1>Thumbnail  created  Successfully!</h1>";
//echo  '<img  src="'.$thumb_name.'">';
//}


$_FILES['image']['tmp_name'];  //  This  is  how  we  will  get  the  temporary  file... 


$thepath "http://xxxxxxxxxxxxxx/images/images/$image_name";

// ELSE statement from line 26 ends here.

// Connect to database
$con  =  mysql_connect("host","user","pass");
if  (!
$con)
   {
    die(
'Could  not  connect:  '  .  mysql_error());
    }
mysql_select_db("database",  $con);



$query "INSERT INTO table (Mynd) VALUES ('$thepath')";
$result mysql_query($query);

?> 

<!-- Taka við innslegnum upplýsingum og senda á viðeigandi stað í gagnasafninu-->
<?php
// collect data sent from form
$form_len $_POST['form_len'];
$form_riki $_POST['form_riki'];
$form_fylking $_POST['form_fylking'];
$form_undirfylking $_POST['form_undirfylking'];
$form_flokkur $_POST['form_flokkur'];
$form_undirflokkur $_POST['form_undirflokkur'];
$form_aettbalkur $_POST['form_aettbalkur'];
$form_undiraettbalkur $_POST['form_undiraettbalkur'];
$form_aett $_POST['form_aett'];
$form_undiraett $_POST['form_undiraett'];
$form_aettkvisl $_POST['form_aettkvisl'];
$form_tegund $_POST['form_tegund'];
$form_heiti $_POST['form_heiti'];

// connection variables
$host "host";
$db_name "database";
$db_user "user";
$db_pass "pass";
$db_table "table";

// connect to host and select db
$link mysql_connect($host$db_user$db_pass);
mysql_select_db($db_name);

// create and execute the query to insert data
$query "INSERT INTO $db_table (Len,Riki,Fylking,Undirfylking,Flokkur,Undirflokkur,Aettbalkur,Undiraettbalkur,Aett,Undiraett,Aettkvisl,Tegund,Heiti) VALUES ('$form_len','$form_riki','$form_fylking','$form_undirfylking','$form_flokkur','$form_undirflokkur','$form_aettbalkur','$form_undiraettbalkur','$form_aett','$form_undiraett','$form_aettkvisl','$form_tegund','$form_heiti')";
$result mysql_query($query);
?>

<?
echo $form_len;
echo 
$form_riki;
echo 
$form_fylking;
echo 
$form_undirfylking;
echo 
$form_flokkur;
echo 
$form_undirflokkur;
echo 
$form_aettbalkur;
echo 
$form_undiraettbalkur;
echo 
$form_aett;
echo 
$form_undiraett;
echo 
$form_aettkvisl;
echo 
$form_tegund;
echo 
$form_heiti;
?> 

<?
echo mysql_errno($link) . ": " mysql_error($link) . "\n";  
?>
</body>
</html>
Any help would save my day
P.s.: The code is very ugly right now.... still a lot of work to do.

Last edited by skuliaxe; Jan 23rd, 2008 at 16:50.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote

  #2  
Old Jan 23rd, 2008, 15:04
alexgeek's Avatar
Moderator

SuperMember
Join Date: Jul 2007
Location: Webforumz 24/7
Age: 15
Posts: 3,812
Blog Entries: 9
Thanks: 2
Thanked 2 Times in 2 Posts
Re: Coding help: Combine Insert into and If/else statement!

I don't see $img_name defined anywhere before that if statement, so it should always evaluate to true.

this should work instead:
PHP: Select all

if(empty($_FILES)) 

Last Blog Entry: 3D Chess in your browser! (Mar 14th, 2008)
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #3  
Old Jan 23rd, 2008, 15:58
Junior Member
Join Date: Jan 2008
Location: Reykjavik
Posts: 30
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Coding help: Combine Insert into and If/else statement!

Thanks for that information.
I've updated the code from my first post (and fixed other small errors).

I now did get a "No picture" string to my database when there was no picture uploaded. But the SAME thing happens even if I insert a picture in the upload field/form (and no files are added to the server).

So the ELSE statement is not running instead of the IF statement.

And there´s still problem B, I´m getting two lines in the database in stead for ONE. I know that the code connects twice and inserts twice to the database. But I just don´t know how to combine this whole code to make it one insertion to the database (without making it worse).
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #4  
Old Jan 23rd, 2008, 16:36
alexgeek's Avatar
Moderator

SuperMember
Join Date: Jul 2007
Location: Webforumz 24/7
Age: 15
Posts: 3,812
Blog Entries: 9
Thanks: 2
Thanked 2 Times in 2 Posts
Re: Coding help: Combine Insert into and If/else statement!

$_FILES not $_Files. PHP is case sensitive.
Last Blog Entry: 3D Chess in your browser! (Mar 14th, 2008)
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #5  
Old Jan 23rd, 2008, 16:59
Junior Member
Join Date: Jan 2008
Location: Reykjavik
Posts: 30
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Coding help: Combine Insert into and If/else statement!

I actually had that one right in my code (noticed the coloring). I just wrote it wrong here in the post.

Anyway,
Right now I still have the two main problems. Whether there is an image uploaded or not, I always get the image path in the database (or only part of the path if there is no image).

And then there is the joining of the whole code so there will only be ONE 'insert into' function to the database.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #6  
Old Jan 23rd, 2008, 17:05
alexgeek's Avatar
Moderator

SuperMember
Join Date: Jul 2007
Location: Webforumz 24/7
Age: 15
Posts: 3,812
Blog Entries: 9
Thanks: 2
Thanked 2 Times in 2 Posts
Re: Coding help: Combine Insert into and If/else statement!

Possibly:
PHP: Select all

if(empty($_FILES['image'])) 

Last Blog Entry: 3D Chess in your browser! (Mar 14th, 2008)
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
  #7  
Old Jan 23rd, 2008, 17:50
Junior Member
Join Date: Jan 2008
Location: Reykjavik
Posts: 30
Thanks: 0
Thanked 0 Times in 0 Posts
Re: Coding help: Combine Insert into and If/else statement!

No luck with that
Always returns "No Picture" (only the 'IF' function runs, always).
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Reply With Quote
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
Combine two javascript longcroft JavaScript Forum 6 Jun 3rd, 2008 14:51
Date & Time [Combine] doctypedeclaration JavaScript Forum 3 Mar 12th, 2008 01:22
[SOLVED] combine 2 onlick events. AdRock JavaScript Forum 1 Oct 15th, 2007 06:03
Coding redirect in an else statement after the header BRONIC PHP Forum 2 Apr 19th, 2007 03:46
How can I combine two columns into one column using SQL gecastill Databases 2 Jun 3rd, 2005 18:23


All times are GMT. The time now is 02:24.


Powered by vBulletin®
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.2.0 RC8
© 2003-2008 Webforumz.com : All Rights Reserved