PHP - Connecting To Database Using Php Objects
Hi I am trying to connect to my database but i am having some problems where the server( WAMP) crashes and does not load this page. here is the php coding
<?php $db = new PDO("mysql:host=localhost;dbname=test;port=80", "root", ""); var_dump($db);when i run this no error comes the page doesnt load. anyone know why? when using PDO do i have to do some sort of configuration changes to wamp? i have even changed the directory of the file and still same issue. any suggestions would be wonderful. Similar TutorialsHi all.
My database just stopped connecting? I have tried everything i could but no way! What could have happened and what can i do? I even went as far as creating the database connection inside the page to see if it will work but still no way!
Thanks Can someone tell me why in the following code, in the 'try' section, this code works: (first line after 'try')
$conn = new PDO("mysql:host=$servername;dbname=$dbasename", $username, $password); even though I have not declared a variable named $dbname,
but if I change it to "$databasename", which I have declared, it doesn't work. I don't understand that.
<code>
<?php I have the following code created, however when i run it it doesn't come back as saying connected successfully?
<?php $host = "localhost"; $my_user = "root"; $my_password = ""; $my_db = "notes_db" $con = mysqli_connect("localhost","my_user","my_password","my_db"); echo ("Connected Successfully"); ?> Hi I am struggling to connect to my database and was wondering if someone could please help me. I am not sure what I need to put on line 10 in this code
<?php define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', ''); define('DB_NAME', 'tonyruttle'); define("PERPAGE", 10); $mydb = (DB_HOST, DB_USER, DB_PASS, DB_NAME); /*********************************************** ** SEARCH FOR MATCHING PRODUCTS ************************************************/ $showResults = 0; $search = ''; if (isset($_GET['srch'])) { $search = $_GET['srch']; $showResults = 1; $srch = array_filter(array_unique(explode(' ', trim($_GET['srch'])))); array_walk($srch, function(&$v, $k) { // add the +'s to the search tags $v = '+'.$v; }); $tagparam = join(' ', $srch); // // FINDTOTAL RECORDS IN SEARCH RESULTS // $params[] = $tagparam; $res = $db->prepare("SELECT COUNT(*) as tot FROM television p WHERE MATCH(title,keywords) AGAINST(? IN BOOLEAN MODE) "); $res->execute( $params ); $total = $res->fetchColumn(); $page = $_GET['page'] ?? 1; $params[] = ($page-1)*PERPAGE; // append parameters offset $params[] = PERPAGE; // and number of records for limit clause // // GET A PAGEFUL OF RECORDS // $sql = "SELECT id , title , active FROM television p WHERE MATCH(title,keywords) AGAINST(? IN BOOLEAN MODE) ORDER BY TITLE LIMIT ?,? "; $stmt = $db->prepare($sql); $stmt->execute($params); if ($stmt->rowCount()==0) { $results = "<h3>No matching records</h3>"; } else { $results = "<tr><th>Product Id</th><th>Title</th><th>Active</th><th colspan='2'>Action</th></tr>\n"; foreach ($stmt as $rec) { $cls = $rec['active']==0 ? "class='inactive'" : ''; $results .= "<tr $cls><td>{$rec['id']}</td><td>{$rec['title']}</td><td class='ca'>{$rec['active']}</td> <td class='ca'><a href='?action=edit&id={$rec['id']}'><img src='images/edit-icon.png' alt='edit'></a></td> </tr>\n"; } } } ?> <div id='title'>Product List</div> <form id='form1' "> <fieldset> <legend>Search titles and tags</legend> <input type='text' name='srch' id='srch' size='50' value='<?=$search?>' placeholder='Search for...' > <input type="hidden" name="page" id="page" value="1"> <input type="hidden" name="action" value="search"> <input type="submit" name="btnSub" value="Search"> </fieldset> <div id='formfoot'></div> </form> <?php if ($showResults) { ?> <div class="paginate_panel"> <?=page_selector($total, $page, PERPAGE)?> </div> <table border='1'> <?=$results?> </table> <?php } ?>
Im trying to connect to a database from php. Heres the code: <?php $dbc = mysqli_connect('192.168.0.122', 'boyyo', 'KiaNNa11', 'aliendatabase') or die('Error connecting to MySQL server.'); $query = "INSERT INTO aliens_abduction (first_name, last_name, " . "when_it_happened, how_long, how_many, alien_description, " . "what_they_did, fang_spotted, other, email) " . "VALUES ('Sally', 'Jones', '3 days ago', '1 day', 'four', " . "green with six tentacles', 'We just talked and played with a dog', " . "'yes', 'I may have seen your dog. Contact me.', " . "'sally@gregs-list.net')"; $result = mysqli_query($dbc, $query) or die('Error querying database.'); ?> I think i have a theory that my MySQL server location is wrong but i dont know. I use HostGator to do this and im using Phpmyadmin. But everytime i type in a form that i created it says Error querying database. Can someone tell me whats wrong with this code. Oh by the way im using head first into PHP and MySQL If the script is not uploaded onto the server you cant use $dbc = mysql_connect('localhost', 'username', 'pass'); so how could I connect in cli? this did not work $dbc = mysql_connect('http://123.456.789.10', 'username', 'pass'); So what can I do? Thanks The following code works: Code: [Select] @ $db = new mysqli('localhost', 'username', 'password', 'database'); if (mysqli_connect_errno()) { echo 'Error: Could not connect to database. Please try again later.'; exit; } $query = "select * from model order by name asc"; $result = $db->query($query); However, I just started to include connect.php to my pages. Now I'm getting an error saying: "Fatal error: Call to a member function query() on a non-object on line 14" Here's my connect.php Code: [Select] .... $db = mysql_select_db($dbase , $connection) or die ("Can't select database."); Line 14 is... $result = $db->query($query); Any ideas? I believe it's the $db variable causing the problem. Never worked with GoDaddy before... Can't get my config script to connect to the database. Here's my code (I'm sure all the login info is correct, except maybe the host name but I copied that from GoDaddy too...) <?php ob_start(); // MySQL connection settings $db_host = "anakdesigns.db.2089823.hostedresource.com"; $db_user = "********"; $db_pass = "********"; $db_name = "********"; // Connect to the database $con = mysql_connect($db_host, $db_user, $db_pass) or die("Cannot connect to DB"); mysql_select_db($db_name) or die("Error accessing DB"); ?> http://www.anakdesigns.com/dev How we can make the connection to ODBC in PHP If any shares the coding part then it would be great. (Table to database) For some reason Im not able to connect to mysql database, when i fill in the form and select search, it just basically refreshes the page but does not come up with no error messages or any results from my database. any help is appreciated. HTML Code Code: [Select] <table id="tb1"> <tr> <td><p class="LOC">Location:</p></td> <td><div id="LC"> <form action="insert.php" method="post"> <select multiple="multiple" size="5" style="width: 150px;" > <option>Armley</option> <option>Chapel Allerton</option> <option>Harehills</option> <option>Headingley</option> <option>Hyde Park</option> <option>Moortown</option> <option>Roundhay</option> </select> </form> </div> </td> <td><p class="PT">Property type:</p></td> <td><div id="PS"> <form action="insert.php" method="post"> <select name="property type" style="width: 170px;"> <option value="none" selected="selected">Any</option> <option value="Houses">Houses</option> <option value="Flats / Apartments">Flats / Apartments</option> </select> </form> </div> </td><td> <div id="ptype"> <form action="insert.php" method="post"> <input type="radio" class="styled" name="ptype" value="forsale"/> For Sale <p class="increase"> <input type="radio" class="styled" name="ptype" value="forrent"/> To Rent </p> <p class="increase"> <input type="radio" class="styled" name="ptype" value="any"/> Any </p> </form> </div> </td> </tr> </table> <div id="table2"> <table id="NBtable"> <tr> <td><p class="NBS">Number of bedrooms:</p></td> <td><div id="NB"> <form action="insert.php" method="post"> <select name="number of bedrooms"> <option value="none" selected="selected">No Min</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> to <select name="number of bedrooms"> <option value="none" selected="selected">No Max</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </form> </div> </td> <td><p class="PR">Price range:</p></td> <td><div id="PR"> <form action="insert.php" method="post"> <select name="price range"> <option value="none" selected="selected">No Min</option> <option value="50,000">50,000</option> <option value="60,000">60,000</option> <option value="70,000">70,000</option> <option value="80,000">80,000</option> <option value="90,000">90,000</option> <option value="100,000">100,000</option> <option value="110,000">110,000</option> <option value="120,000">120,000</option> <option value="130,000">130,000</option> <option value="140,000">140,000</option> <option value="150,000">150,000</option> <option value="160,000">160,000</option> <option value="170,000">170,000</option> <option value="180,000">180,000</option> <option value="190,000">190,000</option> <option value="200,000">200,000</option> <option value="210,000">210,000</option> <option value="220,000">220,000</option> <option value="230,000">230,000</option> <option value="240,000">240,000</option> <option value="250,000">250,000</option> <option value="260,000">260,000</option> <option value="270,000">270,000</option> <option value="280,000">280,000</option> <option value="290,000">290,000</option> <option value="300,000">300,000</option> <option value="310,000">310,000</option> <option value="320,000">320,000</option> <option value="330,000">330,000</option> <option value="340,000">340,000</option> <option value="350,000">350,000</option> </select> to <select name="price range"> <option value="none" selected="selected">No Max</option> <option value="50,000">50,000</option> <option value="60,000">60,000</option> <option value="70,000">70,000</option> <option value="80,000">80,000</option> <option value="90,000">90,000</option> <option value="100,000">100,000</option> <option value="110,000">110,000</option> <option value="120,000">120,000</option> <option value="130,000">130,000</option> <option value="140,000">140,000</option> <option value="150,000">150,000</option> <option value="160,000">160,000</option> <option value="170,000">170,000</option> <option value="180,000">180,000</option> <option value="190,000">190,000</option> <option value="200,000">200,000</option> <option value="210,000">210,000</option> <option value="220,000">220,000</option> <option value="230,000">230,000</option> <option value="240,000">240,000</option> <option value="250,000">250,000</option> <option value="260,000">260,000</option> <option value="270,000">270,000</option> <option value="280,000">280,000</option> <option value="290,000">290,000</option> <option value="300,000">300,000</option> <option value="310,000">310,000</option> <option value="320,000">320,000</option> <option value="330,000">330,000</option> <option value="340,000">340,000</option> <option value="350,000">350,000</option> </select> </form> </div> </td> </tr> </table> PHP Code Code: [Select] <?php $server = ""; // Enter your MYSQL server name/address between quotes $username = ""; // Your MYSQL username between quotes $password = ""; // Your MYSQL password between quotes $database = ""; // Your MYSQL database between quotes $con = mysql_connect($server, $username, $password); // Connect to the database if(!$con) { die('Could not connect: ' . mysql_error()); } // If connection failed, stop and display error mysql_select_db($database, $con); // Select database to use $result = mysql_query("SELECT * FROM tablename"); // Query database while($row = mysql_fetch_array($result)) { // Loop through results echo "<b>" . $row['id'] . "</b><br>\n"; // Where 'id' is the column/field title in the database echo $row['location'] . "<br>\n"; // Where 'location' is the column/field title in the database echo $row['property_type'] . "<br>\n"; // as above echo $row['number_of_bedrooms'] . "<br>\n"; // .. echo $row['purchase_type'] . "<br>\n"; // .. echo $row['price_range'] . "<br>\n"; // .. } mysql_close($con); // Close the connection to the database after results, not before. ?> To connect to my database I an entering mysql database details just at the first top lines server,username,password and database. is thats correct? Thank You for your help in adavance. So I've followed this code, corrected about 12 error, talked to my hosting and I am so done. I have tried everything but the error won't go away. The code is pasted below. As it's really late any help would be appreciated that would make my day the next day...
<?PHP Hi, I found the following tutorial on a list of Top 20 tutorials. However, I have gone through code and there doesn't seem to be any form database connection or config.php fille. So how does this code write to a database if it doesn't connect to a database? http://www.99points.info/2010/07/facebook-style-wallpost-and-comments-system-using-jquery-ajax-and-php-reloaded/ Hi. For a uni assignment I am turning my static prototype into a dynamic prototype and adding various features like templates, log in system and the ability to add/delete information stored on the database and view the information on the website. I have running into a problem though, I am having difficulties getting connected to the database, I don't know if this is something to do with the log in information though, below I have quoted the files. update.php (the script I use to connect to the database) Quote <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ $name = $_POST['name']; $sname = $_POST['sname']; $address = $_POST['address']; $number = $_POST['number']; mysql_connect("localhost", "", "") or die ('error: ' .mysql_error()); mysql_select_db ("bza410_test"); $query="INSERT INTO testTable (id, firstname, surname, address, phone)VALUES ('NULL','".$name."', '".$sname."', '".$address."', '".$number."')"; mysql_query($query) or die ('error updating database'); echo "database updated with: " .$name. " ".$sname." ".$address." ".$number ; ?> after localhost I am aware password/username goes there, just removed them for obvious reasons. home.php Quote <?php $pagetitle = 'Welcome to ENSI'; require 'template/header.php'; ?> <p> This web page page was created on <strong> <?php echo date('l F jS \a\t Y h:i:s A \,'); if (date('H') < 12) { echo ' RISE AND SHINE!!!,'; } else { echo ' TIME TO SLEEP!!!,'; } ?> </strong> on the computer that is running on PHP. </p> <div> <p><strong>Please enter your name and birthday:-</strong></p> <form method="post" action="update.php"> <fieldset> <legend>Details</legend> <label>First Name:</label> <input type="text" name="name" /> <br/> <label> Surname:</label> <input type="text" name="sname" /> <br/> <label> Address </label> <input type="text" name="address" /> <br/> <label>Phone</label> <input type="text" name="number" /> <br/> <input type="submit" name="submit" value="submit" /> <input type="reset" name="reset" value="reset" /> </fieldset> </form> <?php if(isset ($_POST['submit'])) { $name = $_POST['name']; $sname = $_POST['sname']; $address = $_POST['address']; $number = $_POST['number']; echo htmlentities ($text); echo 'Hello, your first name is ' .$name; echo ' Your surname is ' .$sname; echo ' Your address is - ' .$address; echo ', Your phone number is - ' .$number; } ?> </div> <?php require 'template/footer.php'; ?> When I fill in the form and then press submit it goes to "error updating database" from the script, so have I got the server information wrong? Thanks Will. Good day: Im doing a login page for a website, but the mysql database is on a server computer and not on the hosting account. It gives me a cannot select db message. Im using the IP address as the host. This is the script: Code: [Select] <?php ob_start(); $host="000.000.000.000"; // Host name $username="ert4567"; // Mysql username $password="xxxxxxxx"; // Mysql password $port="3306"; $db_name="files"; // Database name $tbl_name="users"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password", "$port")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // username and password sent from form $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" session_register("myusername"); session_register("mypassword"); header("location:login_success.php"); } else { echo "Wrong Username or Password"; } ?> Any help will be appreciated. Hi I have been getting to know PHP OOP concepts, and I started trying by writing a class and handful of functions to connect to the database and retrieve the information from the tables. I went through previous posts having similar titles, but most of them have written using mysql functions and I am using mysqli functions. I want somebody to through this simple script and let me know where the mistake is. This is my class.connect.php: Code: [Select] <?php class mySQL{ var $host; var $username; var $password; var $database; public $dbc; public function connect($set_host, $set_username, $set_password, $set_database) { $this->host = $set_host; $this->username = $set_username; $this->password = $set_password; $this->database = $set_database; $this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB'); } public function query($sql) { return mysqli_query($this->dbc, $sql) or or die('Error:'.mysqli_error($this->dbc).', query: '.$sql); } public function fetch($sql) { $array = mysqli_fetch_array($this->query($sql)); return $array; } public function close() { return mysqli_close($this->dbc); } } ?> This is my index.php: Code: [Select] <?php require_once ("class.connect.php"); $connection = new mySQL(); $connection->connect('localhost', 'myDB', 'joker', 'names_list'); $myquery = "SELECT * FROM list"; $query = $connection->query($myquery); while($array = $connection->fetch($query)) { echo $array['first_name'] . '<br />'; echo $array['last_name'] . '<br />'; } $connection->close(); ?> I am getting a error message "Error:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1, query: 1" Any idea why this is happening? Thanks I have a textbox which i want users to be able to search the database for zipcodes, I can't seem to make it work my IDE doesn't show any errors but when I test the code everything goes blank, the mysql credentials are all correct the code is, any suggestions would help <form action="index.php" method="post"> <label for="search2" style="color:#FFF;background-color:#0A016D"><b>Search Homes by Zipcode</b></label><br> zipcode: <input type="text" name="zipcode"><br> <button type="submit" name="submit" value="submit"/> </form> <?php $zipcode= @$_post['zipcode']; require("myconn.php"); mysql_select_db("phplogin")or die(mysql_error()); $sql= mysql_query("SELECT * FROM users WHERE zipcode='$zipcode' "); $numrow= mysql_num_rows($sql); while($row= mysql_fetch_assoc($sql)) { echo "zipcode: ".$row['zipcode']." city :".$row['city']."<br/>"; } ?> Pls anyone tell me to connect database this is on amensharma.co.uk/testing Code: [Select] <?php $db_link = mysql_connect("amensharma.co.uk","amenshar_admin","amen001"); if (!$db_link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db('amenshar_calender', $db_link); if (!$db_selected) { die ('Can\'t use database : ' . mysql_error()); } ?> this is the error it returns Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'amenshar_admin'@'neptune.servers.rbl-mer.misp.co.uk' (using password: YES) in /home/amenshar/public_html/testing/functions/database.php on line 4 Could not connect: Access denied for user 'amenshar_admin'@'neptune.servers.rbl-mer.misp.co.uk' (using password: YES) bit stumped here any help would be great all the details are correct, just confused why im having these errors Having a major problem connecting to a live site. I have set up the user and database on Cpanel like normal. Then proceeded to insert those details into my mysql connection script Code: [Select] <?php $db_link = mysql_connect("***","****","***"); if (!$db_link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db('amenshar_calender', $db_link); if (!$db_selected) { die ('Can\'t use database : ' . mysql_error()); } ?> I am connecting to domain erban.co.uk, yet looking at the cpanel the master domain is amensharma.co.uk. Is this what the problem could be. This is the error messege it is throwing up Warning: mysql_connect(): Access denied for user '_admin'@'localhost' (using password: YES) in d:\Domains\erban.co.uk\wwwroot\functions\database.php on line 4 Could not connect: Access denied for user '_admin'@'localhost' (using password: YES) What is the better way, in terms of best practice and also speed of storing PHP objects in a database? Is it: Serialize Code: [Select] $SQL = "INSERT INTO my_table (my_object) VALUES ('" . seralize($php_object). "')"; OR JSON Code: [Select] $SQL = "INSERT INTO my_table (my_object) VALUES ('" . json_encode($php_object). "')"; Any idea which is faster serialize() / unserialize() or json_ecode() / json_decode()? |