SQL and PHP database access - php

I'm very new to PHP, SQL I've worked with using Coldfusion but only with very simple queries. In coldfusion to access a specific database
<cfquery dbname="blah">
I know in PHP I have to use mysql_query() and mysql_connect(), and here is the code I have, so I understand how to access a server and a table, but not the database. How can this be done?
<?php
$sql_branch = "SELECT BranchNum
FROM Branch WHERE
branchName = '$_POST[branch]'";
$connect = mysql_connect('students','xxxxxxx','xxxxxxx');
if(mysql_query($sql_branch, $connect)) {
$branch = mysql_query($sql_branch, $connect);
}
else {
echo "error".mysql_error();
}
$sql_result = "USE henrybooks;
SELECT AuthorFirst, AuthorLast, OnHand, Title
FROM Inventory i, Wrote w, Author a, Book b
WHERE i.BookCode = b.BookCode AND
i.BookCode = w.BookCode AND a.AuthorNum =
w.AuthorNum AND i.BranchNum = $branch";
if(mysql_query($sql_result, $connect)) {
$result = mysql_query($sql_result, $connect);
}
else {
echo "Error".mysql_error();
}
Also I'm unsure if my Error checking is right, my professor did not really explain how that works exactly.

Find out the database name and select it before making any queries:
$connect = mysql_connect('students','xxxxxxx','xxxxxxx');
mysql_select_db('dbName', $connect);
Documentation for mysql_select_db.

You probably want to use mysql_select_db:
$connect = mysql_connect('students','xxxxxxx','xxxxxxx');
mysql_select_db( "blah", $connect );

Use mysql_select_db to connect to the database. Most of the mysql_ functions should be what you are looking for when working with mysql databases.

Are you looking for mysql_select_db?
You can find all mysql functions here.

Related

Changing mysql_connect to mysqli causes function to fail

To begin with, I am a novice when it comes to PHP and MySQL.
I have a MySQL table called levels that contains two columns: level_id and mapData. Some time ago, I wrote a piece of code using mysql_connect that takes user inputted level_id and fetches the corresponding mapData from the table, and the code works as intended. See below:
<?php
$mysql_host = 'localhost';
$mysql_user = 'username';
$mysql_password = "password";
$mysql_database = 'database';
if (!mysql_connect($mysql_host,$mysql_user,$mysql_password)||!mysql_select_db($mysql_database)){
die('Connection failed');
}
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = mysql_query($query)){
if($query_result = mysql_result($query_run,0,$field)){
return $query_result;
}
}
}
$user_input = mysql_real_escape_string(base64_decode($_GET["level_id"]));
$sql = "SELECT level_id FROM levels WHERE level_id='$user_input'";
$result = mysql_query($sql);
if(mysql_num_rows($result) >0){
$mapData = get_map_data($user_input,'mapData');
print $mapData;
}else{
echo "0";
}
?>
In the case that the user inputs a level_id that does not exist in the database, instead of mapData, he will receive 0. Everything works! I, however, read that mysql_connect is deprecated as of PHP 5.5 and decided to switch from using it in my file to using mysqli:
$conn = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
After changing to mysqli, my get_map_data function has stopped working. I have made certain that the mysqli connection works, but I am simply hitting my head against the wall in making my function work using it. How do I fix my get_map_data function so that it functions again using mysqli?
You can't mix mysqli and mysql_ functions. Furthermore, your mysqli initialization is creating an object, not a resource. Lastly, there is no mysqli_result() function, so therefore we need to emulate what you're trying to do. You wanted the first row 0 and then wanted a specific $field. Below should be what you want.
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = $mysqli->query($query)){
//no mysqli->result() function, so we need to seek to the row.
$query_run->data_seek(0);
if($query_result = $query_run->fetch_assoc()){
return $query_result[$field];
}
}
}
your get_map_data function currently has query running using mysql_query you have to change that to mysqli_query in order to execute:
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = mysqli_query($conn,$query)){
if($query_result = mysqli_result($query_run,0,$field)){
return $query_result;
}
}
}

Basic PHP Object Oriented MYSQL Query

So I've been learning for about 3 months now and am currently using very old procedural techniques and the deprecated mysql extension in my code. So time to take a step forward, ditch my procedural ways and get into object oriented / prepared statements...
This is very basic but I guess everyone has to learn some day. I'm trying to get retrieve and simple dataset from mysql database..
so far I have my connection:
$useri = new mysqli('localhost', 'useri', 'xxx','yyy');
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
I get no errors so I assume this works, and I have my query:
$test_query = "SELECT * FROM t";
$test_query = $useri->real_escape_string($test_query);
echo $test_query;
if($result = $useri->query($test_query)){
while($row = $useri->fetch_object($result)){
echo $row->id;
}
$result->close();
}
$useri->close();
However I get no results... so, 2 questions:
a. what am I doing wrong? and
b. anyone recommend any good tutorials apart from the php manual for this stuff?
Thanks :)
This works for one of the table i have in my db:
$useri = new mysqli('localhost', 'useri', 'xxx','yyy');
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$test_query = "SELECT * FROM t";
$test_query = $useri->real_escape_string($test_query);
if($result = $useri->query($test_query)){
while ($row = $result->fetch_object()) { //only this is changed
echo $row->id;
}
$result->close();
}else{ //check for error if query was wrong
echo $useri->error;
}
$useri->close();
make sure that you have a space after *
$test_query = "SELECT * FROM t";
check this tutorial
http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

