mySQL dropdown using PHP does not display options from database [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I looked at some other questions online and on here related to this, but none seem to really encounter my error exactly.
I wrote my PHP code and implemented it into my HTML, I get the dropdown box appearing, but it doesn't actually want to display any values. Is there any implementations or fixes I should include in my code? How do I get it to work?
My database is called: Treatments
My column in the database that I want displayed is called: Treatment
treatment_dropdown.php
<?php
$hostname = 'host_name';
$dbname = 'database_name';
$username = 'username';
$password = 'password';
$con=mysql_connect($hostname,$username,$password,$dbname) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db($dbname,$con) or die("Failed to connect to MySQL: " . mysql_error());
$query = "SELECT * FROM `Treatments`";
$result = mysql_query($con, $query);
$options = "";
while ($row = mysql_fetch_array($result)){
$options = $options . "<option>$row[1]</option>";
}
?>
HTML:
<body>
<select>
<?php
echo $options;
?>
</select>
</body>

Consider changing this line:
$query = "SELECT * FROM 'Treatments'";
to use backticks instead of single quotes like so:
$query = "SELECT * FROM `Treatments`";
In my test query I got an error because of this, let me know if that helps.

Add <?php include 'treatment_dropdown.php'; ?> to the top of your HTML file. This should give you access to the the $options string so it can be used in that file. Note that in order for this to work, treatment_dropdown.php needs to be in the same directory as your HTML file. If it is not, the include statement will need to be changed to reflect the appropriate file path.

Do not use mysql_*() functions, they are deprecated. Use mysqli or PDO instead.
No matter which library use use to access mysql, always check for errors within the sql code separately. Errors in the sql code do not result in errors in the php code.
In this particular case the problem is that you included the table in single quotes instead of backticks.
The correct code:
$query = "SELECT * FROM `Treatments`";

Here's what your PHP file should look like:
<?php
$hostname = 'localhost';
$dbname = 'Treatments';
$username = 'root';
$password = '';
$con = mysql_connect( $hostname, $username, $password, $dbname) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db($dbname,$con) or die("Failed to connect to MySQL: " . mysql_error());
/* No single quotes needed for the table name. */
$query = "SELECT * FROM Treatments";
/* First parameter should be $query not $con */
$result = mysql_query($query, $con);
$options = "";
/* Check if no results exist. */
if ( !$result ) {
die( "NO results found." );
}
while ( $row = mysql_fetch_array($result) ) {
$options .= "<option>$row[treatment]</option>";
}
?>
Notes:
dont use mysql_* functions, they're not secure, use PDO instead.
your table name does not need to be wrapped in single quotes.
mysql_query expects parameter 1 to be the query not the DB connection.
you should probably check if no results are found.

Related

PHP (If not existant in records.) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So basically I got this code right here:
<?php
include_once 'dbconfig2.php';
$con = new DB_con();
$table = "users";
if(isset($_GET['profile_id']))
{
$sql=mysql_query("SELECT * FROM users WHERE user_id=".$_GET['profile_id']);
$result=mysql_fetch_array($sql);
}
?>
I am clueless as to how I would make it so if the user_id is not existent in the records, they cannot view their profile but it leads them to another messsage or piece of code.
If the user_id doesn't exist, there won't be any rows in the result. When you try to read a row with mysql_fetch_array(), it returns FALSE. So you can simply test $result:
if (!$result) {
die("Invalid profile ID");
}
Try to use prepared statements using mysqli, in order to avoid sql injection.
By way of example:
$mysqli = new mysqli("localhost", "root", "root", "test");
if ($mysqli->connect_errno) {
echo "connect_error". $mysqli->connect_error;
}
$id = $_GET['profile_id'];
$result = $mysqli->prepare('SELECT name FROM users WHERE user_id = ?');
$result->bind_param("i", $id);
$result->execute();
$result->bind_result($col1);
$result->fetch();
$is_valid_profile = (!$col1) ? 'Invalid profile' : 'Valid profile';
echo $is_valid_profile;
$result->close();
http://php.net/manual/en/mysqli.prepare.php

Creating a mysql database with "." in the name (using php) [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I've been having some trouble recently with trying to automate new database creations with a php script.
Basically, the script takes the new login username and creates a database (and then insert some tables and data later on, which is also done via a php script).
I used to have to manually create the database, but now need to make it automated.
The issue is that I used to be able to just create a new database using the phpadmin "new database" function from the web GUI and put in names like "test1.siteA", "userb.siteB".
However, now that I've tried to do the same via php script, it keeps giving me the "You have an error in your syntax..." from my last "echo".
Main parameters are:
$name = $user->username;
$servernm = 'localhost';
$usnm = 'user';
$pasd = 'user';
$dbname = $name;
$dbname .= '.site';
I've found that the error would disappear once I remove the .site part from the code (it still exist even if I combine the $dbname into 1 line).
According to some articles that I've found online, it seems that MySQL doesn't allow special characters like "." to be included in the database name.
It just seems very weird to me that the ".site" can be added manually through phpMyadmin while the php/mysqli script doesn't allow this.
The full script is as follows (I'm sure it can be heavily improved, so any suggestions regarding that are also welcome):
<?php
define("_VALID_PHP", true);
require_once(APPPATH. "/libraries/init.php");
include (BASEPATH . "/database/DB_temp.php");
$row = $user->getUserData();
$name = $user->username;
$servernm = 'localhost';
$usnm = 'user';
$pasd = 'user';
$dbname = $name;
$dbname .= '.site';
// Create connection
$conn = mysqli_connect($servernm, $usnm, $pasd);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check if DB exist
$sql = "SELECT count(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'";
$check = mysqli_query($conn,$sql)
or die("Connection failed: " . mysqli_connect_error());
while($row = mysqli_fetch_array($check,MYSQLI_NUM))
{
$dbval = $row[0];
}
if ($dbval == "0")
{
$createsql = "CREATE DATABASE '$dbname' ";
}
if ($dbval == "1")
{
$createsql = "SELECT count(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'";
}
if (mysqli_query($conn, $createsql)) {
Echo "Completed. DBVAL= " .$dbval ;
}
else
{
echo "Error creating database: " . mysqli_error($conn);
}
?>
PHP version: 5.6.18
phpmyadmin: 4.5.4.1
Ubuntu 14.04
Apologies if I've made some posting errors on here. Do let me know about them and I'll try to correct it as much as I can. Any help is greatly appreciated!
. is a meta character in SQL, use to separate db/table/field names:
SELECT foo.bar.baz FROM sometable
^---------- database 'foo'
^------- table 'bar'
^--- field 'baz'
You should NOT be using metacharacters in any identifiers. It just leads to pain later on, and having to do stuff like:
SELECT `foo.bar`.baz.qux FROM ...
^^^^^^^^^--------- database 'foo.bar'
^------ table 'baz'
^-- field 'qux'
So you can use backticks if you absolutely have to, but you shouldn't be doing this in the first place.
try wrapping the database name with back ticks.
$dbname .= '`.site`';

Simple Register Form in php [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm Trying To Write a login/register system, i got the login down but i need help with registration
Could not enter data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
My Written code
<?php
$dbhost = '';
$dbuser = '';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO members '.
'(id,username,password) '.
'VALUES ( 2, test, test';
mysql_select_db('');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Registered\n";
mysql_close($conn);
?>
Also i need a checker to see if the username is taken and assign a id, going up from whats in my DB, my db is a table called members, inside the table is ID(Ascending number(currently at 1)) Username, password.
I don't need the password encrypted, I have something in place for that elsewhere.
Try This :
// first check if username exist or not
$rows = "SELECT * FROM members WHERE username='" . $_POST['username'] . "'";
$chk = mysql_query($rows);
if (mysql_num_rows($chk) >= 1) {
$userexist = "* This User already exist";
die();
// Then if not exist add it to DB
} else {
$sql = "INSERT INTO members (id,username,password) VALUES ( 2, '" . $_POST['username'] . "', '" . $_POST['password'] . "')";
$result = mysql_query($sql,$conn);
}
You have two errors in your query:
You're missing quotes around your string values
You're missing the closing parenthesis around your values to be inserted
Try this:
$sql = "INSERT INTO members (id,username,password) VALUES ( 2, 'test', 'test')";
FYI, this is much easier to read on one line. I would avoid concatenation in your query if you can help it.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

No result from query in PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have made code without error for connection and data fetching but i don't know why result for query is bool(false)
<?php
$con=mysql_connect("localhost","root","","xyz");
echo "Connection made";
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
The code to query and execution is
<?php
include ("includes/connection.php");
$query="SELECT * FROM userdata ";
$result=mysql_query($query);
var_dump($result);
?>
Help needed here
You should use either mysql or mysqli. This is the main problem for the error
<?php
$con=mysqli_connect("localhost","root","","xyz") or die ("error in connection".mysqli_error($con);
?>
and use $result= mysqli_query($con, $sql) where $sql contains your query
As i stated in the comments, your echo up there to tell you you connected to the mysql server is not effective. I pulled out an old function from me to show you how to do it and make it clear where the error is.
$con = mysql_connect('localhost','root','');
$db = mysql_select_db('xyz',$con);
function OpenConnection(){
global $con;
global $db;
if (!$con){
die('cannot connect to server!');
}else{
if(!$db){
die('cannot connect to database!');
}
}
}
If you dont get anything back, you ll be good to go.
Don't use mysql_* functions they are depracted use mysqli or pdo instead.
You need to fetch results of your query with fetch functions like mysql_fetch_array() or mysql_fetch_row() to get results of your query. There are plenty of examples in PHP manual.
In your cause it would be something like this:
<?php
$con=mysql_connect("localhost","root","") or die("didn't connect to db");
mysql_select_db('name_of_your_db', $con);
$query="SELECT * FROM `userdata` ";
$result=mysql_query($query); //this returns resource ID that needs to be fetched
while($row = mysql_fetch_row($result))
print_r($row);
If $result is false it means that query failed it can be caused by several issues for example there is no DB selected, there is no connection etc.
I'd also give you better solution with PDO
<?php
$dsn = 'mysql:dbname=nameofyourdb;host=127.0.0.1';
$user = 'root';
$password = 'yourpass';
try
{
$db = new PDO($dsn, $user, $password);
foreach ($db->query("SELECT * FROM `userdata`") as $row)
print_r($row);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>

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.

Categories