Cannot add values to table using mysql and php - php

I have a problem with my code. I'm trying to add new post to the table events. I'm confused because I have used this code in other place on the same website (but it was using mysqli_query to register new user). mysqql_error returns "No database selected"
This is the code:
<?php
$add_title = $_POST['add_title'];
$add_happen = $_POST['add_happen'];
$add_created = date('Y-m-d');
$add_content = $_POST['add_content'];
$add_author = $_POST['add_author'];
//connect to
//localhost
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_dbname = "zhp2";
$db_con = mysql_connect($db_host, $db_username, $db_password, $db_dbname);
$query = "
INSERT INTO events ( title, happen, created, content, author )
VALUES ( '$add_title', '$add_happen', '$add_created', '$add_content', '$add_author') )
";
$retval = mysql_query($query, $db_con);
if(! $retval ){
die('Could not enter data: ' . mysql_error());
}
else{
echo "Entered data successfully\n";
}
mysql_close($db_con);
//header('Location: ../../index.php?link=events');?>
I've tried to fix it using trial and error method playing with different combinations both mysql_query and mysqli_query

You are confusing mysql_connect and mysqli_connect functions in the way you pass those parameters. In your example:
$db_con = mysql_connect($db_host, $db_username, $db_password, $db_dbname);
you are passing a fourth parameter which is the database name but that wont work as you should only pass the three first (host,username,password) and then call mysql_select_db():
$db_con = mysql_connect($db_host, $db_username, $db_password);
mysql_select_db( $db_dbname, $db_con );
In mysqli which is the BETTER way of doing it since mysql_ functions are very vulnerable and being deprecated from php you could pass four elements like here:
$db_con = mysqli_connect($db_host,$db_username, $db_password, $db_dbname) or die("Error " . mysqli_error($link));
which is close to what you are trying to do, but in a correct mysqli_ way.

Well then, you need to select the database! ;) The fourth parameter of mysql_connect() is not the database name. You need to do this separate of connecting to the MySQL server.
Using mysql_select_db() function:
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_dbname = "zhp2";
$db_con = mysql_connect($db_host, $db_username, $db_password );
mysql_select_db( $db_dbname, $db_con );
And of course all the obligatory warnings about SQL injection, sanitizing your data, deprecation of mysql_* functions.

You need to select which database to connect to using the mysql_select_db function:
// make $db_dbname the current db
$db_selected = mysql_select_db($db_dbname, $db_con);
if (!$db_selected) {
die ("Can't use $db_dbname : " . mysql_error());
}
See the PHP manual for more info: http://php.net/manual/en/function.mysql-select-db.php

Related

MySQL error message, mysql_connect(), any way to fix it?

