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
Related
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
}
<?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();
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
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);
I recently learned that mysql_* has been depreciated and i have a quick question on how to rewrite something.
$db = mysql_connect("localhost","root","PASSWORD");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("FormData" ,$db);
I have tried rewriting it like this...
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData", $db);
if(!$db) die("Error connecting to MySQL database.");
But when it posts my form i get the "Error connecting to MySQL database." error. I was able to fix it by just using this but i wanted to know how to add in the Error connecting.
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData");
Any help would be great as i try to learn all of the new MySQLi stuff!
PHP website
Straight from php.net
<?php
$mysqli = new mysqli('localhost', 'fake_user', 'my_password', 'my_db');
// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
?>
Edit:
The below will also allow you to do it your way.
$mysqli = mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
Then you can:
if (!$mysqli) {
//handle the error
}
Consider PDO if possible. They are kind similar to me.
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData", $db);
if(!$db) die("Error connecting to MySQL database.");
should be
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData");
if($mysqli->connect_error) die("Error connecting to MySQL database.");
the parameters for mysqli() are:
[ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]]
Not sure why you were trying to use the $db variable to set the port for the connection and then checking if the port variable is true...
For future reference the best place to look first, would be the docs
EDIT
As #Touch pointed out, you must check if error exists and not just that object exists. Edited code to reflect this.
Using mysqli:
define('DB_HOST', 'localhost');
define('DB_NAME', 'some_database_name');
define('DB_USER', 'some_user');
define('DB_PASS', 'some_password');
$Connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$Connection->connect_errno)
{
//do your prepared stuffs
}
else
{
die("Database Connection error:".$Connection->connect_error);
}
or using PDO
try
{
$PDOConnection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
$PDOConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//do your prepared stuffs
$PDOConnection = null;
}
catch(PDOException $e)
{
die('ERROR: ' . $e->getMessage());
}
I wrote a class called better_mysqli that extends mysqli making it easier to use.
The following example shows the answer to your question and also shows basic usage of the better_mysqli class. You can view a detailed example with lots of comments here: detailed usage of better_mysqli
<?php
include_once('better_mysqli.php'); // can be obtained from: http://pastebin.com/ATyzLUfK
// THIS NEXT PART ANSWERS YOUR QUESTION
// THIS NEXT PART ANSWERS YOUR QUESTION
// THIS NEXT PART ANSWERS YOUR QUESTION
// THE ONLY DIFFERENCE IN THE CONNECTION WHEN USING better_mysqli AND mysqli
// is $mysqli = new better_mysqli(...) and $mysqli = new mysqli(...)
// == Instantiate the mysqli database object (aka open the database) ==
$mysqli = new better_mysqli('your_server', 'your_user', 'your_pass', 'your_db_name');
if (mysqli_connect_errno()) {
error_log(sprintf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()));
exit;
}
// == select example ==
unless( $sth = $mysqli->select('select * from table1 where col1=? and col2=?', $row, array('col1_placeholder_value', 'col2_placeholder_value'), $debug_level=0, $verbose_debug_output)){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
while($sth->fetch()){
echo $row['col1'] .', '. $row['col2'] .', and '. $row['col_etc'] .' are accessed like that.<br>';
}
// == insert example ==
$statement = "insert into table1 (col1, col2, date_col, col_etc) values (?, ?, NOW(), ?)";
unless( $mysqli->insert($statement, array('col1_insert_value', 'col2_insert_value', 'col_etc_value'), $debug_level=0, $verbose_debug_output, $id_of_new_record) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// == update example ==
unless($mysqli->update("update table1 set col1=? where col2=?", array('col1_value', 'col2_value'), $debug_level=0, $verbose_debug_output) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// == delete example ==
unless( $mysqli->delete("delete from table1 where col1=? where col2=?", array('col1_value', 'col2_value'), $debug_level=0, $verbose_debug_output) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// in all cases statements are prepared just once and cached so if you reuse any statement the already prepared statement handle is automatically used
?>