PHP - Basic Object Oriented Script Does Not Work
Hi there, I am starting to learn OO PHP programming. After running math.php, it gives an output 'Use only numbers'.
Why? I don't understand this. math.php <?php require('MathClass.php'); $c = new MathClass(); echo $c->add(5,10,15,20); ?> MathClass.php <?php class MathClass{ function add(){ $args = func_num_args(); $sum = 0; $i = 0; for ($i ; $i < $args ; $i++){ is_int(func_get_args($i)) ? $sum += func_get_args($i) : die('Use only numbers'); } return $sum; } } ?> Similar TutorialsHi everyone, It was recommended that I should make the switch from using procedural code to object oriented code with pdo for queries and such. So, I have been doing some reading on both topics, but am finding it rather hard to wrap my head around. I managed to get a PDO query to work with the help of a tutorial that I found online. My next step is to create an object oriented member registration class. I was wondering if anyone on here could provide any advice as far as the setup goes. I will want my member class to be able to: 1) connect to db 2) gather, validate, and send user data to payment processor 3) receive postback data, insert into database, and notify new member. I have already created these functionalities for other websites using procedural coding so once I get pushed in the right direction I should be find to add the other functionalities, which will include 4) Logging a member in 5) Logging a member out 6) Update member information 7) Change password Forgot password 9) Cancel membership Below is my snippet of PDO code that I wrote. Let me know if you guys would do anything differently. I really appreciate your help in this. Code: [Select] <?php // DECLARE DATABASE CONNECTION VARIABLES // $host = 'localhost'; $database = 'database'; $username = 'user'; $password = 'password'; // CONNECT TO DATABASE // try { $connect = new PDO("mysql:host=$host;dbname=$database", $username, $password); } catch(PDOException $e) { echo $e->getMessage(); } $sql = "SELECT siteInfoPage, siteInfoKeywords, siteInfoDescription FROM siteInfo WHERE siteInfoPage = '$page'"; // FETCH INTO A PDOStatement OBJECT // $query = $connect->query($sql); // ECHO THE NUMBER OF COLUMNS // $data = $query->fetch(PDO::FETCH_OBJ); // ASSIGN TO VARIABLES $page_title = $data->siteInfoPage; $keywords = $data->siteInfoKeywords; $description = $data->siteInfoDescription; // CLOSE THE DATABASE CONNECTION // $connect = null; ?> Hello, I have some questions here on PHP Object-Oriented. I started learning PHP Procedural since some months, and I am doing quite well. I want to start with PHP Object-Oriented now, but the problems, I have not found a good easy readable tutorial on it. I have watched some videos on YouTube, but the way they explained it made me confused. I want to know something from you, if you are an experienced PHP programmer. I want to work on CMS like Drupal, WordPress, Magento and Prestashop because I have noticed a rise in job availability in these fields in my country. 1/ Is it necessary to know PHP Object-Oriented to work as Drupal, Magento or Prestashop developers? (Note: I have a blog on WordPress, and I have huge experienced on the Dashboard, configurations and so on...) 2/ Can I start learning frameworks like CodeIgniter without learning PHP Object-Oriented? Thank you.. Perhaps the questions may have not sense for you, but I just want to know your opinions. Please, if you are an experienced programmer, you reply me. Hi all, have constructed a blog through some tutorials which will add and delete messages. I wish to add some form of confirmation box with a yes/no button before deleting but am not sure where to begin. Thanks for any help <?php // Command_BlogDelete.php //############################################################################ // SearchVenueCommand class //############################################################################ class Command_BlogDelete extends Command { //############################################################################ // doExecute //############################################################################ function doExecute(Request $request) { // Get data from request $id = $request->getProperty('id'); // Create manager object $manager = new ManagerMessage(); // Add to database $manager->deleteMessage($id); // Redirect to index header("location:index.php"); } } ?> This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=306162.0 This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=327921.0 Hi, i am trying to add another propertie to the CDproduct class but everytime i keep coming up with an error: can anybody help please, here is the code below, i know it is something simple but i cannot figure it out, thanks in advance: Code: [Select] <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=windows-1250"> <meta name="generator" content="PSPad editor, www.pspad.com"> <title></title> </head> <body> <?php class ShopProduct { public $title; public $producerMainName; public $producerFirstName; public $price; function __construct($title, $firstName, $mainName, $price) { $this->title = $title; $this->producerFirstName = $firstName; $this->producerMainName = $mainName; $this->price = $price; } public function getProducer() { return "$this->producerFirstName $this->producerMainName"; } public function getProductDetails() { $s = "$this->title ($this->producerFirstName $this->producerMainName)"; return $s; } } class CdProduct extends ShopProduct { public $playLength; // Let's override the constructor function __construct($title, $firstName, $mainName, $price, $playLength) { parent::__construct($title, $firstName, $mainName, $price); $this->playLength = $playLength; } function getPlayLength() { return $this->playLength; } // Let's override getProductDetails function getProductDetails() { $s = parent::getProductDetails(); $s.= " - playing time : $this->playLength"; return $s; } public $starsign; // Let's override the constructor function __construct($title, $firstName, $mainName, $price, $starsign) { parent::__construct($title, $firstName, $mainName, $price); $this->starsign = $starsign; } function getstarsign() { return $this->starsign; } // Let's override getProductDetails function getProductDetails() { $s = parent::getProductDetails(); $s.= " - zodiac sign : $this->starsign"; return $s; } } class BookProduct extends ShopProduct { public $numPages; // Let's override the constructor function __construct($title, $firstName, $mainName, $price, $numPages) { parent::__construct($title, $firstName, $mainName, $price); $this->numPages = $numPages; } function getNumberOfPages() { return $this->numPages; } // Let's override getProductDetails function getProductDetails() { $s = parent::getProductDetails(); $s.= " - number of pages : $this->numPages"; return $s; } } $CD1 = new CdProduct("Back to black", "Amy", "Winehouse", 7.99, 63, leo); $CD2 = new CdProduct("Back to bedlam", "James", "Blunt", 7.99, 51, leo); $Book1 = new BookProduct("1984", "George", "Orwell", 8.99, 352); $Book2 = new BookProduct("Never Let", "Kazuo", "Ishiguro", 7.99, 276); echo $CD1->getProductDetails()."<br>"; echo $CD2->getProductDetails()."<br>"; echo $Book1->getProductDetails()."<br>"; echo $Book2->getProductDetails()."<br>"; ?> </body> </html> I am trying to build an object-oriented interface for a website. My classes include a "Database" class with a constructor method that connects to a database and a destructor method that disconnects from the database, a child class called "Content" that will display content stored in the database, another child class called "User" that handles registration, updating user info, logging in, and logging out, etc., and a "Validator" class that will validate all forms. So far I have the database class, the content class, and the index.php page started. My problem is that I cannot get the data returned from the function (using mysqli prepared statements) to display on the main page. I have read tutorials using MySQL, but I am using MySQLi with prepared statements. Any help is appreciated. Code: [Select] Database.php /* The Database class handles connecting to and disconnecting from the database. All interaction with the database is then extended from this class. The constructor will be run automatically each time a new instance of the Database class (or one of its child classes) is made. */ abstract class Database { // assign variables to use in the constructor private $host = 'localhost'; private $user = ''; private $password = ''; private $database = ''; // define constructor method to connect to database public function __construct() { $this->connect = new mysqli($this->host, $this->user, $this->password, $this->database); // if the connection failed kill the script and display an error if($this->connect->connect_errno) { die('Critical database error: ' . $this->database->error . '. Please contact a site administrator.'); } } // define destructor method to disconnect from the database public function __destruct() { $this->connect->close(); } } Content.php require_once('Database.php'); /* This class will display all website content that is held in the database. Anything that is stored in the database that needs to be shown on the front end of the website will go through this class. */ class Content extends Database { public function pageInfo($page) { $query = $this->connect->prepare('SELECT pageTitle, pageHeading, pageContent FROM pageInfo WHERE pageName = ?'); $query->bind_param('s', $page); $query->execute(); $query->bind_result($title, $heading, $content); return $query->fetch(); // procedurally this returns the values of the bound variables which then I can use just by typing echo $variableName // if i echo the variables out inside this method, they display at the top of index.php // how do i call them into my variables to display where i want // return $query->fetch(); should return that object to main script but then how do i call those values } public function displayUsers() { } public function searchUsers() { } } index.php <?php $page = 'index.php'; require_once('modules/Content.php'); $page = new Content(); list($title, $heading, $content) = $page->pageInfo('index.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><?php echo $title; ?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="includes/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="scripts/cufon-yui.js"></script> <script type="text/javascript" src="scripts/arial.js"></script> <script type="text/javascript" src="scripts/cuf_run.js"></script> </head> <body> <!--begin main--> <div class="main"> <?php include('header.php'); ?> <?php include('menu.php'); ?> <!--begin content--> <div class="content"> <!--begin content_resize--> <div class="content_resize"> <!--begin mainbar--> <div class="mainbar"> <!--begin article--> <div class="article"> <h2><span><?php echo $heading; ?></span></h2> <div class="clr"></div> <p><?php echo $content; ?></p> </div> <!--end article--> </div> <!--end mainbar--> <?php include('sidebar.php'); ?> <div class="clr"></div> </div> <!--end content_resize--> </div> <!--end content--> <?php include('footer.php'); ?> </div> <!--end main--> </body> </html> Hey,
I have really looked around and done the research on books and video tutorials about object oriented programming, though I am having difficulties to find something good which gets myself started.
Could somebody recommend me a good book or video tutorials, where I could get started with when it comes to Object Oriented Programming. I am looking to use Object Oriented Programming for building a blog website.
Where would you guys recommend I go to learn and become familiar with writing Object Oriented PHP code? Also what are the advantages of writing object oriented code? Is it better than the 'traditional' coding style? I mean without using Objects, Classes, Methods, etc.. Is one way more efficient than the other? I've been seeing a lot of object oriented php code lately, and I'm just curious and want to learn the concept of OOP, any help is appreciated. Thanks! -CLUEL3SS I'm trying to create an object oriented PHP poll. I know I'm close but I got stuck. If anyone can help me with this. It's a radio button poll: Code: [Select] <html> <head> <title>Polling</title> <head> <body> <h1>Pop Poll</h1> <p>Who will you vote for in the election?</p> <form method=post action="show_poll.php"> <input type="radio" name="vote" value="John Smith">John Smith<br /> <input type="radio" name="vote" value="Mary Jones">Mary Jones<br /> <input type="radio" name="vote" value="Fred Bloggs">Fred Bloggs<br /><br /> <input type=submit value="Show results"> </form> </body> Here is the show_poll.php <?php /******************************************* Database query to get poll info *******************************************/ // get vote from form $vote=$_REQUEST['vote']; // log in to database if (!$db_conn = new mysqli('localhost', 'poll', 'poll', 'poll')) { echo 'Could not connect to db<br />'; exit; } if (!empty($vote)) // if they filled the form out, add their vote { $vote = addslashes($vote); $query = "update poll_results set num_votes = num_votes + 1 where candidate = '$vote'"; if(!($result = @$db_conn->query($query)))//'@' means not showing error message. { echo 'Could not connect to db<br />'; exit; } } else { echo 'You did not vote!<br />'; exit; } // get current results of poll, regardless of whether they voted $query = 'select * from poll_results'; if(!($result = @$db_conn->query($query))) { echo 'Could not connect to db<br />'; exit; } $num_candidates = $result->num_rows;//how many candidates are = the number of rows // calculate total number of votes so far $total_votes=0; while ($row = $result->fetch_object()) { $total_votes += $row->num_votes; } $result->data_seek(0); // reset result pointer ?> <h2>Result:</h2> <table> <tr> <td>John Smith:</td> <td> <img src="poll.gif" width='<?php echo(100*($num_candidates/$total_votes)); ?>' height='20'> <?php echo(100*($num_candidates/$total_votes)); ?>% </td> </tr> <tr> <td>Mary Jones:</td> <td> <img src="poll.gif" width='<?php echo(100*($num_candidates/$total_votes)); ?>'height='20'> <?php echo(100*($num_candidates/$total_votes)); ?>% </td> </tr> <tr> <td>Fred Bloggs:</td> <td> <img src="poll.gif" width='<?php echo(100*($num_candidates/$total_votes)); ?>'height='20'> <?php echo(100*($num_candidates/$total_votes)); ?>% </td> </tr> </table> the Problem:: When I click a candidate it increments the value in the database it gets recorded well but I have problem with showing the result. It doesn't show the result right. I know that the bug lays he Code: [Select] 100*($num_candidates/$total_votes)). Instead of $num_candidates variable I need to come up with another variable that is the number of votes each candidate gets. I don't know how to come up with that. Any help Please help me with this I'd like to have an object oriented solution the point is that I don't want to use "If else" statements. Thanks any help a lot in advance I have this image upload script he
<?php if (isset($_POST['submit'])) { $j = 0; //Variable for indexing uploaded image $target_path = $_SERVER['DOCUMENT_ROOT'] . "/ubergallery/multiple_image_upload/uploads/"; //Declaring Path for uploaded images for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array $validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image $j = $j + 1;//increment the number of uploaded images according to the files in array if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; } else {//if file was not moved. echo $j. ').<span id="error">please try again!.</span><br/><br/>'; } } else {//if file size and file type was incorrect. echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; } } } ?>This script also uses javascript for multiple uploading of images. I am looking to add a query to this where I am looking to have the image file names stored in the database. The original image file name should get stored as well, yet the file name itself should get a unique id. I may have to build this query inside this upload script. I was wondering if I can keep that separately with Object Oriented Programming, if somebody just could show me "how it could look like", when it comes to having this done with Object Oriented Programming, I would appreciate it a lot. Hi, I wrote a classFile to handle files that looks like this: class classfile { //path_parths is an array, use it this way //path_parts["filename"] -> filename //path_parts["dirname"] -> directory //path_parts["extension"] //path_parts["basename"] protected $path_parts; private $fullpath; function __construct($filename){ if(file_exists($filename)){ $this->fullpath = $filename; $this->path_parts= pathinfo($this->fullpath); } else{ die("File or Folder doesn't exist"); } } function move($destination){ if (file_exists($destination)){ rename($this->fullpath, $destination . "/" . $this->getfilename()); //Update properties $this->setfullpath($destination . $this->getfilename()); $this->setpath_parts(); } else{ die("The folder specified doesn't exist"); } } function copy($destination){ copy($this->fullpath, $destination); } function getpath(){ return $this->path_parts["dirname"]; } function getfilename(){ return $this->path_parts["basename"]; } function getextension(){ return $this->path_parts["extension"]; } function getfullpath(){ return $this->fullpath; } function setfullpath($path){ $this->fullpath = $path; } function setpath_parts(){ $this->path_parts = pathinfo($this->fullpath); } function __destruct() { ; } } ?> Then I extended it with a class to handle images that looks like this: include 'c:/wamp/www/classfile.php'; class classimage extends classfile{ var $image; var $image_info; var $image_type; function __construct($filename){ parent::__construct($filename); $this->image_info = getimagesize(parent::getfullpath()); $this->image_type = $this->image_info[2]; if( $this->image_type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg(parent::getfullpath()); } elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif(parent::getfullpath()); } elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng(parent::getfullpath()); } } function save($filename, $image_type=IMAGETYPE_JPEG, $compression=80, $permissions=777) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); } if( $permissions != null) { chmod($filename,$permissions); } } function output($image_type=IMAGETYPE_JPEG) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image); } } function getWidth() { return $this->image_info[0]; } function getHeight() { return $this->image_info[1]; } function resizeToHeight($height) { $ratio = $height / $this->getHeight(); $width = $this->getWidth() * $ratio; $this->resize($width,$height); } function resizeToWidth($width) { $ratio = $width / $this->getWidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); } function scale($scale) { $width = $this->getWidth() * $scale/100; $height = $this->getheight() * $scale/100; $this->resize($width,$height); } function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); echo "resized to:\n"; echo $width . "\n"; echo $height . "\n"; echo "imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight())\n"; imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; } function format(){ $width = $this->getWidth(); $height = $this->getHeight(); if ($width > $height){ return "landscape"; } if ($height > $width){ return "portrait"; } if ($height == $width){ return "square"; } } function isTooBig($maxsize){ $width = $this->getWidth(); $height = $this->getHeight(); if ($width > $maxsize || $height > $maxsize){ return true; } else{ return false; } } function __destruct() { ; } } ?> Now that I got this, I loop through images located in a folder that way: if ($handle = opendir($directory)) { while (false !== ($file = readdir($handle))) { //Instantiate the object $image = new classimage($directory . "/" . $file); //And do quite a lot of verification and particularly this: if ($image->format() == "landscape") { echo "width: " . $image->getWidth() . "\n"; echo "height: " . $image->getHeight() . "\n"; if ($image->isTooBig($maxsize_mini)) { $image->resizeToWidth($maxsize_mini); $image->save($directory . "/mini_" . $image->getfilename()); } } } And now to the problem: I echo'ed the resize function to see what's being run and I got that: picture1 imagecopyresampled(Resource id #26, Resource id #25, 0, 0, 0, 0, 608, 405.65, (), ()) picture2 imagecopyresampled(Resource id #27, Resource id #26, 0, 0, 0, 0, 250, 166.796875, (), ()) It looks like it's reusing an instantiation of the previous object and so on and so forth. In my mind, the way it should look is: picture1 imagecopyresampled(Resource id #2, Resource id #1, 0, 0, 0, 0, 608, 405.65, (), ()) picture2 imagecopyresampled(Resource id #2, Resource id #1, 0, 0, 0, 0, 250, 166.796875, (), ()) The previous object is destructed, the new one has the old id. how does that work? The reason I ask and wonder about this is because I'm having weird result for the resize such as a ridiculously small picture mini size in the actual mini size picture (250 px) except whatever is left is filled with black. Hi I am currently mostly learning procedural PHP but had a question about security.
Are hackers able to see connections to databases in procedural programming? Would connections to databases need to be called from classes and methods instead? Or does it not matter that much? Hi, Im learning php, but Im a bit confused on this basic problem. I have the following code: <?php include "tax.php"; $price = 95; echo "Price before tax: $price <br>"; echo "Price after tax: "; echo add_tax ($price); ?> Which uses the function below <?php function add_tax ($amount) { $total = $amount * 1.09; return $total; } ?> When I execute the code I can see that it does work, but I do not understand why this part works! echo add_tax ($price); There is no multiplier symbol here, so is the function performed on the ($price) variable simply because of where it is located on this line of code? Thanks hi guys i have been building a website and have added a contact form and PHP script to send me a email server side the script works as it it will refresh the pages and display my thank you message but no email ever turns up my email address is correct so there must be somthing else not working <?php /*Email Varibles*/ $emailSubject = 'media-ondemand-contact.php'; $webMaster = 'alextrashacc@hotmail.com'; /*Data Varibles*/ $email = $_POST['email']; $name = $_POST['name']; $radiobuttons = $_POST['radiobuttons']; $where = $_POST['where']; $comments = $_POST['comments']; $newsletter = $_POST['newsletter']; $body = <<<EOD <br><hr><br> Email: $email <br> Name: $name <br> Suggestions Ect: $radiobuttons <br> Where did you hear about us: $where <br> Comments: $comments <br> News Letter Sign up: $newsletter $headers = "$email\r\n"; $headers .= "Content-type: text/html\r\n"; $success = mail($webMaster, $emailSubject, $body, $headers); EOD; $theResults = <<<EOD <html> <head> <meta http-equiv="refresh" content="3;//media-ondemand.com"> <title>Sent Message</title> <style type="text/css"> <!-- body { text-align: center; font-family: Verdana, Geneva, sans-serif; font-size: 36px; font-weight: bold; font-variant: normal; color: #666; } --> </style> </head> <body> <p>Thank You</p> <p> Your Message Has Been Sent </p> </body> </html> EOD; echo "$theResults"; ?> the contact page is at www.media-ondemand.com/contact.html Hi All, The Problem: I'm trying to learn how to take records from the NAME row of one table (i.e. Tom, Jim, Chris, Mike) and put them into a SELECT (drop down menu) box, then select a name and save it to a DIFFERENT table where the row is also called NAME, and THEN have that selection I just saved show in the SELECT box as SELECTED when the page refreshes. I have found a hundred websites showing how to bind a SELECT box to a table and put them into a SELECT box via $key => $val and even how to save it to ANOTHER textbox on the page, which is a lot easier, but never a step further as described in the first paragraph above. Seems unbelievable to me since it's so common. Maybe I'm just not using the proper search terms/keywords. Here's an example: Let's say you wanted to notify 3 people of your birthday. So, on the notification page, you would enter three names of people you would want notified all in separate input textboxes with [keys]. So, you enter John, Chris, and Tom into three text boxes and save the page. Done. Now, on another page, I have -- say .... five select boxes. For arguments sake, let's just say I click on all of them one at a time. In each of them, I would only see three names (John, Chris, and Tom). Now, in the first SELECT box I click on John. In the second select box I click on Chris, and on the third I click on Tom. Then save the form. I would like to see John, Chris, and Tom in the first three boxes after refreshing and I would like to see SELECT A NAME on the last two Select boxes that we never did anything with. Remember, there are NO default names in the first table with row called NAMES. They are populated by the user and saved to the row. I'm attaching an image of what the page looks like that I want to see the names and be able to select them. Does anyone have a link to a site that shows how to do this... or maybe have something very basic that would show me the process? Or, if not too difficult, maybe you could show me? Thanks in advance for any help! Attached Files Untitled.jpg 24.97KB 0 downloads Hello, I'm trying to take the value from an HTML form and insert it into a database on a button click. It inserts a null value into the database. The script is called submitColumnDetails.php. This is where I create the text field that I want to take the information from. This is in a separate file. Code: [Select] echo <<<END <form action = "submitColumnDetails.php" method = "POST"> <input type = "text" name = "columnField"/> </form> END; This is the submitColumnDetails.php file Code: [Select] <?php //Submit Column Data //-----------------------------------------------------// //Connect to localhost server $connector = mysql_connect("localhost", "root", "root"); if(!$connector){ //If user can't connect to database die('Could not connect: ' . mysql_error()); //Throw an error } //-----------------------------------------------------// mysql_select_db("colin_db", $connector); $newValue = $_POST["columnField"]; //Data from column field. THIS IS WHAT RETURNS NULL $newColumnQuery = "INSERT INTO `colin_db`.`allColumnFields` (`DATA`) VALUES ('$newValue')"; mysql_query($newColumnQuery); //Query to add form to main table $newColumnIntoMainTableQuery = "ALTER TABLE colin_table ADD ('$newValue' varchar(50))"; mysql_query($newColumnIntoMainTableQuery); //Query to add column to main table mysql_close($connector); //Close database connection echo "<script type = 'text/javascript'> window.location = 'index.php'</script>"; //Go back to original page ?> Even when I print out the $newValue, it does not print anything. What am I doing incorrectly? i need help trying to get this delete feature to work its not deleting from the database (by the way i took out my database names and passwords at the top of the file) is it possible someone could help me, ive been working on this for like a week and cant figure out the problem. thanks! you can email me at spr_spng@yahoo.com picture 2.png is showing what it looks like Code: [Select] <?php $host="localhost"; // Host name $username="username"; // Mysql username $password="password"; // Mysql password $db_name="database_name"; // Database name $tbl_name="table_name"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name"; $result=mysql_query($sql); $count=mysql_num_rows($result); ?> <style> /*table affects look of the whole table look */ table { margin-left: auto; margin-right: auto; border: 1px solid #330000; border-collapse:collapse; width:70%; border-width: 5px 5px 5px 5px; border-spacing: 1px; border-style: outset outset outset outset; border-color: #330000 #330000 #330000 #330000; border-collapse: separate; background-color: #330000; #800517 f535aa #330000 school color #9A0000 school color2 #991B1E school color3 #CCCC99 school color4 #9A0000 } /*th is table header */ th { text-align: left; height: 2.5em; background-color: #330000; color: #FC0; font-size:1.5em; } /*td is table data or the cells below the header*/ td { text-align: left; height:1.0em; font-size:1.0em; vertical-align:bottom; padding:10px; border-width: 5px 5px 5px 5px; padding: 8px 8px 8px 8px; border-style: outset outset outset outset; border-color: #9A0000 #9A0000 #9A0000 #9A0000; background-color: #CCCC99; -moz-border-radius: 0px 0px 0px 0px; } </style> <table width="400" border="0" cellspacing="1" cellpadding="0"> <tr> <td><form name="form1" method="post" action=""> <table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC"> <tr> <td bgcolor="#FFFFFF"> </td> <td colspan="4" bgcolor="#FFFFFF"><strong>Pick Which Rows you want to delete, Then press delete.</strong> </td> </tr> <tr> <td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td> <td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td> <td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td> <td align="center" bgcolor="#FFFFFF"><strong>Email</strong></td> <td align="center" bgcolor="#FFFFFF">delete</td></tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td bgcolor="#FFFFFF"><? echo $rows['id']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['name']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['lastname']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['email']; ?></td> <td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td> </tr> <?php } ?> <tr> <td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td> </tr> <? // Check if delete button active, start this // edited if($delete){ for($i=0;$i<$count;$i++){ $del_id = $checkbox[$i]; $sql = "DELETE FROM $tbl_name WHERE id='$del_id'"; $result = mysql_query($sql); } // if successful redirect to delete_multiple.php if($result){ echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete_multiple.php\">"; } } mysql_close(); ?> </table> </form> </td> </tr> </table> Hi, I am not sure why but my script is not working. Choose a post is not working http://beta.cwuforum.com/stock/tech.php Code: [Select] <?PHP $idofp = $_REQUEST['bida']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Ryan Weekly</title> <style type="text/css"> body { background-color: #E3E5E2; } </style> </head> <style type="text/css"> <!-- body { font-size:12px; font-family:Verdana, Arial, Helvetica, sans-serif; } div#wrapper { width: 80%; background-color:#FFFFFF; margin-top: 50px; margin-bottom: 50px; margin-left: auto; margin-right: auto; padding: 0px; border: thin solid #000000; } div#header { padding: 15px; margin: 0px; text-align: center; } div#nav { width: 25%; padding: 10px; margin-top: 1px; float: left; border: thin solid #000000; } div#main { margin-left: 30%; margin-top: 1px; padding: 10px; border: thin solid #000000; } div#underhead { padding: 15px; margin: 0px; border-top: thin solid #000000; } { ul.nav a:hover, ul.nav a:active, ul.nav a:focus { /* this changes the background and text color for both mouse and keyboard navigators */ background: #6F7D94; color: #FFF; } .content ul, .content ol { padding: 0 15px 15px 40px; /* this padding mirrors the right padding in the headings and paragraph rule above. Padding was placed on the bottom for space between other elements on the lists and on the left to create the indention. These may be adjusted as you wish. */ } /* ~~ The navigation list styles (can be removed if you choose to use a premade flyout menu like Spry) ~~ */ ul.nav { list-style: none; /* this removes the list marker */ border-top: 1px solid #666; /* this creates the top border for the links - all others are placed using a bottom border on the LI */ margin-bottom: 15px; /* this creates the space between the navigation on the content below */ } ul.nav li { border-bottom: 1px solid #666; /* this creates the button separation */ } ul.nav a, ul.nav a:visited { /* grouping these selectors makes sure that your links retain their button look even after being visited */ padding: 5px 5px 5px 15px; display: block; /* this gives the link block properties causing it to fill the whole LI containing it. This causes the entire area to react to a mouse click. */ text-decoration: none; background: #8090AB; color: #000; } ul.nav a:hover, ul.nav a:active, ul.nav a:focus { /* this changes the background and text color for both mouse and keyboard navigators */ background: #6F7D94; color: #FFF; } /* ~~ The footer ~~ */ .footer { padding: 10px 0; background: #6F7D94; position: relative;/* this gives IE6 hasLayout to properly clear */ clear: both; /* this clear property forces the .container to understand where the columns end and contain them */ } /* ~~ miscellaneous float/clear classes ~~ */ .fltrt { /* this class can be used to float an element right in your page. The floated element must precede the element it should be next to on the page. */ float: right; margin-left: 8px; } .fltlft { /* this class can be used to float an element left in your page. The floated element must precede the element it should be next to on the page. */ float: left; margin-right: 8px; } .clearfloat { /* this class can be placed on a <br /> or empty div as the final element following the last floated div (within the #container) if the #footer is removed or taken out of the #container */ clear:both; height:0; font-size: 1px; line-height: 0px; } --> </style> <body> <div align="Left"> <p><img src="indexp.png" width="728" height="90" /></p> </div> <div id="underhead"> <form id="bida2" name="form1" method="post" action="tech.php"> Choose Post: <label for="id"></label> <select name="id" id="bida"> <option value="ad1">Google Chrome Netbook </option> </select> <input type="submit" name="send" id="send" value="View" /> </form> </div> <?php include("menu.php"); ?> <div id="main"> <?PHP if (empty($idofp)) include ("canoncamera1.php"); if ($idofp == ad1) include ("chromenetbook.php"); ?> </div> Ryan Weekly 2009 - 2011 (May 11, 2011 at 6:00PM Is our 3 Year anniversary!) </body> </html> It works other then the fact it won't go to another page to see results. <?php // Get the search variable from URL $var = @$_GET['q'] ; $trimmed = trim($var); //trim whitespace from the stored variable // rows to return $limit=10; // check for an empty string and display a message. if ($trimmed == "") { echo "<p>Please enter a search...</p>"; exit; } // check for a search parameter if (!isset($var)) { echo "<p>We dont seem to have a search parameter!</p>"; exit; } //connect to your database ** EDIT REQUIRED HERE ** mysql_connect("localhost","username","password"); //(host, username, password) //specify database ** EDIT REQUIRED HERE ** mysql_select_db("database") or die("Unable to select database"); //select which database we're using // Build SQL Query $query = "select * from the_table where 1st_field like \"%$trimmed%\" order by 1st_field"; // EDIT HERE and specify your table and field names for the SQL query $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); // If we have no results, offer a google search as an alternative if ($numrows == 0) { echo "<h4>Results</h4>"; echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>"; echo "<p><a href=\"http://www.google.com/search?q=" . $trimmed . "\" target=\"_blank\" title=\"Look up " . $trimmed . " on Google\">Click here</a> to try the search on google</p>"; } // next determine if s has been passed to script, if not use 0 if (empty($s)) { $s=0; } // get results $query .= " limit $s,$limit"; $result = mysql_query($query) or die("Couldn't execute query"); // display what the person searched for echo "<p>You searched for: "" . $var . ""</p>"; // begin to show results set echo "Results"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["1st_field"]; echo "$count.) $title" ; $count++ ; } $currPage = (($s/$limit) + 1); //break before paging echo "<br />"; // next we need to do the links to other results if ($s>=1) { // bypass PREV link if s is 0 $prevs=($s-$limit); print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><< Prev 10</a>  "; } // calculate number of pages needing links $pages=intval($numrows/$limit); // $pages now contains int of pages needed unless there is a remainder from division if ($numrows%$limit) { // has remainder so add one page $pages++; } // check to see if last page if (!((($s+$limit)/$limit)==$pages) && $pages!=1) { // not last page so give NEXT link $news=$s+$limit; echo " <a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 >></a>"; } $a = $s + ($limit) ; if ($a > $numrows) { $a = $numrows ; } $b = $s + 1 ; echo "<p>Showing results $b to $a of $numrows</p>"; ?> |