How can I use a PHP variable in a MySQL query?

Discussion in 'PHP' started by uleesgold, Apr 19, 2012.

  1. #1
    $result = mysql_query("SELECT * FROM $articletitle ORDER BY id ASC");
    PHP:
    And I would set the $articletitle variable beforehand.

    mysql_query("	INSERT INTO $articletitle(name,url,email,body)
    					VALUES (
    						'".$arr['name']."',
    						'".$arr['url']."',
    						'".$arr['email']."',
    						'".$arr['body']."'
    					)");
    PHP:
    I want an option for comments for each article I put on my website. The syntax I showed didn't work, it was to give you an idea of what I wanted. Obviously, I wouldn't want all of the same comments together on each article.

    I could have redundant code for each article to have its own comments but obviously that's not a good route to take.
     
    uleesgold, Apr 19, 2012 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    It's perfectly fine, but it's an insanely bad habit to allow user-input directly into the database. It WILL lead to problems, trust me.

    I'd suggest using PDO instead of mysql_ (or at LEAST mysqli_) - since it has a lot more built in security, and enables transactions and queues.

    However:

    $result = mysql_query("SELECT * FROM $articletitle ORDER BY id ASC"); should work just fine - depends a bit what the value of $articletitle is - hence I'd suggest you put "$articletitle" in `$articletitle` so the complete query becomes this: $result = mysql_query("SELECT * FROM `$articletitle`ORDER BY id ASC");

    The insert-query needs a bit of the same - first off you should just make simple $variables - something like this:
    $name = $arr['name'];
    $url = $arr['url'];
    $email = $arr['email'];
    $body = $arr['body'];

    and then the query would be something like this: mysql_query("INSERT INTO `$articletitle`(name,url,email,body) VALUES ('$name','$url','$email','$body')");

    Note that this still isn't a good way to do it (putting input values directly into the database).
     
    PoPSiCLe, Apr 19, 2012 IP
  3. uleesgold

    uleesgold Member

    Messages:
    288
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    30
    #3
    I tried the code that you suggested, and when I inserted a comment onto an article to test it out the comment went on the page. When I refreshed however, the comment then went missing.

    This didn't previously happen with the code I had before - the comment would stay on the page and become part of the HTML when live.

    Coding sort of isn't my thing since I don't like all of the special characters that all languages use- so many non-letters and numbers which makes programming concepts hard to learn for me. Pure JavaScript gets under my skin for that same reason, so I insist on JS libraries / frameworks instead.

    thanks for the effort.
     
    uleesgold, Apr 19, 2012 IP
  4. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #4
    Did the comment get stored in the database? If not, there is something wrong with the query inputting it. I'm assuming you show the comment that's being posted right away (either by echoing it out, or some other means).

    If the comment didn't get stored in the database, for some reason, try echoing out the query:

    $query = "INSERT INTO `$articletitle`(name,url,email,body) VALUES ('$name','$url','$email','$body')";
    echo $query;
    mysql_query($query);

    Be advised that you'll have problems inputting stuff into the database unless you escape the content (as I already stated, unfiltered user-input is BAD) - in the code you started with, it'll break if the content of one of the insert-values contains a ", and in mine it'll break if it contains one or more ' (single apostrophes), since this will end the content.

    Use mysql_real_escape_string() on each of the variables - ie something like this:

    $name = mysql_real_escape_string($arr['name']);
    $url = mysql_real_escape_string($arr['url']);
    $email = mysql_real_escape_string($arr['email']);
    $body = mysql_real_escape_string($arr['body']);

    and try again
     
    PoPSiCLe, Apr 20, 2012 IP
  5. Uploadables

    Uploadables Member

    Messages:
    100
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    28
    #5
    make sure you're defining your variable using an apostrophe at the start and the end.
     
    Uploadables, Apr 20, 2012 IP
  6. uleesgold

    uleesgold Member

    Messages:
    288
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    30
    #6
    Is it that such a thing should be done when using the variable inside of a MySQL query? Well, this is how I've been defining the variables for this:
    <?php $articletitle = "title-of-my-article";?>
    PHP:
    (which references the table created & assigned for that article)
     
    uleesgold, Apr 21, 2012 IP
  7. aayush93

    aayush93 Active Member

    Messages:
    28
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    58
    #7
    try this code

    mysql_query("INSERT INTO $articletitle (name,url,email,body)
                        VALUES (
                            '" . mysql_real_escape_string($arr['name']) . "',
                             '" . mysql_real_escape_string($arr['url']) . "',
                            '" . mysql_real_escape_string($arr['email']) . "',
                             '" . mysql_real_escape_string($arr['body']) . "'
                        )");
    PHP:
     
    aayush93, Apr 22, 2012 IP
  8. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #8
    That's insanely ugly, and besides, exactly the same as my example above (expect I chose to do the escaping outside the query, and put simple $variables inside).
     
    PoPSiCLe, Apr 22, 2012 IP
  9. sayfarz

    sayfarz Member

    Messages:
    28
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    36
    #9
    use single quotes '$var' .
     
    sayfarz, Apr 24, 2012 IP
  10. BOS-Mike

    BOS-Mike Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #10
    What you could also do, is;

    
    <?php
    
     function protect($value){
      
      $value = mysql_real_escape_string($value);
      $value = trim($value);
    
      return $value;
    
     }
    
     $articletitle = "your table name here, or article";
    
     $name = protect($arr['name']);
     $url = protect($arr['url']);
     $email = protect($arr['email']);
     $body = protect($arr['body']);
    
       $insert = mysql_query("INSERT INTO `$articletitle` (name, url, email, body) VALUES ('$name', '$url', '$email', '$body')") or die(mysql_error());
    
      if($insert){
    
       echo "<font color='green'>Success, the value has been inserted into the database.</font>";
       exit();
    
      } else {
        
       echo "<font color='red'>Sorry, there was an error inserting the value into the database.</font>";
       exit();
    
      }
    
    ?>
    
    PHP:
     
    Last edited: Apr 24, 2012
    BOS-Mike, Apr 24, 2012 IP
  11. uleesgold

    uleesgold Member

    Messages:
    288
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    30
    #11
    thanks. I tried the code you gave.

    While browsing, I considered concatenation as inspired by this line of code I found:

    $tutorname = mysql_query("SELECT Personal_tutor FROM Student WHERE student_ref = '".$username."'");

    This doesn't work either and returns errors. Here's the code I currently have for comments.php
    <?php
    // Error reporting:
    error_reporting(E_ALL^E_NOTICE);
    
    include "connect.php";
    include "comment.class.php";
    echo $articletitle;
    
    /*
    /	Select all the comments and populate the $comments array with objects
    */
    
    $comments = array();
    $result = mysql_query("SELECT * FROM '".$articletitle."' ORDER BY id ASC");
    
    while($row = mysql_fetch_assoc($result))
    {
    	$comments[] = new Comment($row);
    }
    
    ?>
    
    PHP:

    and the code for submit.php
    
    <?php
    
    // Error reporting:
    error_reporting(E_ALL^E_NOTICE);
    
    include "connect.php";
    include "comment.class.php";
    
    /*
    /	This array is going to be populated with either
    /	the data that was sent to the script, or the
    /	error messages.
    /*/
    
    $arr = array();
    $validates = Comment::validate($arr);
    
    if($validates)
    {
    	/* Everything is OK, insert to database: */
    	
    	mysql_query("	INSERT INTO '".$articletitle."'(name,url,email,body)
    					VALUES (
    						'".$arr['name']."',
    						'".$arr['url']."',
    						'".$arr['email']."',
    						'".$arr['body']."'
    					)");
    	
    	$arr['dt'] = date('r',time());
    	$arr['id'] = mysql_insert_id();
    	
    	/*
    	/	The data in $arr is escaped for the mysql query,
    	/	but we need the unescaped variables, so we apply,
    	/	stripslashes to all the elements in the array:
    	/*/
    	
    	$arr = array_map('stripslashes',$arr);
    	
    	$insertedComment = new Comment($arr);
    
    	/* Outputting the markup of the just-inserted comment: */
    
    	echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));
    
    }
    else
    {
    	/* Outputtng the error messages */
    	echo '{"status":0,"errors":'.json_encode($arr).'}';
    }
    
    ?>
    
    PHP:
    I already tried removing the single quotes from the concatenated string, this didn't help either.
     
    uleesgold, Apr 24, 2012 IP