Jump to content

Darkelve

Members
  • Posts

    16
  • Joined

  • Last visited

    Never

Everything posted by Darkelve

  1. Currently I'm learning about objects and classes. I followed a tutorial about making a DB abstraction class (a mySQL select) and then I tried to adapt it and wrote a method to Insert a new name. However, then I had a problem: what if the value already exists in the DB? So I thought maybe I could write a method for that too, and hopefully this would be re-usable for other purposes. So I'm posting the code here and I hope someone could take a look at it, since I do not want to start any bad practices and start a habit of writing sloppy code. Would the code below be considered 'good code'? <?php // This file is called database.php class database { public $mysql; function __construct() { $this->mysql = new mysqli('localhost', 'root', 'password', 'db') or trigger_error('Database connection failed'); } /* Function to check whether value: $queriedName already exists inside table: $table and column: $column */ function findMatch($table, $column, $queriedName) { if ($result = $this->mysql->query("SELECT * FROM $table WHERE $column='$queriedName'")) { if (!$numberOfRows=$result->num_rows) { return false; } else { return true; } } } /* Function to select all records from table: $table */ function selectAll($table) { if ($result = $this->mysql->query("SELECT * FROM $table") ) { while($row=$result->fetch_object()) { $nameFields[]=$row->names; } return $nameFields; } } /* Function to insert a name: $newName into table: $table. Uses method finMatch to avoid doubles */ function insertName($table, $newName) { if ($this->findMatch($table, 'names', $newName)) { $result="Person already exists!"; return $result; } else { $result = $this->mysql->query("INSERT INTO $table(names) VALUES ('$newName')"); return $result; } // } } ?> Main page: // This file is called index.php require('database.php'); $newName='Mary Jane'; $result=$myDb->insertname('mytable', $newName); echo $result;
  2. Thanks! I've been thinking... what's the most clean/efficient way to use functions? For example, in the post above, I used the functions with return values... but - is this really the best way to do it? - wouldn't it be better to execute the query inside the function, so that it is more like a 'complete' block of code? - OR should I make a separate function where the DB connection is created and the SQL queries executed? - OR ... something else?
  3. Cleaned it up some more. And for the second function, also re-wrote the code for the other function to use a return value. Next thing to do: write some code to check that the text field is not empty. Because right now, entering a blank value and picking 'update' will make the name field blank. <?php /* Retrieve the 'name' and 'action' values from the FORM */ $userQuery=$_POST['name']; $userAction = $_POST['action']; /* Set up a new Mysql instance: conntection to database 'db' */ $mysql = new mysqli('localhost', 'root', 'password', 'db') or trigger_error('Connection to database failed'); /* Execute a function, based on the selected radiobutton */ switch ($userAction) { // Execute the selectName Function case 'select': $getName = $mysql->query(selectName($userQuery)) or trigger_error('Query failed'); if ($getName) { while ($row = $getName->fetch_object() ) $name = $row->name; if ($name) { echo $name . ' exists in the table'; } }; break; // Execute the updateName Function case 'update': $updateName = $mysql->query(updateName($userQuery)) or trigger_error('Query failed'); break; // Code to execute if no radiobuttons are selected default: echo 'Please select an action'; } /* function to UPDATE the table */ function updateName($userQuery) { $updateNameSql= "UPDATE mytable SET name = '$userQuery' WHERE id='1'"; return $updateNameSql; } /* function to SELECT from the table */ function selectName($userQuery) { $getNameSql= "SELECT * FROM mytable WHERE name='$userQuery'"; return $getNameSql; } ?> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Mysql</title> </head> <body> <div id="content"> <form method="POST" action=""> <label for="name">Name: </label><input type="text" name="name" id="name" /> <br /><br /> <input type="radio" name="action" value="select" checked="checked" />Select person <input type="radio" name="action" value="update" />Update person ID=1 <input type="submit" name="submit" value="submit" /> </form> </div> </body> </html>
  4. Studied a bit more in the meantime... watched some PHP tutorials videos and wrote the following small program. It displays in input box and two radio buttons to select the action to perform. The user enters something in the box and selects a radio button. When the user submits, the corresponding function (SQL select, SQL update) is performed. First I followed the tutorial literally. Then I made the blocks of code into functions. Then I added The SWITCH statement. Finally, I tried using the return value in the 'update' function. To my own amazement, it works.. Tried adding mysql_real_escape_string, but faile (not sure how that works exactly). Any suggestions, comments, criticism are appreciated! <?php $userQuery=$_POST['name']; $userAction = $_POST['action']; $mysql = new mysqli('localhost', 'root', 'password', 'db') or trigger_error('Connection to database failed'); switch ($userAction) { case 'select': selectName($userQuery); break; case 'update': $updateName = $mysql->query(updateName($userQuery)) or trigger_error('Query failed'); break; default: echo 'No action selected'; } /* function to UPDATE the table */ function updateName($userQuery) { $mysql = new mysqli('localhost', 'root', 'password', 'db') or trigger_error('Connection to database failed'); // $userQuery=$_POST['name']; $updateNameSql= "UPDATE mytable SET names = '$userQuery' WHERE id='1'"; return $updateNameSql; } /* function to INSERT into table */ function selectName($userQuery) { // $userQuery=$_POST['name']; $getNameSql= "SELECT * FROM mytable WHERE names='$userQuery'"; $getName = $mysql->query("$getNameSql") or trigger_error('Query failed'); if ($getName) { while ($row = $getName->fetch_object() ) $name = $row->names; if ($name) { echo $name . ' exists in the table'; } } } ?> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Mysql</title> </head> <body> <div id="content"> <form method="POST" action=""> <label for="name">Name: </label><input type="text" name="name" id="name" /> <br /><br /> <input type="radio" name="action" value="select" checked="checked" />Select person <input type="radio" name="action" value="update" />Update person ID=1 <input type="submit" name="submit" value="submit" /> </form> </div> </body> </html>
  5. I think this will take a little longer... do not really know where to start. I've seen the arrow ( -> ). Seen it in articles about objects and classes before, so maybe I should read up on that? But I've never seen it with a double dash.
  6. echo '1h' . 2 + 3 The above is equal to the following: echo '1h2' + 3 http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion So 1h2 gets converted to 1 and then 3 is added. So the answer is: 4
  7. 1. The first line displays: h3 2. The second line was hard. I had to Google for documentation, apparently it is a 'ternary operator'. It displays: foo - first it checks if 'true' is true, which it is, so the value 'Hello' is assigned. Then it goes to the next part of the formula. Since 'Hello' has a value of 'true' (it is true as long as it does not hold the value of 0 or the keyword 'false'), the value 'foo' is assigned and finally displayed. The following formula will display 'bar': echo false ? 'Hello' : 0 ? 'foo' : 'bar'; // Output: ? 3. Third one I had to 'cheat', i.e. execute it to see what is does. It checks if 'a' is smaller than 'A' and returns true or false. When true, it returns 1 and '1' is diplayed, otherwise it returns false, in which case nothing is displayed. I guess it's equivalent to 'echo false'. So I suppose lowercase 'a' comes before uppercase 'A'. 4. The last one dazzled my mind, had to 'cheat' as well. I guess an empty/non-existing array defaults to false?
  8. Sorry, no knowledge yet of classes, objects and sessions!
  9. Hey, I would like to get some practice in the following areas: - arrays (including multidimensional and associative) - functions and their return values I would appreciate it if anyone could give me/point me to some exercises/challenges. Thanks!
  10. Well, it does work if I change the following rule and strip out the slashes: $sqlStatement=stripslashes(createPerson()); However, I wonder if that defeats the purpose of using the mysql_real_escape_string function?
  11. I added an error check, and the Error message says: What is the correct way to make use of it?
  12. In the code below, I do not understand why my query executes when I use mysql_query with the literal values, but NOT when I use mysql_query with the variable. (disclaimer: I know the code below is far from perfect, but the purpose is to get some practice and get my head around some of PHP's concepts). <?php // 1. create connection $db = mysql_connect('localhost', 'root'); if($db === false) { trigger_error('Failed to connect to the database server.'); } if(!mysql_select_db('test', $db)) { trigger_error('Database test does not exist or could not be accessed.'); } // 2. function - create new person in table moderators function createPerson () { $newPerson="INSERT INTO moderators (name, age) VALUES('Mark', '20')"; $sql= "'" . mysql_real_escape_string($newPerson) . "'"; return $sql; } $sqlStatement=createPerson(); print $sqlStatement; // seems like the SQL statement is returned OK mysql_query($sqlStatement, $db); // this does NOT work mysql_query('INSERT INTO moderators (name, age) VALUES(\'Mark\', \'20\')', $db); // this DOES work ?>
  13. I simplified the code a bit for the purpose of learning more about functions and return values (and to keep things clear). I do have a problem though: the SQL statement gets returned, but when I try to execute the query (through mysql_query command), I can see in PhpMyAdmin that the age field does not get updated. Can't see a reason though... <?php // 1. create connection $database_resource = mysql_connect('localhost', 'root'); mysql_select_db('test', $database_resource) or trigger_error('Could not connect to the database'); // 2. function - update age of person X in table $tableName function updateAge ($tableName, $person) { $selectPersonString=("UPDATE $tableName SET age = 60 WHERE name = '$person'"); $selectPersonSql=mysql_real_escape_string($selectPersonString); return $selectPersonSql; } print(updateAge ('Moderators', 'Bruce')); $newAge=mysql_query(updateAge ('Moderators', 'Bruce')); ?>
  14. How can I do that with the SQL statements? If I return the string containing the SQL query, how can I actually execute this query string?
  15. Modified the code a bit, hope this is a little better. Still have to work at 7. and 8. of your remarks. <?php // Connection string $database_resource = mysql_connect('localhost', 'root'); mysql_select_db('test', $database_resource) or trigger_error('Could not connect to the database'); // Insert Two values in the corresponding rows in table $tableName function insertNewRecord ($tableName, $recordName1, $recordName2, $recordVal1, $recordVal2) { $selectPerson=mysql_query("SELECT * FROM $tableName WHERE $recordName1=$recordVal1 AND $recordName2='$recordVal2';"); $doesPersonExist=mysql_fetch_array($selectPerson); // check if person already exists if ($doesPersonExist) { print ('Person already exists'); } // if he does not yet exist, insert the record into the table else { mysql_query("INSERT INTO $tableName ($recordName1, $recordName2) VALUES('$recordVal1', '$recordVal2'); ") or trigger_error('Could not insert record into table'); } } function deleteRecord ($tableName, $recordName1, $recordName2, $recordVal1, $recordVal2) { $myQuery=mysql_query("DELETE FROM $tableName WHERE $recordName1=$recordVal1 AND $recordName2='$recordVal2';") or trigger_error('Could not delete record from table'); } insertNewRecord ('Moderators', 'age', 'name', '40', 'Jack'); deleteRecord ('Moderators', 'age', 'name', '40', 'Jack'); ?>
  16. Started learning PHP a few weeks ago, I want to ask if anyone can give me some feedback (warnings, pointers, ...) about some code I wrote, with the objective to learn more about functions as well as MySQL. I created three functions, one to create a new table (in an existing DB), one to add a new Record and one to delete an existing record. Next I want to try to use an array as parameters for these functions. <?php require 'DB.php'; // Connection string mysql_connect("localhost", "root", "") or die(mysql_error()); /* echo "Connected to MySQL<br />"; */ mysql_select_db("test") or die(mysql_error()); /* echo "Connected to Database"; */ // Create a MySQL table in the selected database function newTable($tableName) { mysql_query("CREATE TABLE IF NOT EXISTS $tableName ( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name VARCHAR(30), age INT)") or die(mysql_error()); } // Insert Two values in the corresponding rows in table $tableName function newRecordTwoVal ($tableName, $recordName1, $recordName2, $recordVal1, $recordVal2) { $myQuery=mysql_query("SELECT * FROM $tableName WHERE $recordName1=$recordVal1 AND $recordName2='$recordVal2';"); $doesItExist= mysql_fetch_array($myQuery); if ($doesItExist) { print ('Person already exists'); } else { mysql_query("INSERT INTO $tableName ($recordName1, $recordName2) VALUES('$recordVal1', '$recordVal2'); ") or die(mysql_error()); echo "Data Inserted!"; } } function delRecord ($tableName, $recordName1, $recordName2, $recordVal1, $recordVal2) { $myQuery=mysql_query("DELETE FROM $tableName WHERE $recordName1=$recordVal1 AND $recordName2='$recordVal2';"); } newTable('Moderators'); newRecordTwoVal ('Moderators', 'age', 'name', '40', 'Jack'); delRecord('Moderators', 'age', 'name', '40', 'Jack'); ?>
  17. Hi everyone, I'm Wouter, a 32 year-old living in Belgium. I'm a website manager and right now am trying to go from the 'managing' to the 'creating'. I also want to learn a server side scripting language and, being a bit of an Open Source guy myself, decided to go with PHP. Also in part because PHP is so enormously flexible and for web work, just 'feels right. I hope I can learn a lot here! Wouter
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.