php mysql script not working - php

I got my script working for one column of data but I am trying to send it other data to a second column in mysql table. Here's my php code:
<?php
function db_connect()
{
$hostname = '127.0.0.1';
$db_user = 'root';
$db_password = '';
$db_name = 'hit';
mysql_connect ($hostname, $db_user, $db_password) or die (mysql_error());
echo "Success.. Connected to MySQL...<br />";
mysql_select_db($db_name) or die(mysql_error());
echo "Success.. Connected to Database...<br /> ";
}
function insertData($DATA)
{
function insterData($DATA2)
{
db_connect();
$requete = "INSERT INTO data SET col_Data='".$DATA."'";
if(!mysql_query($requete))
echo mysql_error();
else
echo 'data accepted.';
$requete2 = "INSERT INTO data SET col_Data2='".$DATA2."'";
if(!mysql_query($requete2))
echo mysql_error();
else
echo 'data accepted.';
}
if(isset($_GET['DATA']))
if(isset($_GET['DATA2']))
}
insertData($_GET['DATA']);
insertData($_GET['DATA2']);
}
else
{
echo 'Nop';
}
?>
This is how I send the post data
http://localhost/hit.php?DATA=iamwicked&DATA2=iamcool
This then suppose to send DATA=iamwicked goes into database hit table data column col_data
This then suppose to send DATA2=iamcool goes into database hit table data column col_data2
But I get this error,
but there are errors can someone help me debug.
Here is a working script:
<?php
function db_connect()
{
$hostname = '127.0.0.1';
$db_user = 'root';
$db_password = '';
$db_name = 'hit';
mysql_connect ($hostname, $db_user, $db_password) or die (mysql_error());
echo "Success.. Connected to MySQL...<br />";
mysql_select_db($db_name) or die(mysql_error());
echo "Success.. Connected to Database...<br /> ";
}
function insertData($DATA)
{
db_connect();
$requete = "INSERT INTO data SET col_Data='".$DATA."'";
if(!mysql_query($requete))
echo mysql_error();
else
echo 'data accepted.';
}
if(isset($_GET['DATA']))
{
insertData($_GET['DATA']);
}
else
{
echo 'Nop';
}
?>
this is a working script when I use this url to post data
localhost/hit.php?DATA=iamwicked
When I use this it save iamwicked in database hit table data column col_data
so how do I fix my script to send more data to col_data2 and so forth

Return $conn connection resource #id from function
<?php
function db_connect()
{
$hostname = '127.0.0.1';
$db_user = 'root';
$db_password = '';
$db_name = 'hit';
$conn = mysql_connect ($hostname, $db_user, $db_password) or
die (mysql_error());
echo "Success.. Connected to MySQL...<br />";
mysql_select_db($db_name) or die(mysql_error());
echo "Success.. Connected to Database...<br /> ";
return $conn;
}
$conn = db_connect();
To insert single field
function insertData($DATA)
{
$requete = "INSERT INTO data SET col_Data='".$DATA."'";
mysql_query($requete) or die(mysql_error());
}
if(isset($_GET['DATA'])) {
insertData($_GET['DATA']);
}
if(isset($_GET['DATA2'])) {
insertData($_GET['DATA2']);
}
UPDATE
To insert multiple fields
function insertData($DATA, $DATA2)
{
$requete = "INSERT INTO data SET col_Data='".$DATA."', col_Data2='".$DATA2."'";
mysql_query($requete) or die(mysql_error());
}
if(isset($_GET['DATA']) && isset($_GET['DATA2'])) {
insertData($_GET['DATA'], $_GET['DATA2']);
}
?>

I think you have an wrong spelling here:
function insertData($DATA2) instead of function insterData($DATA2);

