No database selected PHP [duplicate] - php

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 1 year ago.
I've been trying to spot the error in my database connection , I read several answers suggesting to make sure of the password grant full access ... I checked everything the problem is still appearing ...
My question is ... I understand mysqli is in this case better (from what I read) so ...
if I replace mt $dbcon with
$dbcon = mysqli_connect("$host","$username","$password","$db_name") ;
will that fix the problem and if it does, how do I get rid of the never ending
mysqli_error expects exactly 1 parameter, 0 given ... error
My php is
<?php
$host="****" ;
$username="****" ;
$password="****" ;
$db_name="****" ;
$tbl_name="courses" ;
$dbcon = mysql_connect("$host","$username","$password","$db_name") ;
if (!$dbcon) {
die('error connecting to database'); }
echo 'Courses successfully registerd , ' ;
// escape variables for security
$studentid = ( $_GET['studentid']);
$fname = $_POST["name"]; //echo $studentid;
$query=mysql_query("select * from courses where studentid='".$studentid."' ") or die(mysql_error());
$duplicate=mysql_num_rows($query);
if($duplicate==0)
{
$query1=mysql_query("insert into user values('".$studentid."')") or die(mysql_error());
}
else
{
echo'The ID you entered '.$studentid.' already registered, please wait 24 hours until you can register again';
}
// Get Cources
$name = $_GET['ckb'];
if(isset($_GET['ckb']))
{
foreach ($name as $courcess){
$cc=$cc. $courcess.',';
}
}
$sql="INSERT INTO courses (studentid, ckb, name)
VALUES ('$studentid', '$cc', $fname)";
if (!mysql_query($dbcon,$sql)) {
die('Error: ' . mysqli_error($dbcon));
}
echo " Thank you for using IME Virtual Registeration ";
mysql_close($dbcon);
?>

The problem is in Your PHP on line 7. mysql_connect() has those parameters:
mysql_connect(string $server, string $username, string $password, #optional bool $new_link = false, #optional int $client_flags = 0)
You are giving the fourth parameter $db_name =MISTAKE (fourth parameter must be boolean as you can see.) There's a function mysql_select_db() to tell PHP which database are you using. So here's a rework of your 7th line:
$dbcon = mysql_connect("$host","$username","$password");
mysql_select_db("$db_name");
but I recommend you to use mysqli or PDO ->they are inbuilt PHP libraries, so you don't have to download anything and what's more important they are easy to use.
Good Luck :)

Although we are mostly using a PDO interface now, here is the code also use to connect to the database with some simple command line scripts:
$sql_link=mysql_connect ('host','user','password') or die('Cannot connect to the database because: ' . mysql_error());
if (!$sql_link) {
echo('Could not connect to database : ' . mysql_error());
exit;
}
mysql_select_db('database_name') or die(mysql_error());
Hope that helps!

Related

Tutorial issues using INSERT INTO without adding a row to database for certain entries

