I'm attempting to create a dropdown list that is populated using PHP by gathering all of my clients in my database. This is working, but the problem is the code I am using requires the my_sql_connect and my_sql_select_db login details to populate the list.
On the pages this feature is required, the following snippet of code is provided at the top of each page to connect to the database:
require_once ('includes/dbConfig.php');
The code that is working is below (the #'s substitute my login details):
mysql_connect('localhost', '#', '#');
mysql_select_db('#');
$sql = "SELECT client_organisation_name FROM clients";
$result = mysql_query($sql);
echo "<select name='clients'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['client_organisation_name'] ."'>" . $row['client_organisation_name'] ."</option>";
}
echo "</select>";
What I am having difficulty in achieving is the dropdown list to populate using the connection already established. I have used the following code to try and substitute this but to no success:
$conn = mysql_connect('$dbhost', '$dbuser', '$dbpass') or die ('Error connecting to mysql');
mysql_select_db('$dbname');
I have searched the internet but have not found a suitable solution. For obvious reasons, it is a security risk and hassle to have your database login details evident, therefore I would be grateful for some help to get my snippet of code to connect to my database.
You can use MySQLi:
define(DB_HOST, "yourhost"); // Host
define(DB_NAME, "yourdbname"); // Database
define(DB_USER, "youruser"); // Username
define(DB_PASS, "yourpass"); // Password
$mysqli=new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die("Error " . mysqli_error($link));
mysqli_set_charset($mysqli, 'utf8');
$results = $mysqli->query("SELECT client_organisation_name FROM clients");
while(($array_results[] = $results->fetch_assoc()) || array_pop($array_results));
echo '<select name="clients">'."\n";
foreach($array_results as $client) {
echo '<option value="'.$client['client_organisation_name'].'">'. $client['client_organisation_name'].'</option>'."\n";
}
echo '</select>'."\n";
Make sure that the connection data (user, password, name and host) are correct.
The single quote strings don't evaluate the variables inside.
So your code should be:
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
EDIT:
I saw #Jason McCreary's comment and I have to agree with him.
You should definitely use mysqli. The only changes in your code are following:
$db = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
Then you execute the mysql queries like this:
$db->query("INSERT MYSQL CODE HERE");
Related
Hi there Im very new to PHP and Im having issues trying to make drop-down list with php connecting to my mysql db. I am able to connect to the database no problem as no error message is showing up when I load up the php document online.
However from my research I just cant seem to find what Im looking for. I have made a table in mysql with the necessary ids and values. Below is my code within select tags if even thats a good way to do it? if anyone can help much appreciated.
<select>
<?php
$db = mysqli_connect ("host", "username", "password");
if (!$db)
{
echo "Sorry! Can't connect to database";
exit();
}
//table name on mysql db = users3
?>
</select>
It looks like you're trying to run PHP inside of an HTML select tag. PHP runs server side (in the background).
You'll need to create your dropdown menu using Javascript and HTML, then have have your javascript code call your PHP via AJAX. There are a number of ways doing this, but the basic idea is to have an event bound to each item in your dropdown list. When you click one of your list items, your javascript uses AJAX to call your PHP which queries the database.
That's a pretty high level description of it but hopefully it gives you a sense of where you need to go from here.
Regards,
--Drew
Your code is obviously missing any SQL select query.
The following code was adapted from W3Schools, I suggest you have a read over some examples using mysqli here Mysql select query example
Included is a select list that is also courtesy of W3Schools, HTML form elements
I implore you to read some examples at W3Schools.
HTML
<select name="items"><?php echo getSelectItems(); ?></select>
PHP
<?php
function getSelectItems() {
$servername = "host";
$username = "username";
$password = "password";
$dbname = "itemDB";
$output = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT itemName FROM items";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$output .= '<option value="' . $i . '">' . $row["itemName"] . '</option>';
$i++;
}
}
$conn->close();
return $output;
}
I'm trying to make a simple PHP script that fetches a table from my MySQL database and encodes the results in JSON, so I can use them later in Java.
This is my code:
<?php
$servername = "localhost:3036";
$username = "example_user";
$password = "example_password";
$conn = mysql_connect($servername, $username, $password);
if(! $conn) {
die("Could not connect: " . mysql_error());
}
$sql = "SELECT * FROM table_name";
mysql_select_db("database_name");
$retval = mysql_query($sql, $conn);
if(! $retval) {
die("Could not get data: " . mysql_error());
}
while($row = mysql_fetch_assoc($retval)) {
$output[]=$row;
}
print(json_encode($output));
mysql_close($conn);
?>
This just gives a blank page as output (error messages are set to display).
However, if I change json_encode($output) to json_encode($output[0]) (or any other number within the array's bounds), the output becomes that one $row array.
This is probably a really stupid question, but after about 3 hours of research I'm at my wit's end. Thank you for any help.
User #Joni led me to the solution.
Adding mysql_set_charset("utf8") fixed my issue.
As mentioned in this post: Why is this PHP call to json_encode silently failing - inability to handle single quotes?.
Try
echo json_encode($output) ;
It seems you have some utf8 character in your result set
add this statement before running your query
mysql_query('SET CHARACTER SET utf8');
Update
"mysql"
to
"mysqli"
and add
mysqli_set_charset($variável_de _conexão, 'utf8');
below the connection variable
Good morning,
I am quite new to php and I am trying to create a connection to a MSSQL server, I've been able to do it through MYSQL php connection but what I thought would be a simply change to MSSQL is proving to be much harder than expected.
The below code is basically what I am using after much googleing and search in this website this is what i've come up with:
<?php
$Server = "127.0.0.1";
$User = "BOB123";
$Pass = "BOBPASS";
$DB = "BOBDB";
//connection to the database
$dbconn = mssql_connect($Server, $User, $Pass)
or die("Couldn't connect to SQL Server on $Server");
//select a database to work with
$selected = mssql_select_db($DB, $dbconn)
or die("Couldn't open database $myDB");
//declare the SQL statement that will query the database
$query = "SELECT CustomerName from tblCustomer ";
//execute the SQL query and return records
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display the results
while($row = mssql_fetch_array($result))
{
echo "<br>" . $row["name"];
}
//close the connection
mssql_close($dbconn);
?>
As you can see the above script is very basic and there are very similar ones knocking around on the web could anyone help in connecting to the server this script doesn't seem to want to connect. I've changed the log on details as you'd probably know.
Thanks
Kris
You have a typo on:
$dbconn = mssql_connect($Server, $User, $Pass);
Should be:
$dbconn = mysql_connect($Server, $User, $Pass);
You're typing mysql wrong on each mysql_ function you create, change all mssql_ to mysql_
Note:
You shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and use PDO or MySQLi.
#Daniel Gelling Doesn't look like a typo, looks like he is trying to connect to Microsoft SQL Server using mssql. You are correct about the API being outdated however.
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'];
}
?>
Got a problem! Though I found almost similar threads but none helped :(
I've written a php script to fetch the number of registered users from my MySQL database. The script is working great in my localhost; it is using the given username,pass and host name which are "root", "root", and "localhost" respectively, but the script is not using the given username/pass/host rather using root#localhost (password: NO) in Live server.
In the Live server I created a MySQL user, set an different password, and hostname there is of course not localhost. I updated the script with my newly created mysql users data. BUT, whenever I run the script, I see that the script is still using "root", "root", and "localhost"!!
take a look at the script:
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ");
while ($row = mysql_fetch_array($query)):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
-- Some says to change the default username and pass in the config.ini.php file located in phpMyAdmin directory. Would this help?? I didn't try this because either my hosting provider didn't give me privilege to access that directory (because I am using free hosting for testing scripts) or I simply didn't find it :(
Please help....
Foreword: The MySQL extension is marked as deprecated, better use mysqli or PDO
Though you store the connection resource in $conn you're not using it in your call to mysql_query() and you're not checking the return value of mysql_connect(), i.e. if the connection fails for some reason mysql_query() "is free" to establish a new default connection.
<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
die(mysql_error()); // or a more sophisticated error handling....
}
$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
while ( false!=($row=mysql_fetch_array($query)) ):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
edit: It looks like you're processing only one row.
Either move the echo line into the while-loop or (if you really only want one record) better say so in the sql statement and get rid of the loop, e.g.
// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
echo 'no record found';
}
else {
echo htmlspecialchars($row['total_regd']);
}
First of all:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
What is your mysql_error()? :)