There are indeed two problems here.
function insertData($DATA)
{
function insterData($DATA2)
{
What are you trying to achieve here? Declaring a function inside another function is totally useless (and generates errors since it's not allowed). If you want to call a function inside another one you must declare them separately and then call them, f.e.
function insertData($DATA)
{
insterData($somevariable);
//Rest of the operations
}
This should be clear enough. There is another error though.
if(isset($_GET['DATA']))
if(isset($_GET['DATA2']))
}
insertData($_GET['DATA']);
insertData($_GET['DATA2']);
}
else
{
echo 'Nop';
}
I suppose there is a typo here, and you meant
if(isset($_GET['DATA2']))
{

Related

How to connect to MySQL database in PHP using mysqli extension?

I have code like this to connect my server database:
<?php
$con = mysqli_connect("", "username", "password", "databasename");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
But it displayed "Failed to connect to MySQL", what is wrong with this code? First time I am trying it in web server, whereas my localhost worked perfectly.
mysqli_connect("","username" ,"password","databasename");//Server name cannot be NULL
use loaclhost for server name(In Loacl)
<?php
$con = mysqli_connect("localhost","username" ,"password","databasename");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Or can use MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$con = mysqli_connect($servername, $username, $password);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
EDIT 01
$servername = "localhost";
$username = "root";
$password = "";
To connect to the MySQL database using mysqli you need to execute 3 lines of code. You need to enable error reporting, create instance of mysqli class and set the correct charset.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname', 3307);
$mysqli->set_charset('utf8mb4'); // always set the charset
The parameters in the mysqli constructor are all optional, but most of the time you would want to pass at least 4 of them. In the correct order they are:
MySQL Host. Most of the time it is localhost, but if you connect to a remote host it will be some other IP address. Make sure this does not contain the http protocol part. It should either be an IP address or the URL without protocol.
Username. This is the username of your MySQL user. To connect to the MySQL server you need to have a valid user with the right privileges.
Password.
Database name. This is the MySQL database name you want to connect to.
Port. Most of the time the default port is the correct one, but if you use for example wampserver with MariaDB, you might want to change it to 3307.
Socket name. Specifies the socket or named pipe that should be used.
Unfortunately the charset is not one of these parameters, so you must use a dedicated function to set this very important parameter.
Please beware never to display the connection errors manually. Doing so is completely unnecessary and it will leak your credentials.
On unrelated note: I do not recommend to use MySQLi in a new project. Please consider using PDO, which is overall a much better API for connecting to MySQL.
Why use mysqli? Just use PDO for safer mysql connection just use:
$hostname='localhost';
$username='root';
$password='';
$dbh = new PDO("mysql:host=$hostname;dbname=dbname",$username,$password);
You should specify hostname
$con = mysqli_connect("localhost","username" ,"password","databasename");
If it returns an error like
Failed to connect to MySQL: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'
Replace localhost with 127.0.0.1.
If still you cant connect check if mysql server is actually running.
service mysqld start
Then, try the one of the following following:
(if you have not set password for mysql)
mysql -u root
if you have set password already
mysql -u root -p
$localhost = "localhost";
$root = "root";
$password = "";
$con = mysql_connect($localhost,$root,$password) or die('Could not connect to database');
mysql_select_db("db_name",$con);
<?php
$servername="";
$username="";
$password="";
$db="";
$conn=mysqli_connect($servername,$username,$password,$db);
//mysql_select_db($db);
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno($conn) . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error($conn) . PHP_EOL;
exit;
}
#session_start();
$event_name = $_POST['first_name'];
$first_name = $_POST['last_name'];
$sql = "INSERT INTO customer(first_name, last_name,) VALUES ('$first_name', '$last_name')";
$conn->query($sql);
$lastInsertId = mysqli_insert_id($conn);
?>
A better method is to keep the connection and the login parameters apart.
<?php
class Database{
protected $url;
protected $user;
protected $passw;
protected $db;
protected $connection = null;
public function __construct($url,$user,$passw,$db){
$this->url = $url;
$this->user = $user;
$this->passw = $passw;
$this->db = $db;
}
public function __destruct() {
if ($this->connection != null) {
$this->closeConnection();
}
}
protected function makeConnection(){
//Make a connection
$this->connection = new mysqli($this->url,$this->user,$this->passw,$this->db);
if ($this->connection->connect_error) {
echo "FAIL:" . $this->connection->connect_error;
}
}
protected function closeConnection() {
//Close the DB connection
if ($this->connection != null) {
$this->connection->close();
$this->connection = null;
}
}
protected function cleanParameters($p) {
//prevent SQL injection
$result = $this->connection->real_escape_string($p);
return $result;
}
public function executeQuery($q, $params = null){
$this->makeConnection();
if ($params != null) {
$queryParts = preg_split("/\?/", $q);
if (count($queryParts) != count($params) + 1) {
return false;
}
$finalQuery = $queryParts[0];
for ($i = 0; $i < count($params); $i++) {
$finalQuery = $finalQuery . $this->cleanParameters($params[$i]) . $queryParts[$i + 1];
}
$q = $finalQuery;
}
$results = $this->connection->query($q);
return $results;
}
}?>
This in combination with a database factory keeps the data separated and clean.
<?php
include_once 'database/Database.php';
class DatabaseFactory {
private static $connection;
public static function getDatabase(){
if (self::$connection == null) {
$url = "URL";
$user = "LOGIN";
$passw = "PASSW";
$db = "DB NAME";
self::$connection = new Database($url, $user, $passw, $db);
}
return self::$connection;
}
}
?>
After that you can easily make your (class based) your CRUD classes (objectname+DB)
<?php
include_once "//CLASS";
include_once "//DatabaseFactory";
class CLASSDB
{
private static function getConnection(){
return DatabaseFactory::getDatabase();
}
public static function getById($Id){
$results = self::getConnection()->executeQuery("SELECT * from DB WHERE Id = '?'", array(Id));
if ($results){
$row = $results->fetch_array();
$obj = self::convertRowToObject($row);
return $obj;
} else {
return false;
}
}
public static function getAll(){
$query = 'SELECT * from DB';
$results = self::getConnection()->executeQuery($query);
$resultsArray = array();
for ($i = 0; $i < $results->num_rows; $i++){
$row = $results->fetch_array();
$obj = self::convertRowToObject($row);
$resultsArray[$i] = $obj;
}
return $resultsArray;
}
public static function getName($Id){
$results = self::getConnection()->executeQuery("SELECT column from DB WHERE Id = '?'", array($Id));
$row = $results->fetch_array();
return $row['column'];
}
public static function convertRowToObject($row){
return new CLASSNAME(
$row['prop'],
$row['prop'],
$row['prop'],
$row['prop']
);
}
public static function insert ($obj){
self::getConnection()->executeQuery("INSERT INTO DB VALUES (null, '?', '?', '?')",
array($obj->prop, $obj->prop, $obj->prop));
}
public static function update ($propToUpdate, $Id){
self::getConnection()->executeQuery("UPDATE User SET COLTOUPDATE = ? WHERE Id = ?",
array($propToUpdate, $Id));
}
}
And with this fine coding it's a piece of cake to select items in frontend:
include 'CLASSDB';
<php
$results = CLASSDB::getFunction();
foreach ($results as $class) {
?>
<li><?php echo $class->prop ?><li>
<php } ?>
The easiest way to connect to MySQL server using php.
$conn=new mysqli("localhost", "Username", "Password", "DbName");
if($conn->connect_error)
{
die("connection faild:".$conn->connect_error);
}
echo "Connection Successfully..!";
localhost like this (MySQLi Procedural)
<?php
$servername ="localhost";
$username="username";//username like (root)
$password="password";//your database no password. (" ")
$database="database";
$con=mysqli_connect($servername,$username,$password,$database);
if (!$con) {
die("Connection failed: " . MySQL_connect_error());
}
else{
echo "Connected successfully";
}

Mysqli connection in function PHP

I'm facing a PHP problem. I've searched the web but couldn't find the answer. This is my code so far:
<?php
$db_host = 'db_host';
$db_user = 'db_user';
$db_password = 'db_password';
$db_name = 'db_name';
//not showing you the real db login ofcourse
$conn = mysqli_connect($db_host, $db_user, $db_password, $db_name);
if($conn) {
echo 'We are connected!';
}
Up to here, everyting goes well. The connection is established and 'We are connected!' appears on the screen.
function login($username, $password, $conn) {
$result = $conn->query("SELECT * FROM users");
echo mysqli_errno($conn) . mysqli_error($conn);
}
When I run this function however, the mysqli error 'No database selected pops up. So I added the following piece of code the the file before and in the function, so the total code becomes:
<?php
$db_host = 'db_host';
$db_user = 'db_user';
$db_password = 'db_password';
$db_name = 'db_name';
//not showing you the real db login ofcourse
$conn = mysqli_connect($db_host, $db_user, $db_password, $db_name);
if($conn) {
echo 'We are connected!';
}
if (!mysqli_select_db($conn, $db_name)) {
die("1st time failed");
}
function login($username, $password, $conn, $db_name) {
if (!mysqli_select_db($conn, $db_name)) {
die("2nd time failed");
}
$result = $conn->query("SELECT * FROM users");
echo mysqli_errno($conn) . mysqli_error($conn);
}
$username = 'test';
$password = 'test';
login($username, $password, $conn, $db_name);
?>
The first time adding the database name works fine, however, in the function it doesn't work. I've also tried using global $conn inside the function but that didn't work either. Changing mysqli_connect() to new mysqli() also doesn't have any effect.
Thanks in advance!
Please be aware, this code is refactored based on your code, and the login logic is NOT RECOMMENDED. Please try this code and make the changes that you think you need.
Make sure that your Database information is also updated as needed.
MyDB Class
Class MyDB {
protected $_DB_HOST = 'localhost';
protected $_DB_USER = 'user';
protected $_DB_PASS = 'password';
protected $_DB_NAME = 'table_name';
protected $_conn;
public function __construct() {
$this->_conn = mysqli_connect($this->_DB_HOST, $this->_DB_USER, $this->_DB_PASS);
if($this->_conn) {
echo 'We are connected!<br>';
}
}
public function connect() {
if(!mysqli_select_db($this->_conn, $this->_DB_NAME)) {
die("1st time failed<br>");
}
return $this->_conn;
}
}
Login Class
Class Login {
protected $_conn;
public function __construct() {
$db = new MyDB();
$this->_conn = $db->connect();
}
//This is a HORRIBLE way to check your login. Please change your logic here. I am just kind of re-using what you got
public function login($username, $password) {
$result = $this->_conn->query("SELECT * FROM user WHERE username ='$username' AND password='$password'");
if(!$result) {
echo mysqli_errno($this->_conn) . mysqli_error($this->_conn);
return false;
}
return $result->fetch_row() > 0;
}
}
Usage
$login = new Login();
$logged = $login->login('username', 'password');
if ($logged) {
echo "yeah!! you are IN";
} else {
echo "boo!! . Wrong username and password";
}

How to get database in php using class & function oops concepts

I am new developer in php. I'm writing below code a class and functions to connect to the database. but code was not working how to create class and function oops concept help me.
code:
class database {
#code
var $host = "localhost";
var $username ="root";
var $password ="";
var $dbase ="blue";
var $myconnect;
function connectTodata()
{
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
die("Cannot Connect to the datagase");
}
else
{
$his->myconnect = $conn;
echo "Connect Established";
}
return $myconnect;
}
function selectDatabase() // selecting the database.
{
mysql_select_db($this->database); //use php inbuild functions for select database
if(mysql_error()) // if error occured display the error message
{
echo "Cannot find the database ".$this->database;
}
echo "Database selected..";
}
function closeConnection() // close the connection
{
mysql_close($this->myconn);
echo "Connection closed";
}
}
Just to make it work:
class database
{
#code
var $host = "localhost";
var $username ="root";
var $password ="";
var $dbase ="blue";
var $myconnect;
function connectTodata()
{
$this->myconnect = mysql_connect($this->host, $this->username, $this->password);
if(!$this->myconnect) die("Cannot Connect to the datagase");
echo "Connect Established";
return $this->myconnect;
}
function selectDatabase() // selecting the database.
{
mysql_select_db($this->database); //use php inbuild functions for select database
if(mysql_error()) // if error occured display the error message
{
echo "Cannot find the database ".$this->database;
}
echo "Database selected..";
}
function closeConnection() // close the connection
{
mysql_close($this->myconnect);
echo "Connection closed";
}
}
Fix the errors as described by the previous posters, then try this to start:
$database_connection=new database();
$database_handle=$database_connection->connectTodata();
$database_connection->selectDatabase();
$database_connection->closeConnection();
unset($database_connection);
exit();
and in the space between the chunks of code, you can add your mysql queries and use $database_handle as the second parameter.
you can use constructor so that you don't need to call class function everytime :
class database {
var $host = "localhost";
var $username ="root";
var $password ="";
var $dbase ="blue";
var $myconnect;
function __construct() {
$this->myconnect = mysql_connect($this->host, $this->username, $this->password);
if( !$this->myconnect ) {
$msg = "could not connect to mysql database <Br/>";
$msg .= mysql_error();
die($msg);
}
$db_connect = mysql_select_db($this->dbase, $this->myconnect);
if( !$db_connect ) {
die(" can not select database \n".mysql_error());
}
}
function __destruct() {
mysql_close($this->myconnect);
}
}
// call database
$con = new database();
You can do it with the help of Defining them something like
define("DB_SERVER_NAME","your host");
define("DB_USER_NAME","your user name");
define("DB_USER_PASSWORD","your password");
define("DB_DATABASE_NAME","your database");
now the connection file:
class DBClass{
public $DB_LINK;
public $DB_DATABASE_NAME;
function DBClass($Main_DB = FALSE){
$this->DB_LINK = #mysqli_connect(DB_SERVER_NAME,DB_USER_NAME,DB_USER_PASSWORD,DB_DATABASE_NAME);
if(! $this->DB_LINK){
die("<h2>Could not connect to Database.</h2>");
}
}
function __destruct(){
mysqli_close($this->DB_LINK);
}
}
This works perfectly for me

