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;
}
}
}
Related
I am new in Php and MYsql,
I am trying to create a simple query using which contain a variable using php.
however I think I am not writing the querty correctly with the variable since the result of this query is 0.
would be happy for assistance here is my code:
<?php
$phone = $_GET['phone'];
echo $phone;
$query = "SELECT * FROM `APPUsers` WHERE `Phone` LIKE "."'".$phone."' ";
echo $query;
$result = mysqli_query($mysqli, $query);
echo mysqli_num_rows($result);
?>
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM APPUsers WHERE Phone LIKE '%$phone%'";
$result = $conn->query($sql);
Above there is a fast solution , but it is not safe ,
because is vulnerable to injection ...
Below let's see how to do it and why to do it in this way
It is a good practice to store sensible information in a separate file
out of the document root , it means will be not accesible from the web .
So let's create a file configDB.ini for example and put in db informations
servername = something;
username = something;
password = something;
dbname = something;
Once did it we can create a script called dbconn.php and import the file with credentials ,
in this way there is an abstraction between credentials and connection .
in dbconn.php :
$config = parse_ini_file('../configDB.ini');
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
We can even improve the code connecting to db only once and use the same connection all the time we need query .
function db_connect() {
// static will not connect more than once
static $conn;
if(!isset($conn)) {
$config = parse_ini_file('../configDB.ini');
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
return $conn;
}
...
$conn = db_connect();
$sql = "SELECT * FROM APPUsers WHERE Phone LIKE '%$phone%'";
$result = mysqli_query($conn,$sql);
In the end let's say something about mysqli_query
Reasons why you should use MySQLi extension instead of the MySQL extension are many:
from PHP 5.5.0 mysql is deprecated and was introduced mysqli
Why choose mysqli (strenghts)
object oriented
prepared statements
many features
no injection
Do you connect to the database?
The apostrophes around APPUsers and Phone might not be the right ones, as they are not the single apostrophes but some weird squiggly ones.
Try this :
$query = "SELECT * FROM 'APPUsers' WHERE 'Phone' LIKE '".$phone."' ";
We have the following code in the HTML of one of our webpages. We are trying to display all of the Wifi speeds and GPS locations in our database using the MySQL call and while loop shown in the below PHP code. However, it doesn't return anything to the page. We put echo statements in various parts of the PHP (ex. before the while loop, before the database stuff) and it doesn't even print those statements to the webpage.
<body>
<h2>WiFi Speeds in the System</h2>
<p>Speeds Recorded in the System</p>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbc = mysql_connect($hostname, $username, $password)
or die('Connection Error: ' . mysql_error());
mysql_select_db('createinsertdb', $dbc) or die('DB Selection Error' .mysql_error());
$data = "(SELECT Wifi_speed AND GPS_location FROM Instance)";
$results = mysql_query($data, $dbc);
while ($row = mysql_fetch_array($results)) {
echo $row['Wifi_speed'];
echo $row['GPS_location'];
}
?>
</body>
This line is incorrect, being the AND:
$data = "(SELECT Wifi_speed AND GPS_location FROM Instance)";
^^^
Change that to and using a comma as column selectors:
$data = "(SELECT Wifi_speed, GPS_location FROM Instance)";
However, you should remove the brackets from the query:
$data = "SELECT Wifi_speed, GPS_location FROM Instance";
Read up on SELECT: https://dev.mysql.com/doc/refman/5.0/en/select.html
Using:
$results = mysql_query($data, $dbc) or die(mysql_error());
would have signaled the syntax error. Yet you should use it during testing to see if there are in fact errors in your query.
Sidenote:
AND is used for a WHERE clause in a SELECT.
I.e.:
SELECT col FROM table WHERE col_x = 'something' AND col_y = 'something_else'
Or for UPDATE, i.e.:
UPDATE table SET col_x='$var1'
WHERE col_y='$var2'
AND col_z='$var3'
Footnotes:
Consider moving to mysqli with prepared statements, or PDO with prepared statements, as mysql_ functions are deprecated and will be removed from future PHP releases.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
"Thank you for the suggest but we tried that and it didn't change anything. – sichen"
You may find that you may not be able to use those functions after all. If that is the case, then you will need to switch over to either mysqli_ or PDO.
References:
MySQLi: http://php.net/manual/en/book.mysqli.php
PDO: http://php.net/manual/en/ref.pdo-mysql.php
hi mate i see some problem with your DB connection & query
here is example check this out
in SELECT is incorrect, being the AND .using a comma as column selectors:
and make condition for after set query & check data validation that is proper method
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "createinsertdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT `Wifi_speed `, `GPS_location `, FROM `Instance`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['Wifi_speed'];
echo $row['GPS_location'];
}
} else {
echo "0 results";
}
$conn->close();
?>
I am trying to make a blog site.For this purpose I need to use a specific data from a specific field from my database table.To do that I wrote these code.
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
echo $img;
?>
My database connection is OK.It should print like this user_img1.jpg. But it prints the whole sql query like select image from news where uid=1. I run this code on phpmyadmin. It works! But it does not work in my php script.How can I do now?
You can not give the query as it is and expect result like in phpadmin.
For this first of all you have to connect to your DB like this
$con = mysqli_connect("localhost","my_user","my_password","my_db");
execute required query like this
$query22 = "select image from news where uid = 1";
$result22 = mysqli_query($con, $query22) or die (mysqli_error());
Get the result and display like this
while($rows = mysqli_fetch_array($result22, MYSQLI_BOTH))
{
echo "<br>Values in db: " . $rows['columnname'];
}
Also i advice you to take a look at these tutorials
http://codular.com/php-mysqli
http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-prepared-statements/
Please read some PHP 101 kind of tutorials on how to use PHP.
To get data from DB (in almost any language)
You need to connect to a DB. The connection gets you some sort of resource
You formulate your query (which you seem to have done)
You execute the query against the DB that you connected to (step #1)
You get a result (set)
You iterate over the result set to get the individual result(s); in your case the result set would be just one result (or row).
The examples to do this in PHP are very basic; please do your own lookup on net. This one seems good enough to get you started - http://www.w3schools.com/php/php_mysql_intro.asp
Try this,
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
$result=mysql_query($img);
while($row=mysql_fetch_array($result)){
echo '<img src="your_path_to_image/'.$row['image'].'" /> - '.$row['image'];
}
?>
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");
?>
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.