I currently have a php file with html code in it. At the beginning of the body tag im including a dbcon.php which contains a db connection, a query and a fetch_result. I now want to use those results later in the html file but i cant get it to work.
Website-file looks like this:
<html>
<head>...</head>
<body>
<?php include("dbcon.php"); ?>
...
<some html stuff>
...
<? here i want to use the data from the query ?>
...
</body></html>
The dbcon.php simply contains the connection, the query and the fetch_results.
edit:
dbcon:
<?php
$con=mysql_connect("localhost:8889","user","pw","db");
$result_query = mysql_query($con,"SELECT * FROM table");
$results = mysql_fetch_array($results_query);
?>
I cant access the data in the lower part of the html file.
Your code is "right", in that you don't need anything more to access your dbcon.php variables.
But you're mixing mysql_ and mysqli_ syntax :
mysql_query take as first parameter the query, not the connexion
mysqli_query take as first parameter the connexion, and the query as second one
You should use mysqli_ :
$con = mysqli_connect("localhost:8889","user","pw","db");
$result_query = mysqli_query($con, "SELECT * FROM table");
$results = mysqli_fetch_array($results_query);
Another version, object oriented :
$mysqli = new mysqli("localhost:8889", "user", "pw", "db");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$results = array();
if ($result_query = $mysqli->query("SELECT * FROM table")) {
$results = $result_query->fetch_array();
}
don't use mysql_ function,it is depricated.
anyway you use wrong variable name. $results_query in mysql_fetch_array($results_query) so change it to $result_query and it might work.
<?php
$con=mysql_connect("localhost:8889","user","pw","db");
$result_query = mysql_query("SELECT * FROM table");
$results = mysql_fetch_array($result_query );
?>
Related
I'm using include connection file to connect to the database. My challenge is how do I fetch from the database this is where am stuck.
include 'connection.php';
$sql = 'SELECT * FROM country';
$results = mysqli_query($sql);
assume your connection.php contain
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
So the in your file, you're using include 'connection.php' to get the connection. By using include its act like single page now. Then you've to use it like below
require_once 'connection.php';
$sql= 'SELECT * FROM country';
$results = mysqli_query($con, $sql); # add connection string to query
Explanation
when you add this include 'connection.php'; then whatever the data on parent(connection.php) file (ex: variable, Functions, etc ..) will come to child.
Links to refer
In PHP, how does include() exactly work?
Are PHP include paths relative to the file or the calling code?
include, include_once, require or require_once?
I am trying to get the results of a SQL query using WHERE, whenever I use the $_GET variable it doesn't work, now I have echoed the $query variable and it shows the value of $_GET['idced'] but for some reason it doesn't do the query thus the loop doesn't show anything.
But when I manually type in the value that I want to compare, it works perfectly fine... any help would be greatly appreciated.. I also know that their might be some security issues with using GET but its a local app so it's not a concern.. heere is the code I have:
<?php
$mysqli = new mysqli("localhost", "cx", "", "cxtrack");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$idced_history = mysqli_real_escape_string($mysqli, $_GET['idced']);
//This is the query that is not working:
$query = "SELECT * FROM applications WHERE idced = $idced_history;";
if ($result = $mysqli->query($query)) {
//This loop works fine when I replace $idced_history with a value of idced
while ($row = $result->fetch_assoc()) {
$curenttime=$row["applicationposition"];
$time_ago =strtotime($curenttime);
echo "<div style='background:red; position:relative; top:2.6em; margin-bottom:1%;'>";
echo "<a href='#'>".$row["applicationposition"]."</a><br/>";
echo "Applied On: ".$row["applicationdate"]." ( ". timeAgo($time_ago) ." ) <br>";
echo "Via: ".$row["applicationtype"]."</div>";
}
$result->free();
}
$mysqli->close();
?>
sometime it not work that way.. try change to:
$query = "SELECT * FROM applications WHERE idced = ".$idced_history;
It didn't work because, idced you get from url is a string and you should spare strings from the sql query with single quotes. Otherwise, mysql act like to your variable as a table name.
try
"SELECT * FROM applications WHERE idced = '$idced_history'";
I need help with the follow code to change it from Procedural to Prepared Statement. I will do my best to code it:
Default procedural script MYSQLI default
<?php
$conn = mysqli_connect ('localhost', 'gggggg', 'gggggg') ;
mysqli_select_db ($conn, 'ggggg');
$anti_injection = mysqli_real_escape_string($_GET['user']);
$sql = "SELECT * FROM profiles WHERE username =".$anti_injection);
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($sql)) {
$username = stripslashes($row['username']);
$age = stripslashes($row['age']);
$gender = stripslashes($row['gender']);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title</title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
CATEGORY <?php echo $username; ?>
TITEL <?php echo $age; ?>
CONTENT <?php echo $sex; ?>
</body>
</html>
<?php
}
?>
#
NOW MY CHANGES TO STATEMENTS HOPE IT WORKS
#
$query = $sql->prepare("SELECT * FROM profiles WHERE `username`=?")
$prep->bind_param("s",$anti_injection);
$prep->execute();
Thats all I know for the SELECT in a safe mode but then with the MYSQLI_FETCH_ARRAY I really dont know it it will work and hopefully if there is a chance to keep the script the way I like with the echos between the HTML BODY page
Some Example On How it must be done?
First off, I highly recommend you not mix procedural with objects. It will get confusing much faster that way. Consider using the mysqli object instead.
$mysqli = new mysqli('localhost'...);
Second, you're close but, as I said, you're mixing objects and procedural so the way you've changed it won't work. Plus you're bouncing variables all over the place (if you ran your changes raw it would fail). Assuming you switch to the mysqli object as outlined above, you can do this
$prep = $mysqli->prepare("SELECT * FROM profiles WHERE `username`=?");
$prep->bind_param("s",$anti_injection);
$prep->execute();
Now, the next part is tricky. You have to have mysqlnd installed to do this but it's the best way to get your results back. If you run this and get an error about get_result being missing, you're not running mysqlnd
$result = $prep->get_result();
while($row = $result->fetch_array()) {
//Your HTML loop here
}
I provide a script, based on yours, that i have commented, tested, and uses procedural 'mysqli'. Hopefully, it will clarify things.
<?php
/* (PHP 5.3.18 on XAMPP, windows XP)
*
* I will use the procedural 'mysqli' functions in this example as that is
* what you seem familiar with.
*
* However, the 'object oriented' style is preferred currently.
*
* It all works fine though :-)
*
* I recommend PDO (PHP Data Objects) as the way to go for Database access
* as it provides a 'common' interface to many database engines.
*/
// this is an example 'select' parameter -- how this value gets set is up to you...
// use a form, get parameter or other, it is not important.
$bindparamUsername = 'user_2'; // example!!!!
// connect to the database...
$dbConnection = mysqli_connect('localhost', 'test', 'test'); // connect
mysqli_select_db($dbConnection, 'testmysql'); // my test database
// the SQL Query...
// the '?' is a placeholder for a value that will be substituted when the query runs.
// Note: the ORDER of the selected Columns is important not the column names.
//
// Note: The number of selected columns is important and must match the number of
// 'result' bind variables used later.
$sql = "SELECT username, age, gender FROM profiles WHERE username = ?";
// DB engine: parse the query into an internal form that it understands
$preparedQuery = mysqli_prepare($dbConnection, $sql);
// bind an actual input PHP variable to the prepared query so the db will have all required values
// when the query is executed.
//
mysqli_stmt_bind_param($preparedQuery, 's', $bindparamUsername);
// run the query...
$success = mysqli_execute($preparedQuery);
// You can only bind which variables to store the result columns in AFTER the query has run!
//
// Now bind where any results from the query will be returned...
// There must be as many 'bind' variables as there are selected columns!
// This is because each column value from the query will be returned into the
// 'bound' PHP variable.
//
// Note: You cannot bind to an array. You must bind to an individual PHP variable.
//
// I have kept the same names but they are only of use to you.
$fetchedRow = array( 'username' => null,
'age' => null,
'gender' => null);
/*
* Note: order of columns in the query and order of destination variables in the 'bind' statement is important.
*
* i.e. $fetchedRow[username] could be replaced with variable $firstColumn,
* $fetchedRow[age] could be replaces with variable $secondColumn
* and so on...
*
* There must be as many bind variables as there are columns.
*/
mysqli_stmt_bind_result($preparedQuery, $fetchedRow['username'],
$fetchedRow['age'],
$fetchedRow['gender']);
/*
* Note: if you use the 'Object Oriented' version of 'mysqli': All of this is 'hidden'
* but still happens 'behind the scenes'!
*
*/
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
<?php // each 'fetch' updates the $fetchedRow PHP variable... ?>
<?php while (mysqli_stmt_fetch($preparedQuery)): ?>
<br />
CATEGORY <?php echo $fetchedRow['username']; ?>
<br />
TITEL <?php echo $fetchedRow['age']; ?> <br />
CONTENT <?php echo $fetchedRow['gender']; ?> <br />
<?php endwhile ?>
</body>
</html>
If you'r learning I encourage you to use Object Oriented Style
The Manual is the first resource where you can find the most accurate information. Following your example:
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//Here you avoid the warning undefine variable if $_GET['user'] ins't set
$user = isset($_GET['user']) ? $_GET['user'] : NULL;
$row = array();
//Checking if $user is NULL
if(!empty($user)){
// Prepared statement, stage 1: prepare
if (!($stmt = $mysqli->prepare("SELECT * FROM profiles WHERE `username`=?"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$stmt->bind_param("s", $user)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
//Fetching the result
$res = $stmt->get_result();
$row = $res->fetch_assoc();
/* explicit close recommended */
$stmt->close();
}else{
//do this code if $user is null
}
//Printing out the result
echo '<pre>';
print_r($row);
echo '</pre>';
you can do it like that
$link = mysqli_connect("localhost", "my_user", "my_password", "db"); //Establishing connection to the database , this is alias of new mysqli('')
$query="SELECT * FROM profiles WHERE `username`=?";
$stmt = $link->prepare($query);
$stmt->bind_param("s",$anti_injection); // binding the parameter to it
$stmt->execute(); //Executing
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)) // we used MYSQLI_ASSOC flag here you also can use MYSQLI_NUM or MYSQLI_BOTH
{
//Do stuff
}
I have a project (exisiting) and I am ordered to continue it
but there's something strange
in my connection
<?php
include "adodb5/adodb.inc.php";
$config['mysqlhost'] = 'localhost';
$config['mysqluser'] = 'xxx';
$config['mysqlpass'] = 'yyy';
$config['mysqldb'] = 'zzz';
$DB = ADONewConnection('mysql');
$DB->Connect($config['mysqlhost'],$config['mysqluser'],$config['mysqlpass'],$config['mysqldb'],true);
?>
and if I try to call query (same queries as below) from this page, it works (and when I echo, it shows the value)
So I go to other page
<?
include ("inc/con.php");
?>
<?php
$sql = ("SELECT * FROM table");
$query = mysql_query($sql)or die($myQuery."<br/><br/>".mysql_error());
$result = mysql_fetch_array($query);
echo $result ['table id'];
?>
and the result is
Notice: Undefined variable: myQuery in C:\xampp\htdocs\d88\www\mypage.php on line 9
No database selected
is there anything wrong with it?
since i try on con page, it works and when i include it to other page, it not working
You are not defining any $myQuery either in inc/con.php nor in the same file itself. Also you are not selecting any database with mysql_select_db:
mysql_select_db($config['mysqldb']);
You are suggest, also, not to use mysql_* functions as they are going to be deleted and are yet deprecated (and you can use PDO or mysqli).
Notice: I think $sql = ("SELECT * FROM table") gets evaluated as $sql = true.
You can not connect with ADODB connection and establish a query with mysql_query.
the syntax is something like this mysql_query ($query ,$con). $con is optional but if you do not specify it, the last link opened by mysql_connect() is assumed; but you have not any mysql_connect() statement before
because of my version of php, i must use <?php ?> instead of <? ?>
thanks for helping
I have created two functions one for connecting to MySQL database and one for running a specific query.
I enter the database name as parameter for first function to connect to the database, this works fine, but my problem is with the second one.
2nd function returns the $result from running a query, but when I use mysql_fetch_array with the $result, it gives one output even if it supposed to give more than one.
As I am no php expert so i can't find the solution. Please help me.
Here is the code:
File Function.php
<?php
function myconnect($data)
{
$db_host='localhost';
$db_user='root';
$db_pwd='';
$data=$data;
$dbc = mysqli_connect($db_host, $db_user,$db_pwd,$data) or die (mysql_error());
return $dbc;
}
function runquery($db,$table,$tcol,$tid)//(databse,table,column_name,identifier)
{
$dbc=myconnect($db);
$query="SELECT *FROM ".$table." WHERE ".$tcol."=".$tid." ORDER BY first_name ASC";
$result = mysqli_query($dbc, $query);
return $result;
}
?>
File test.php
<?php
require_once('testfunc.php');
$result= runquery('user','user_basic','user_type','1');
//runquery('database','table','col','id')/
while($row=mysqli_fetch_array($result))
{
echo '<strong>First Name:</strong>' . $row['first_name'] . '<br/>';
}
?>
If I am doing all wrong then suggest me a better way :-)
A quick glance shows that in your function runquery
SELECT *FROM
should be
SELECT * FROM
note the space after the *
EDIT :
I also notice you are using *mysqli_fetch_array* and this is not a valid mysqli method. You are right in using the mysqli extension over mysql but you should look more into statement fetch to solve this issue. The link I provided give a procedural example that should work for what you need.
function myconnect($db)
{
/*Removed redundant - single use variables*/
/*DB name was passed to the client_flags parameter of mysql_connect instead of mysql_select_db*/
$dbc = mysql_connect("localhost", "root","") or die (mysql_error());
/*Inserted Line*/
mysql_select_db($data);
return $dbc;
}
Currently you're not selecting a database - equivalent of USE DATABASE db_name.
Couple of syntax changes and function definition
function runquery($db,$table,$tcol,$tid)//(databse,table,column_name,identifier)
{
$dbc=myconnect($db);
/*Query and link identifier were in the wrong order*/
return mysql_query("SELECT * FROM ".$table." WHERE ".$tcol."=".$tid." ORDER BY first_name ASC", $doc);
}
Finally a couple of syntax changes, function calls
require_once('testfunc.php');
$result= runquery('user','user_basic','user_type','1');
/*fetch associateive array of result during iteration*/
while($row=mysql_fetch_assoc($result))
{
echo '<strong>First Name:</strong>' . $row['first_name'] . '<br/>';
}