I am following the last part of the following video tutorial "How to create a database website with PHP and mySQL 07 - Add in input form" :
https://www.youtube.com/watch?v=MGIG00d1Xzc&list=PLhPyEFL5u-i0zEaDF0IPLYvm8zOKnz70r&index=7
At the end here is my code, for the inserting portion to the database for the new_jokes.php script (everything up to this point of the series I have gotten to work fine so far)
Basically I am getting the seemingly classic "INSERT INTO" not working although all my syntax looks correct. Am I missing something obvious here? I get no errors, just the row isn't added.
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question
$new_joke_answer </h2>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES
(NULL, '$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
include "search_all_jokes.php";
?>
Return to the main page
Here is the db_connect.php code as requested:
<?php
// four variables to connect the database
$host = "localhost";
$username = "root";
$user_pass = "usbw";
$database = "test";
// create a database connection instance
$mysqli = new mysqli($host, $username, $user_pass, $database);
?>
Here is search_all_jokes.php (which has minor error checking):
// if there are any values in the table, select them one at a time
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "SELECT JokeID, Joke_question, Joke_answer FROM Jokes_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "JokeID: " . $row["JokeID"]. " - Joke_question: " .
$row["Joke_question"]. " " . $row["Joke_answer"]. "<br>";
}
} else {
echo "0 results";
}
?>
Also here is the table structure screenshot viewed in myPHPAdmin:
I added error capturing into new_jokes.php inspired by this Stack Overflow post:
INSERT INTO SYNTAX ERROR
And get the following error:
Error: 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 't jump.' )' at line 1localhost via TCP/IP
Thank you everyone for helping out with this! Syntax can really throw a wrench in everything. I also will read up on prepared statements since that also could have prevented the issue. The ultimate help to this I found the solution to by adding the function referenced here for MySQLi real_escape_string to clean the single quote I had within the answer I was submitting to my joke table:
(Can a kangaroo jump higher than the empire state building? Of course, the empire state building can't jump.)
As shown in the documentation #miken32 linked as a comment here it is says: "But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)"
But now the code for this part 7 of the tutorial on you tube I found works and adds it into a row on the database table, then displaying the full new table on the next webpage. I spent a good while shooting in the dark on while the answer ended up being fairly simple. Again special thanks to #miken32 for pointing me the right direction.
Here is my completed code that ended up working to at least achieve the goal of the tutorial:
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
$new_joke_question = $mysqli->real_escape_string($new_joke_question);
$new_joke_answer = $mysqli->real_escape_string($new_joke_answer);
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question $new_joke_answer
</h2>";
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES (' ',
'$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
if ($mysqli->query($sql) === TRUE) {
echo 'users entry saved successfully';
}
else {
echo 'Error: '. $mysqli->error .'<br>';
}
include "search_all_jokes.php";
?>
Return to the main page

PHP 7.1 query for User check gives out a Warning: A non-numeric value encountered in E:\XAMPP\htdocs

I'm facing a weird problem, I'm trying to implement a simple Usercheck with PHP 7.1.
$con = getConnection();
//check connection
if(!$con){
die("Connection to database failed". mysql_connect_error() );
} else echo ("connection to database successfull");
//checking if nickname already exists
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" + $nickname+ "'";
//sending query to sql database
$doesExist = mysqli_query($con, $checkUserExistanceSql)
or die ("Fehler in der Datenbankabfrage");
if(mysqli_num_rows($doesExist)>=1){
echo "Nickname not available, use another name";
}
But I'm getting this warning
Warning: A non-numeric value encountered in E:\XAMPP\htdocs... Line 29
Line 29 is the $checkUserExistanceSql. Any ideas where the problem is?
String concatenation on PHP uses . (dot) as operator, not + (plus).
You actual code uses +:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" + $nickname+ "'";
This is why PHP is telling that $nickname isn't a numeric variable. It cannot sum strings, only concatenate.
Change your operator to . and it will work:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" . $nickname . "'";
You can also use this syntax, with the same result but cleaner code:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='{$nickname}'";
Security Alert
You code is sucessive to SQL injection. You should use prepared statements instead of concatenating your variables into the Query.
Thanks to the help of Yolo and Elias Soares.
The script runs flawless now, I also used prepared statement to counter the risk of sql injection as mentiones by elias.
$con = getConnection();
//check connection
if(!$con){
die("Connection to database failed". mysql_connect_error() );
} else echo ("connection to database successfull");
//prepared statement for sql query
$stmt = $con -> prepare("SELECT nickname FROM user WHERE (nickname=?)");
$stmt -> bind_param("s", $nickname);
$stmt->execute();
//checkking result, if nickname is already used
if($stmt->get_result()){
echo "0";
} else {
//insert user
}

No Database Selected Php

This is a somewhat simple task, I am trying to compare a username to that in the database. I am testing it out in a single php file before I do it properly. My code is below. Basically I have a user, which is in the database and I am checking if it is in there.
<?php
$db_connect = mysql_connect("127.0.0.1", "root", "anwesha01", "mis");
//Check if connection worked.
if(!$db_connect)
{
die("Unable to connect to database: " . mysql_error());
}
//For testing purposes only.
else
{
echo "Database connect success!";
}
$user = "alj001";
$query = "SELECT Username FROM `user` WHERE `Username` = '".$user."'";
//What is being passed through the database.
echo "<p><b>This is what is being queried:</b> " . $query;
//Result
if (mysql_query($query, $db_connect))
{
echo "<br> Query worked!";
}
else
{
echo "<p><b>MySQL error: </b><br>". mysql_error();
}
?>
The result I get is:
Database connect success!
This is what is being queried: SELECT Username FROM user WHERE Username = 'alj001'
MySQL error: No database selected
First I had my mysql_query without the $db_connect as it is above, but I put it in and I still get "no database selected".
Ive looked at the w3c schools for the mysql_query function, I believe I have done everything correctly. http://www.w3schools.com/php/func_mysql_query.asp
Because you haven't called mysql_select_db. Note that the 4th parameter to mysql_connect is not what you think it is.
That said, you really should be using PDO or mysqli, not the plain mysql_ functions, since they're deprecated.

Outputting contents of database mysqli

Hi I know this is a little general but its something I cant seem to work out by reading online.
Im trying to connnect to a database using php / mysqli using a wamp server and a database which is local host on php admin.
No matter what I try i keep getting the error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given when i try to output the contents of the database.
the code im using is:
if (isset($_POST["submit"]))
{
$con = mysqli_connect("localhost");
if ($con == true)
{
echo "Database connection established";
}
else
{
die("Unable to connect to database");
}
$result = mysqli_query($con,"SELECT *");
while($row = mysqli_fetch_array($result))
{
echo $row['login'];
}
}
I will be good if you have a look at the standard mysqli_connect here
I will dont seem to see where you have selected any data base before attempting to dump it contents.
<?php
//set up basic connection :
$con = mysqli_connect("host","user","passw","db") or die("Error " . mysqli_error($con));
?>
Following this basic standard will also help you know where prob is.
you have to select from table . or mysqli dont know what table are you selecting from.
change this
$result = mysqli_query($con,"SELECT *");
to
$result = mysqli_query($con,"SELECT * FROM table_name ");
table_name is the name of your table
and your connection is tottally wrong.
use this
$con = mysqli_connect("hostname","username","password","database_name");
you have to learn here how to connect and use mysqli

Need HELP in converting MySQL to MySQLI in my PHP script? [duplicate]

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 1 year ago.
I need some help in converting my script from using mysql to mysqli I have been trying for ever to do this and keep getting errors I have read articles on how to do this and still can get it to work.
Here is the original working script below.
<?php
require_once ('./mysqli_connect.php'); // Connect to the db.
if (isset($_POST['submitted'])) {
if ($dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD)) { // Make the connnection.
if (!mysql_select_db (DB_NAME)) { // If it can't select the database.
// Handle the error.
trigger_error("Could not select the database!\n<br />MySQL Error: " . mysql_error());
exit();
} // End of mysql_select_db IF.
} else { // If it couldn't connect to MySQL.
// Print a message to the user, include the footer, and kill the script.
trigger_error("Could not connect to MySQL!\n<br />MySQL Error: " . mysql_error());
exit();
} // End of $dbc IF.
// grab the tag
$tag = mysql_real_escape_string($_POST['tag']);
// see if the tag already exists and potentially what the current count is
$query = "SELECT id, count, page FROM tags WHERE tag='$tag'";
$result = mysql_query($query);
//--if there is a row, that means the tag exists
if(mysql_num_rows($result))
{
//--pull out the tag ID and the current count and increment by one.
$tag_info = mysql_fetch_array($result);
$tag_info_id = $tag_info["id"];
$tag_info_count = $tag_info["count"] + 1;
//--update the table with the new count
$sql_update_cnt = "UPDATE tags SET count='$tag_info_count'
WHERE id='$tag_info_id'";
mysql_query($sql_update_cnt);
echo "$tag now with $tag_info_count instances";
}
else
{
// tag is not there, so insert a new instance
$query = "INSERT INTO tags (tag, count) VALUES ('$tag', 1)";
if (!mysql_query($query, $dbc))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
mysql_close($dbc);
}
?>
Here is the errors I keep getting.
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given on line 13
Warning: mysqli_error() expects exactly 1 parameter, 0 given on line 16
If you're going to go through the hassle, I would really recommend you consider PDO instead.
It's all a matter of changing mysql to mysqli.
For example, you could call mysqli_query just like you do mysql_query here.
When you call these functions, you need to pass in the database reference as the first parameter.
See the mysqli function reference here
It's been a while since I've done a mysql->mysqli conversion (like 2 or 3 years), but IIRC there are some functions for which you also have to reverse the parameter order. Isn't that lovely?

Categories