I'm new to php. I have this piece of code:
<?php
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$db = mysql_connect("localhost", "root", "usbw");
$sdb = mysql_select_db("test", $db);
$sql = "SELECT * FROM config WHERE id=$id";
$mq = mysql_query($sql) or die("not working query");
$row = mysql_fetch_array($mq);
?>
And from this code, I want to make a function, but how?
What I'm trying to do is linking my MySQL database to my PHP code, and I also try to use the GET[id] to auto change my page if a change my id.
This piece of code does work, but I want to change it into a function. But I don't know how to start.
Here's an example of a function around your query, mind you it's just an example, as there are many improvements to make.
Such as not using the mysql_* api and moving towards PDO or mysqli_*
But it should be enough to get you started
<?php
// your if logic stays unchanged
$db=mysql_connect("localhost","root","usbw");
$sdb=mysql_select_db("test",$db);
function getConfig($id,$db){
$sql="SELECT * FROM config WHERE id=$id";
$mq=mysql_query($sql);
if ($mq) {
return mysql_fetch_array($mq);
}
else {
return false;
}
}
$results = getConfig($id,$db);
if ($results==false) {
print "the query failed";
}
else var_dump($results);
You can make a file named db.php including some common db functions so you will be able to use them easier:
<?php
function db_connection() {
//SERVER, USER, MY_PASSWORD, MY_DATABASE are constants
$connection = mysqli_connect(SERVER, USER, MY_PASSWORD, MY_DATABASE);
mysqli_set_charset($connection, 'utf8');
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
return $connection;
}
function db_selection() {
$db_select = mysqli_select_db(MY_DATABASE, db_connection());
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
return $db_select;
}
function confirm_query($connection, $result_set) {
if (!$result_set) {
die("Database error: " . mysqli_error($connection));
}
}
function q($connection, $query) {
$result = mysqli_query($connection, $query);
confirm_query($connection, $result);
return $result;
}
?>
Then, you can have your code in some other files:
<?php
require_once('db.php'); //This file is required
$id = $_GET['id']; //Shorthand the $_GET['id'] variable
if (!isset($id)) {
die("missing query parameter");
}
if ( filter_var($id, FILTER_VALIDATE_INT) === false) ) {
die("Invalid query parameter");
}
$sql = "SELECT * FROM config WHERE id = '$id'";
$result = q($connection, $sql);
while ($row = mysqli_fetch_array($result)) {
//Do something
}
?>
Try not to use mysql_* functions because they are deprecated. Use mysqli_* or even better try to learn about prepared statements or PDO.
Related
I want to create service which every second checking incoming orders in database and doing some stuff. Now I'm using php5.6 and mysql but I'm not sure this is good for that.
Sorry for my code, but now I'm doing like this:
for ($x=0; $x < 999999999999; $x++)
{
$query1 = mysql_query("SELECT * FROM `orders`");
while ($row = mysql_fetch_assoc($query1)) {
//doing some stuff here
}
sleep(1);
}
It works about 12 hours and when crashing with error.
Is there better solution for that or maybe is better to choose different language ?
Your 999999999999 will get reached.
Try something like this:
<?php
$link = mysqli_connect("localhost", "username", "password", "database");
if(!$link) {
die("Could not connect to MySQL database.");
}
while(1) {
$query = "SELECT * FROM YOUR_TABLE";
$res = mysqli_query($link, $query);
if(!$res) {
die("Could not execute query: " . mysqli_error($link));
}
while($row = mysqli_fetch_assoc($res)) {
// Do stuff here
}
sleep(1);
}
I am new to mysqli and was going through a tutorial from: http://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17#comment1
I was able to connect to my database using this:
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if($connection === false) {
die('Connection failed [' . $db->connect_error . ']');
}
echo("hello"); //this worked!
But then I tried wrapping it in a function (as discussed in the tutorial)... I saw that you call the connection function from another function... in the tutorial each function keeps getting called from another and another... and I never quite found where the initial call started from to get the domino effect of functions calling eachother.. so anyway, I tried to stop it at two just to test and teach myself.. but it's not working and I don't know why:
function db_connect() {
static $connection;
if(!isset($connection)) {
$config = parse_ini_file('../config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
echo("hello2");
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
echo("hello1");
}
db_query("SELECT `Q1_Q`,`Q1_AnsA` FROM `Game1_RollarCoaster`"); //this didn't work :(
Well I ended up taking it out of the functions and made the code super simple (sticking with procedural instead of OOP even though a lot of tutorials use OOP - thought it was better to start this way):
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_Q] . '<-- Here is your question! ' . $row[Q1_AnsA] . '<-- Here is your answer! ';
echo '<br />';
}
mysqli_free_result($result);
mysqli_close($link);
?>
Here's a simple mysqli solution for you:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
If you're grabbing more than one row, I do it like this:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With Error Handling: If there is a fatal error the script will terminate with an error message.
// ini_set('display_errors',1); // Uncomment to show errors to the end user.
if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) die('Database Error: '.$db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With try/catch exception handling: This lets you deal with any errors all in one place and possibly continue execution when something fails, if that's desired.
try {
if ( $db->connect_errno ) throw new Exception("Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
} catch (Exception $e) {
echo "DB Exception: ",$e->getMessage(),"\n";
}
This is my first post so please bear with me with inputting the code into here. Im trying to output some images to a PDF and need to create a if statement that looks for data with in a row.
$connection = mysql_connect("localhost", "testdb", "********")
or die ("Unable to connect!");
// select database
mysql_select_db("testdb") or die ("Unable to select database!");
// Select all the rows in the test table
$query = "SELECT * FROM test2 WHERE testid=89";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while ($row= mysql_fetch_array($result)) {
$image = $row[1];
$text = $row[2];
}
That's what I have so far and basically I need something along the line of this:
If (data in row 1) {
print $image;
} else {
print $text;
}
It's hard to say exactly what you're looking for since it isn't very clear, but I think what you're wanting to do is check to see if $image has a value, and if so, display it. If not, display $text instead.
If this is the case use empty(). It will tell you if a variable is empty or not.
if (!empty($image))
{
print $image;
}
else
{
print $text;
}
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
looks like you just need to test for data in $image
if(!empty($image))
{
echo $image;
}
else
{
echo $text;
}
if( !empty($row[1]) ) {
...
Use isset to check variable.
Like
if(isset($images) !='')
{
echo $images;
}
Although you are using old mysql_* functions which are depreciated, you are almost there
$connection = mysql_connect("localhost", "testdb", "********") or die ("Unable to connect!");
// select database
mysql_select_db("testdb") or die ("Unable to select database!");
// Select all the rows in the test table
$query = "SELECT * FROM test2 WHERE testid=89";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while ($row= mysql_fetch_array($result))
// This will only be called if there is a matching result.
{
echo $row[1];
echo $row[2];
}
Edit: Here is a cut and paste of a section of a query that happen to be open in eclipse:
$arrKPIData = Array();
try{
$dbh = new PDO($this->mySQLAccessData->hostname, $this->mySQLAccessData->username, $this->mySQLAccessData->password);
$stmt = $dbh->query($sql);
$obj = $stmt->setFetchMode(PDO::FETCH_INTO, new kpiData);
$dataCount=0;
foreach($stmt as $kpiData)
{
$arrKPIData[$dataCount]['year']=$kpiData->year;
$arrKPIData[$dataCount]['month']=$kpiData->month;
$arrKPIData[$dataCount]['measure']=$kpiData->kpiMeasure;
$arrKPIData[$dataCount]['var1']=$kpiData->var1;
$arrKPIData[$dataCount]['var2']=$kpiData->var2;
$dataCount++;
unset($stmt);
}
unset($dbh);
}
catch(PDOException $e){
echo 'Error : '.$e->getMessage();
exit();
}
unset($arrKPIData);
I am populating a simple array with data before I cleanse it and convert it into a class further in the code.
I was wondering if there's a way in PHP to list all available databases by usage of mysqli. The following works smooth in MySQL (see php docs):
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
}
Can I Change:
$db_list = mysql_list_dbs($link); // mysql
Into something like:
$db_list = mysqli_list_dbs($link); // mysqli
If this is not working, would it be possible to convert a created mysqli connection into a regular mysql and continue fetching/querying on the new converted connection?
It doesn't appear as though there's a function available to do this, but you can execute a show databases; query and the rows returned will be the databases available.
EXAMPLE:
Replace this:
$db_list = mysql_list_dbs($link); //mysql
With this:
$db_list = mysqli_query($link, "SHOW DATABASES"); //mysqli
I realize this is an old thread but, searching the 'net still doesn't seem to help. Here's my solution;
$sql="SHOW DATABASES";
$link = mysqli_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql: ' . mysqli_error($link).'\r\n');
if (!($result=mysqli_query($link,$sql))) {
printf("Error: %s\n", mysqli_error($link));
}
while( $row = mysqli_fetch_row( $result ) ){
if (($row[0]!="information_schema") && ($row[0]!="mysql")) {
echo $row[0]."\r\n";
}
}
Similar to Rick's answer, but this is the way to do it if you prefer to use mysqli in object-orientated fashion:
$mysqli = ... // This object is my equivalent of Rick's $link object.
$sql = "SHOW DATABASES";
$result = $mysqli->query($sql);
if ($result === false) {
throw new Exception("Could not execute query: " . $mysqli->error);
}
$db_names = array();
while($row = $result->fetch_array(MYSQLI_NUM)) { // for each row of the resultset
$db_names[] = $row[0]; // Add db name to $db_names array
}
echo "Database names: " . PHP_EOL . print_r($db_names, TRUE); // display array
Here is a complete and extended solution for the answer, there are some databases that you do not need to read because those databases are system databases and we do not want them to appear on our result set, these system databases differ by the setup you have in your SQL so this solution will help in any kind of situations.
first you have to make database connection in OOP
//error reporting Procedural way
//mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//error reporting OOP way
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL & MYSQLI_REPORT_STRICT;
$conn = new mysqli("localhost","root","kasun12345");
using Index array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_NUM)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row[0] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row[0];
}
}
same with Assoc array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row["Database"] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row["Database"];
}
}
same using object of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($obj = $result->fetch_object()){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if( $obj->Database == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'. $obj->Database;
}
}
PHP:
function generate_uid() {
$uid = mt_rand();
$sql = "SELECT user_id
FROM user_registration";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
$result = mysql_query($sql);
$availability = TRUE;
while($row = mysql_fetch_array($result)) {
if($row['user_id'] == $uid) {
$availability = FALSE;
}
}
if($availability == FALSE) {
generate_uid();
}
}
The error
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in E:\Web Design EC\register2.php on line 8
Error:
But when i execute this function as normal php there is no error and the $uid is generated. What maybe the problem??
$con is not defined in the current variable scope. You can pass the connection to function as a parameter:
function generate_uid($con) {
...
mysql_query($sql, $con);
}
$uid = generate_uid($con);
Or you can use global:
function generate_uid() {
global $con;
...
mysql_query($sql, $con);
}
$uid = generate_uid();
Or, simply leave the connection variable out, and the last opened connection will be used:
function generate_uid() {
...
mysql_query($sql);
}
$uid = generate_uid();
All of those should work.
To learn more about variable scope, check out the PHP manual on the subject at:
http://www.php.net/manual/en/language.variables.scope.php
You are using $con in your function, but $con is not defined in your function scope.
http://php.net/manual/en/language.variables.scope.php
You need to either
a) Pass $con to your function or
b) Set $con as a global
c) Not use $con at all eg.
if (!mysql_query($sql))
however make sure that your app is only connecting to ONE database, otherwise you will run into issues because when you don't specify a connection it will use the last connection opened.
Inside your function, your MySQL connection doesn't exist. You either need to pass it in, or use the global keyword:
$con = mysql_connect('localhost', 'mysql_user', 'mysql_password');
function generate_uid()
{
global $con;
$uid = mt_rand();
$sql="SELECT user_id FROM user_registration";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query($sql);
$availability=TRUE;
while($row = mysql_fetch_array($result))
{
if($row['user_id']==$uid)
{
$availability=FALSE; }
} if($availability==FALSE) { generate_uid(); }
}
while($row = mysql_fetch_array($result))
You can't use that if you plan to use $row as an associative array. Use:
while($row = mysql_fetch_assoc($result))
instead.
EDIT
MYSQL_BOTH is turned on by default, forgot about that. The problem is pointed out by the other users, regarding the connection not being available in the function scope.