So this is the error message:
PHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
This is the affected piece of code:
class wdClient {
var $dbLink; // The database link
var $prefix; // Table prefix
var $script; // The script running
/**
* Construct a new directory object.
*/
function wdClient() {
error_reporting(E_ALL ^ E_NOTICE);
$this->prefix = WDDBPREFIX;
// Connect to the database
$this->dbLink = mysql_connect(WDDBHOST, WDDBUSER, WDDBPASSWD);
// Select the database
mysql_select_db(WDDBNAME, $this->dbLink) or die('Sorry, The site is currently unavailable!');
}
where WDDBPREFIX, WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME are already defined in a config file.
I have tried simply using mysqli_connect instead of mysql_connect but it's not working.
Note: Never use MySQL, use this method!
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
Good luck!
well, as pointed in here http://php.net/manual/en/function.mysqli-connect.php , you should make something like this:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
Apparently, in your case it will look like this:
$link = mysqli_connect(WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME);
And then you can continue with your code...
if (!link){
die('Sorry, The site is currently unavailable!');
} else{
// write your SQL here and fetch it
}

Trying to connect sql database in xampp

<?php
$host = 'localhost';
$user = 'root'
$password = '';
$db ='members';
$connection = mysqli_connect("localhost", "user", "password") or die("Unable to connect to the server!");
mysqli_select_db("members", $connection) or die("Couldn't connect to the database!");
I have installed xampp and create database named "members". I tried to connect it to phpmyadmin but didn't work. I try to google all the answers since three days but in vain. Please help me...
<?php
$host = 'localhost';
$user = 'root';
$password = '';
$db ='members';
$connection = mysqli_connect($host,$user,$password,$db);// you can select db separately as you did already
if($connection){
// do all your stuff that you want
}else{
echo "db connection error because of".mysqli_connect_error();
}
Are your credentials for username and password correct?
By default, the localhost has username = root and password as blank.
Also, what's the issue? Is it showing "Unable to connect to the server!"?
You are missing a semicolon after $user = 'root' and you are using a mixture of mysql_ and mysqli_. Also, you could select a table by passing a fourth argument to mysqli_connect()
$host = 'localhost';
$user = 'root';
$password = '';
$db ='members';
$connection = mysqli_connect($host,$user,$password,$db);// you can select db separately as you did already
if($connection){ echo "Connected Successfully";}else{ echo "Error connecting: . mysqli_connect_error()"; }
Use mysqli_ to do queries:
mysqli_query($connection, "INSERT INTO user_login (uname,upassword,email) VALUES ('$uname','$upassword','$email')");
I recommend you to use prepared statements to avoid SQL injection.
So the above query would look like:
$stmt->prepare("INSERT INTO user_login (uname,upassword,email) VALUES (?,?,?)");
$stmt->bind_param('sss', $uname, $upassword, $email);
$stmt->execute();

Error! Call to undefined function pg_insert()

I am trying to copy an array into a table in the test database. I get this fatal error: Call to undefined function pg_insert() in C:\wamp\www\Lessons\GMS-DB.php on line 31. Can u please help me!
Here is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$database = "test";
// Create server connection
$con = mysql_connect ($servername, $username, $password, $database) or die('cant connect server');
mysql_select_db('test',$con);
// Create database connection
$db_selected = mysql_select_db('test',$con);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
//-----------------------------------------------------------------------
// Specify directory
$dir = 'C:/Users/Desktop/data';
$files1 = scandir($dir);
$data = array_diff($files1, array('.', '..')); //remove the dots or periods
// print_r($data);
// put in a string
$matstring = implode("','",$data);
$matstring="".$matstring."";
$table_name = `test table 1`;
$res = pg_insert ($con , $table_name , $data);
if ($res) {
echo "POST data is successfully logged\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>
You have two different kinds of databases there. One is MySQL and another is PostgreSQL. Your using a mysql database so use a mysql query to insert.
You need to use mysql query
mysql_query("INSERT INTO $table (column_name, column_name2) VALUES('$value', '$value2')");
Also, you are using mysqli syntax to connect to db. In mysql, the syntax is
$con = mysql_connect ($servername, $username, $password);
mysql_select_db('foo', $con);
And I strongly suggest you to use mysqli. Ancient mysql is no longer supported!
Here's the code in MySQLi
$db = new mysqli("host", "user", "password", "database");
$db->query("INSERT INTO $table (column_name, column_name2) VALUES('$value', '$value2')");
When should I use MySQLi instead of MySQL?
MySQLi Query

mysqli version of mysql pattern

Here's a MySQL pattern in PHP:
$username="username";
$password="password";
$database="username-databaseName";
// Opens a connection to a mySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$query = some query
$result = mysql_query($query);
I tried to replace most of it with a mysqli pattern and then stick the query part at the bottom like so:
//Database Information
$db_host = "localhost"; //Host address (most likely localhost)
$db_name = "username-databaseName"; //Name of Database
$db_user = "username"; //Name of database user
$db_pass = "password"; //Password for database user
/* Create a new mysqli object with database connection parameters */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
GLOBAL $mysqli;
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
// Search the rows in the markers table
$query = some query
$result = mysql_query($query);
However, I get this error message:
Invalid query: No database selected
What am I doing wrong?
First of all, you're calling mysql_query and not mysqli_query, like you intended to.
Second, since you're using the object oriented form, you need to call mysqli_query as a method:
$result = $mysqli->query($query);

Changing a global MySQL db file to MySQLi db file from PHP 4 to PHP 5.4

I have always used the following for MySQL database connection for procedural coding not OO running on PHP 4 and now I am moving some old websites to PHP 5.4:
<?php
global $db_user;
global $db_pass;
global $db_host;
global $db_name;
$db_user = 'USERNAME';
$db_pass = 'PASSWORD';
$db_host = 'HOST';
$db_name = 'DBNAME';
function do_query ( $sql )
{
global $db_user;
global $db_pass;
global $db_host;
global $db_name;
mysql_pconnect( $db_host, $db_user, $db_pass )or die("Cant connect to $db_host: ");
mysql_select_db( $db_name )or die("Cant select $db_name: ");
$res = mysql_query( $sql )or die("You messed up in your sql Using <b>$sql</b>\n\r" . mysql_error());
return $res;
}
?>
How can I change this to work with PHP 5.4 as all that is required for my website is to change this file as everything else now is up to date and the current way I connect with MySQLi never output errors the same way?
Thanks in advance.
UPDATE:
I tried the following:
<?php
$db_user = 'USERNAME';
$db_pass = 'PASSWORD';
$db_host = 'HOST';
$db_name = 'DBNAME';
function do_query ( $sql )
{
mysqli_connect( $db_host, $db_user, $db_pass )or die("Cant connect to $db_host: ");
mysqli_select_db( $db_name )or die("Cant select $db_name: ");
$res = mysqli_query( $sql )or die("You messed up in your sql Using <b>$sql</b>\n\r" . mysqli_error());
return $res;
}
?>
And use a mysqli_close(); at the end but it still doesn't work.
I also tried using it procedurally with:
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
But I can't seem to make that work as a function.
I have done loads of tests with different versions but I didn't want to over fill the page with information most people already know so I just put up the original code I have used in the past as I have so many other variations I have tried. I was not just trying to pass the buck, just trying to explain what exactly I was trying to convert to MySQLi. Sorry if people think this is pointless but I am stuck. Thanks.
Three flaws in one post.
First, using a function to create a connection and then query is a bad idea.
Second, you're using a persistent connection. So even when the page is done the connection remains. You'll exhaust your pool of database connections like that.
Third, you're using mysql_ functions, which are deprecated.
So here's the preferred way to do things now, using mysqli and an object approach. I don't recommend $GLOBALS normally but it sounds like you're working with legacy code
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
function do_query($sql) {
$mysqli = $GLOBALS['mysqli'];
$res = $mysqli->query($sql)or die("You messed up in your sql Using <b>$sql</b>\n\r" . mysqli->error);
return $res;
}

Categories