mysql vs mysqli config file and queries

I need start using the mysqli extension but I'm finding all kinds of conflicting info depending on how all the info is that I'm trying to use.
For example, my header connects to a 'config.php' file that currently looks like this:
<?php
$hostname_em = "localhost";
$database_em = "test";
$username_em = "user";
$password_em = "pass";
$em = mysql_pconnect($hostname_em, $username_em, $password_em) or trigger_error(mysql_error(),E_USER_ERROR);
?>
But when I go to php.net I see that I should be using this but after updating everything I get no database.
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
?>
I also went through and added an "i" to the following code in my site and again no luck:
mysql_select_db($database_em, $em);
$query_getReview =
"SELECT
reviews.title,
reviews.cover_art,
reviews.blog_entry,
reviews.rating,
reviews.published,
reviews.updated,
artists.artists_name,
contributors.contributors_name,
contributors.contributors_photo,
contributors.contributors_popup,
categories_name
FROM
reviews
JOIN artists ON artists.id = reviews.artistid
JOIN contributors ON contributors.id = reviews.contributorid
JOIN categories ON categories.id = reviews.categoryid
ORDER BY reviews.updated DESC LIMIT 3";
$getReview = mysql_query($query_getReview, $em) or die(mysql_error());
$row_getReview = mysql_fetch_assoc($getReview);
$totalRows_getReview = mysql_num_rows($getReview);
And here's the only place on my display page that even mentions mysql so far:
<?php } while ($row_getReview = mysql_fetch_assoc($getReview)); ?>
I did see something at oracle that another stackoverflow answer pointed someone to that updates this stuff automagically, but I have so little code at this point it seems like overkill.
Adding an i to any mysql function won't make it a valid mysqli function. Even if such function exists, maybe the parameteres are different. Take a look here http://php.net/manual/en/book.mysqli.php and take some time to check mysqli functions. Maybe try some examples to become familiar with the way things work. I also reccomend you to choose either object oriented code, either procedural. Don't mix them.
I just made the switch to mysqli lately, took me a few hours to wrap my head around it. It works well for me, hope it will help you out a bit.
Here the function to connect to the BD:
function sql_conn(){
$sql_host = "localhost";
$sql_user = "test";
$sql_pass = "pass";
$sql_name = "test";
$sql_conn = new mysqli($sql_host, $sql_user, $sql_pass, $sql_name);
if ($sql_conn->connect_errno) error_log ("Failed to connect to MySQL: (" . $sql_conn->connect_errno . ") " . $sql_conn->connect_error);
return $sql_conn;
}
This will return a Mysqli Object that you can use to make you request afterward. You can put it in your config.php and include it or add it at the top of your file, whatever works the best for you.
Once you have this object, you can use it to make your query against the object like so: (in this case, if an error came up it will be outputted in the error_log. I like having it there, you can echo it instead.
//Use the above function to create the mysqli object.
var $mysqli = sql_conn();
//Create the query string (truncated for the example)
var $query = "SELECT reviews.titl ... ... ted DESC LIMIT 3";
//Launch the query on the mysqli object using the query() method
if(!($results = $mysqli->query($query))){
//It it fails, log the error
error_log(mysqli_error($mysqli));
}else{
//Manipulate your data.
//here it depends on what you retunr, a single value, row or a list of rows.
//Example for a set of rows
while ($record = $results->fetch_object()){
array_push($array, $record);
}
}
//Just to show, this will output the array:
print_r($array);
//Close the connection:
$mysqli->close();
So basically, in mysqli, you create an object and use the method to work your way out.
Hope this helps. Once you figured it out, you will most likely enjoy mysqli more that mysql. I did anyway.
PS: Please note that this was copy/pasted from existing, working code. Might have some typo, and might forgot to change a var somewhere, but it's to give you an idea of how mysqli works. Hope this helps.

Mysql Query, comparing values and assigning to PHP variables

I have done a fair bit of research into what i want to do, although i haven't found anything. I am not too sure if i am looking for the right thing :( I am also a little bit new to PHP and MySQL syntax, so please be kind.
I wish to perform the following in this order:
Connect to a database (DONE)
Query for a specific string (I think im done)
From here is gets a bit fuzzy :(
If a match is found for the variable, copy the whole row (I need other variables).
Assign the values from the SQL query to a PHP variables.
From there i will be right to carry on.
I have established the connection to the database with the following:
function connect() {
$dbname = 'database';
$dbuser = 'username';
$dbpass = 'password';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
}
And then calling the function connect();
I then wish to query the database for a particular value, for the sake of this argument i will use a static value. This is what i have:
mysql_select_db(DATABASENAME) or die( "Unable to select database");
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'";
$result=mysql_query($query);
From here i am not too sure how to compare the query result to see if it is a match (something along the lines of mysql rows?).
If there is a match, then i would like to obtain the entire row, and assign each value to a php variable.
I am not asking for you to do it for me, simply i kick in the right direction should be fine!
Hope it explains it enough :)
Thanks for your kind guidance
Ok. You will want to keep the connection to the mysql database somewhere. A common use is $conn.
So you would have
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
Then, either from the URL or Post, or just some variables you have sitting in your php file, you can query the database by putting the variables in the query itself. Also, here you can use $conn so that you have one place to connect to the database, in an include for example, and you won't have to make all of the connection string in each place you need to connect to the DB.
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%" . $varToCompare . "%'";
$result=mysql_query($query,$conn);
Above you are using a like. You may want to just look at doing .. Where column=$var.
Then you can use php to spin through the results into an array (for queries where would get multiple rows).
Where the hell you learned how to use MySQL in PHP ? The mysql_* functions are more then 10 years old and not maintained anymore. Community has already begun to work on deprecating them.
You should be using PDO or MySQLi for that.
// connection to database
$db = new PDO('mysql:host=localhost;dbname=datadump_pwmgr;charset=UTF-8',
'datadump_pwmgr',
'kzddim05xrgl');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// setting up prepared statement for the query
$statement = $db->prepare('SELECT * FROM table WHERE column LIKE :value');
$statement->bindParam(':value', $some_variable, PDO::PARAM_STR, 127);
// executing query and fetching first result
if ( $statement->execute())
{
$data = $statement->fetch(PDO::FETCH_OBJ);
var_dump( $data );
}
This should give you something like what you needed. Though, I would recommend to try this tutorial. And learning more about prepared statements could be useful too.
Also , if you are working with objects, then it is possible to create a single DB connection object , and pass it to multiple other classes to use it:
$pdo = new PDO('sqlite::memory:');
$a = new Foo( $pdo );
$b = new Bar( $pdo, 'something');
This way you pass both objects the same database connection, and you do not need to reinitialize it.
I think you're looking for something like this:
$count = mysql_num_rows($result);
//if there is more then 1 record retrieved from the database
if($count > 0)
{
//Do what ever you want to do here, which I think you want to be
while ($row = mysql_fetch_assoc($result))
{
echo $row["Columnname1"];
echo $row["Columnname2"];
echo $row["Columnname3"];
}
}
else
{
echo "There are no matches for this specific value";
}
You can get the queried data by rows as an associated array using mysql_fetch_array():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_array($data)) !== false)
{
echo "row = $row, name1 = " . $result["name1"] . ", name2 = " . $result["name2"];
$row ++;
}
... or as an objects using mysql_fetch_object():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_object($data)) !== false)
{
echo "row = $row, name1 = $result->name1, name2 = $result->name2";
$row ++;
}
I'm not too sure of what you want, but I can see one probable bug here: you're using LIKE in a way which means =: in order to have LIKE to behave like a like, you need some joker chars :
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'" // This will return all rows where column='VAUL'
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'" // This will return all rows where column='%VAUL%' // This will return any row containing 'VAUL' in column
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE'" // This will return all rows where column='%VAUL' // this will return all rows ending by VAUL. I guess you get it now :)
An to retrieve the actual results:
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'";
$result=mysql_query($query);
while (false !== ($row = mysql_fetch_assoc($result))) {
//here $row is an array containing all the data from your mysql row
}
Try to write the database connection in another page no need to use function and include that page in where ever you need.
ex: require_once 'dbConnect.php';
dbConnect.php consists:
<?php
$dbname = 'datadump_pwmgr';
$dbuser = 'datadump_pwmgr';
$dbpass = 'kzddim05xrgl';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
?>

How does one implement a MySQL database into a webpage?

I am a complete database newbie. So far, I know that I can connect to MySQL using PHP's mysql_connect() command, but apart from that, I really don't see how to take that data and put it onto a web page.
a) are there ways other than mysql_connect()
b) lets say I had a table of data in mysql and all I wanted was for that table (for example: list of names and telephone numbers) to now appear on my web page. I can't for the life of me find a tutorial for this.
<?
$database_name = "dbname";
$mysql_host = "localhost"; //almost always 'localhost'
$database_user = "dbuser";
$database_pwd = "dbpass";
$dbc = mysql_connect($mysql_host, $database_user, $database_pwd);
if(!$dbc)
{
die("We are currently experiencing very heavy traffic to our site, please be patient and try again shortly.");
}
$db = mysql_select_db($database_name);
if(!$db)
{
die("Failed to connect to database - check your database name.");
}
$sql = "SELECT * FROM `table` WHERE `field`= 'value'";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
// code here
// access variables like the following:
echo $row['field'].'<br />';
echo $row['field2'];
}
?>
Check out mysql_fetch_assoc mysql_fetch_array and mysql_fetch_object
This is the very basics, you will want to search for tutorials. There are many about.

Categories