XML request MySQL by PHP

Actually i'm working in a flash web page using XML. I want to make a sing up page with XML that uses PHP to insert data into de MySQL database, but I'm stuck... and i my XML-PHP knowledge are not enough for this duty.
This is the XML file:
<?xml version="1.0" encoding="utf-8"?>
<data>
<title>Sing up</title>
<request field1="user" field2="email" field3="password" field4="other">reg.php</request>
<description><![CDATA[Please sing up!]]></description>
</data>
The reg PHP file:
<?php
function Reg()
{
if (isset($_POST['reg'])==true) {
require_once('db_conf.php');
$user = $_POST['username'];
$pass = sha1(strtoupper($user.':'.$_POST['password']));
$email = $_POST['email'];
$con = mysql_connect($dbhost, $dbuser, $dbpassword);
if (!$con)
{
die('Could not connect!');
} else {
mysql_select_db("$logondb", $con);
$sql="INSERT INTO accounts (username, sha_pass_hash, email) VALUES ('$user','$pass','$email')";
if (!mysql_query($sql,$con))
{
die('Error creating account.');
}
echo $succesmsg;
mysql_close($con);
}
} else {
?>
And PHP conf for database:
<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpassword = 'password';
// Accounts Database
$logondb = 'accounts';
$errormsg="Error creating account..";
$succesmsg="Account created!";
?>
I would like to suggest using PDO instead - it's a more general approach. And then you should use data-binding to reduce vulnerability against SQL Injections...
This should take you one step further:
<?php
function Reg()
{
if (isset($_POST['reg'])==true) {
require_once('./db_conf.php');
$user = $_POST['username'];
$pass = sha1(strtoupper($user.':'.$_POST['password']));
$email = $_POST['email'];
$dsn = "mysql:host=$dbhost;dbname=$logondb";
$pdo = new PDO($dsn,$dbuser,$dbpassword);
if (!$pdo)
{
die('Could not connect!');
} else {
$sql = "INSERT INTO accounts (username, sha_pass_hash,email) VALUES (:user,:pass,:email)";
$stmt = $pdo->prepare($sql);
$res = $stmt->execute(array("user"=>$user , "pass"=>$pass , "email" => $email));
if (!$res) {
echo "Error :((<pre>";
var_dump($stmt->errorInfo());
echo "</pre>";
} else
{
echo $succesmsg;
}
}
} else {
echo "reg was not set - terminating...!";
}
}
Reg(); // execute it!
?>

php script to execute sql statements inside a dump file

I have a php script that is supposed to execute several mysql statements, everything works if there are no comments /* */ and no breaklines...
Could you please help me add this functionality, also ignore -- comments
<?
$sqlFileToExecute = 'mysql_dump.sql';
$hostname = 'localhost';
$db_user = 'root';
$db_password = '';
$database_name = 'db_';
$link = mysql_connect($hostname, $db_user, $db_password);
if (!$link) {
die ("error connecting MySQL");
}
mysql_select_db($database_name, $link) or die ("wrong DB");
$f = fopen($sqlFileToExecute,"r+");
$sqlFile = fread($f, filesize($sqlFileToExecute));
$sqlArray = explode(';',$sqlFile);
foreach ($sqlArray as $stmt) {
//THIS SEEMS NOT TO WORK
if (strlen($stmt)>3 && substr(ltrim($stmt),0,2)!='/*') {
$result = mysql_query($stmt);
if (!$result) {
$sqlErrorCode = mysql_errno();
$sqlErrorText = mysql_error();
$sqlStmt = $stmt;
break;
}
}
}
if ($sqlErrorCode == 0) {
echo "SETUP COMPLETED ;)";
} else {
echo "FAIL!<br/>";
echo "Error code: $sqlErrorCode<br/>";
echo "Error text: $sqlErrorText<br/>";
echo "Statement:<br/> $sqlStmt<br/>";
}
?>
Are you sure you need to run it this manner:
You can also use
$mysql -pxxx -u username db_name -vvv < sourcefile.sql >/tmp/outfile.log
Enable verbose mode to check the stats, else you can omit -vvv option
OR
mysql > source "sourcefile.sql"
You can see more options here

Categories