views:

54

answers:

2

I am working on a simple ruby assignment and I am getting and internal server error. I am assuming it is in how I am tying my classes together.

EDIT: I updated it and now I am just not inserting to the database. The point of issue is where I call "result = @dbh.query(query)"

This is my first page:

#!/usr/local/bin/ruby

require 'cgi'
require 'mysql'
load 'pizzaClass.cgi'
cgi = CGI.new
puts "Content-type: text/html\n\n"

db = Database_obj.new
pizza = Pizza.new(db)

submit = cgi['submit']
size = cgi['size']
topping1 = cgi['topping1']
topping2 = cgi['topping2']
name = cgi['name']

if submit == 'Order'
    pizza.new_pizza(size,topping1,topping2,name)
end




puts <<HTML
<form name="pizza" id="pizza" method="post" action="db.cgi">
<select name="size" id="size">
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
</select>
<br /><br />
<label for="topping1">Topping 1: <input type="text" name="topping1" id="topping1" /></label>
<br /><br />
<label for="topping2">Topping 2: <input type="text" name="topping2" id="topping2" /></label>
<br /><br />
<label for="name">Name: <input type="text" name="name" id="name" /></label>
<br /><br />
<input type="submit" name="submit" id="submit" value="Order" />

</form>
HTML

This is my pizzaClass.cgi

    class Database_obj
attr_accessor :dbh
    def initialize()
     @dbh = Mysql.real_connect("localhost", "ljackson42001", "5rechaka", "ljackson42001")
    end

    def query_db(query)
     result = @dbh.query(query)
    end

    def get_results()
     result.each do |row|
      puts row
     end
    end
end

class Pizza
    def initialize(db)
    @dbh=db 
    end

    def new_pizza(size,topping1,topping2,name)
     query = "INSERT INTO pizza VALUES(0,#{size},#{topping1},#{topping2},#{name})"
     @dbh.query_db(query)
     puts "two"
    end
end

Any help would be appreciated,
Levi

+1  A: 

You only store result in a local variable in query_db, so it's not accessible in get_results. You can fix this pretty easily by switching to using an instance variable. Instance variables begin with an @ symbol.

def query_db(query)
    @result = @dbh.query(query)
end

def get_results()
    @result.each do |row|
            puts row
    end
end
rampion
Even though this wasn't my problem it did help out with the rest. Thanks!
Levi
A: 

Ok, so in regards to it now querying the database this was my solution. The variables were not properly being referenced.

def new_pizza(size,topping1,topping2,name)
     query = "INSERT INTO pizza VALUES(0,\"#{size}\",\"#{topping1}\",\"#{topping2}\",\"#{name}\")"
     @dbh.query_db(query)
end
Levi