When ever I use php to connect to my database I get a sudden error saying "database connection failed" is there anyway to fix this its for a login and register screen. Thanks to anyone who help...
<?php
$connection = mysqli_connect('localhost', 'root','','test');
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'test');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
<?php
//
require('database.php');
$connection = mysqli_connect('localhost', 'root','','test');
// If the values are posted, insert them into the database.
if (isset($_POST['Register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
//echo $query;
$result=mysqli_query($connection,$query);
if($result){
$smsg = "User Created Successfully.";
}else{
$fmsg ="User Registration Failed";
}
}
?>
Connection to a database with php requires 4 parameters (host, data base user, password, data base name, passwd), it's better nowadays to use db object instead of procedural "old" behaviour:
function connection(){
try{
//host, user, passwd, DB name)
$mysqli = new mysqli("localhost", $dbUser, $passwd, $dbName);
if (!$mysqli->set_charset("utf8")) $msg = "error charset mySQLi"; else $msg = "Set UTF-8 ok";
return $mysqli;
}
catch (Exception $mysqlin){
echo "Error stablishing connection with database ".$mysqlin->getMessage();
}
}
then you can connect easily as follows:
$sql = "SELECT * FROM users;";
if(!$result = connection()->query($sql)) echo "db query error"; else "query ok";
$rs = mysqli_fetch_assoc($result);
//do whatever and, to get next line of results:
if($rs!=''){
$rs = mysqli_fetch_assoc($result);
}
So you get a row of the results on $rs[] array.
EDIT: You'll need to apply security, this is a simple connection without regarding on it. Check mysqli bind params on php official webpage for it:
http://php.net/manual/en/mysqli-stmt.bind-param.php
Hope it helps
Related
I have tried debugging and cannot seem to get to the bottom of this problem. My query returns successful, however nothing is inserted into my table within my database. I am working on a CRUD application to enter holdings of cryptocurrency, and this is simply the Create button. My function gets to the very end of the if statement, and Mysqli_query returns a 1. Could this be issues with permissions in PHPAdmin? Or possibly something to do with Ports?
The code below:
$con = createDB();
if (isset($_POST['create'])){
createData();
}
function createData(){
$username = textboxValue('Username');
$BTC = textboxValue('BTC');
$ETH = textboxValue('ETH');/*$ETH =(isset($_POST['ETH']) ? $_POST['ETH'] : '');*/
$DASH = textboxValue('DASH');
if($username && $BTC && $ETH && $DASH){
$sql = "INSERT INTO cryptoholdings(username,BTC_holdings,ETH_holdings,DASH_holdings)
VALUES('$username','$BTC','$ETH','$DASH')";
if($GLOBALS['con']->query($sql) ){ /*(mysqli_query($GLOBALS['con'],$sql))*/
$GLOBALS['con']->commit();
echo "Record Successfully inserted...!";
}
else{
echo "Error Recording Data <br>" . mysqli_error($GLOBALS['con']);
}
}
else{echo "Provide all data in textboxes.";
}
}
function createDB(){
$servername='localhost';
$username='root';
$password='password';
$dbname='holdings';
//create connection to our database "holdings"
$con=mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection Failed: ". mysqli_connect_error());
}
//create Database
$sql= 'CREATE DATABASE IF NOT EXISTS $dbname';
if(mysqli_query($con,$sql)){
$con = mysqli_connect($servername,$username,$password,$dbname);
$sql= 'CREATE TABLE IF NOT EXISTS cryptoholdings(
username VARCHAR(25) NOT NULL,
BTC_holdings FLOAT(11) NOT NULL,
ETH_holdings FLOAT(11) NOT NULL,
DASH_holdings FLOAT(11) NOT NULL)';
if(mysqli_query($con,$sql)){
return $con;}
else{
echo "Error when Creating Table...";
}
}
else{
echo "Error while creating Database...". mysqli_error($con);
}
}
function textboxValue($value){
$textbox = mysqli_real_escape_string($GLOBALS['con'],trim($_POST[$value]));
if(empty($textbox)){
return false;
}
else{
return $textbox;
}
}
First check that the connection was very okay by echoing something from the db or by doing sth on the db. 2nd try using another method other than the global con being used. For the purpose of testing and finding solution, I recommend you create a simpler table (of one or 2 fields) and try inserting into the fields. I recommend this method of connection below.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
New to php and am connecting form attributes to php to connect to a godaddy mysql. Every attempt ends in a blank screen with no error messages. Is there any syntax errors the jump out? My sublime text wont register php syntax, but thats another problem for another time. I may need to call up godaddy support? the password has been removed for privacy.
<?php
$servername = "localhost";
$dbusername = "jaysenhenderson";
$dbpassword = "xxxxx";
$dbname = "EOTDSurvey";
$con = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
mysql_select_db('EOTDSurvey', $con)
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo("Connected successfully");
$_POST['BI1']
$_POST['BI2']
$_POST['BI3']
$_POST['BI4']
$_POST['BI5']
$_POST['BI6']
$_POST['BI7']
$_POST['BI8']
$_POST['BI9']
$_POST['BI10']
$_POST['BI11']
$_POST['BI12']
$_POST['BI13']
$_POST['BI14']
$_POST['BI15']
$sql = "INSERT INTO Survey1(BI1)"
$sql = "INSERT INTO Survey1(BI2)"
$sql = "INSERT INTO Survey1(BI3)"
$sql = "INSERT INTO Survey1(BI4)"
$sql = "INSERT INTO Survey1(BI5)"
$sql = "INSERT INTO Survey1(BI6)"
$sql = "INSERT INTO Survey1(BI7)"
$sql = "INSERT INTO Survey1(BI8)"
$sql = "INSERT INTO Survey1(BI9)"
$sql = "INSERT INTO Survey1(BI10)"
$sql = "INSERT INTO Survey1(BI11)"
$sql = "INSERT INTO Survey1(BI12)"
$sql = "INSERT INTO Survey1(BI13)"
$sql = "INSERT INTO Survey1(BI14)"
$sql = "INSERT INTO Survey1(BI15)"
if ($conn->query<$sql) === TRUE) {
echo "IT FUCKING WORKS.";
}
else{
echo "didnt workkkkkk";
}
$conn->close();
?>
please connect database like this...
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
And Use mysqli_select_db instead of mysql_select_db
And insert semi-colon (;) after every line end according to php code standard.
There are a lot of issues with this code, as mentioned the mysqli_select_db issue. The $_POST['BIx'] will also cause errors because there is no semi-colon after each statement. You're missing a '(' on the line if ($conn->query<$sql) === TRUE) { not to mention that line will not work anyway because you're logically comparing a resource type (I think) to a string.
You're also never executing the insert statements. All around I seriously think you should practice PHP coding some more and read up on how to use mysqli properly: see here.
Regards
EDIT: You also have a closing PHP tag at the end of your script which is generally not a good idea as explained here
EDIT 2: Also using an IDE such as Netbeans is always a good idea as it can highlight syntax errors instead of asking SO to do it for you ;)
<?php
$servername = "localhost";
$dbusername = "jaysenhenderson";
$dbpassword = "xxxxx";
$dbname = "EOTDSurvey";
$con = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
mysqli_select_db('EOTDSurvey', $con);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo("Connected successfully");
############# Function For Insert ##############
function insert($tableName='',$data=array())
{
$query = "INSERT INTO `$tableName` SET";
$subQuery = '';
foreach ($data as $columnName => $colValue) {
$subQuery .= " `$columnName`='$colValue',";
}
$subQuery = rtrim($subQuery,', ');
$query .= $subQuery;
pr($query);
mysqli_query($con,$query) or die(mysqli_error());
return mysqli_insert_id();
}//end insert
#########################################
if(isset($_POST['submit'])){
unset($_POST['submit']);
//print_r($_POST);
$result=insert('Survey1',$_POST);
if($result){
echo '<script>window.alert("Success!");</script>';
echo "<script>window.location.href = 'yourpage.php'</script>";
}
}
$conn->close();
?>
include_once 'dbfunction.php';
getDbConnect();
mysqli_query("DELETE FROM crewlist WHERE id = $_GET[crew_id]") or die (mysqli_error());
echo 'Delete success';
header ('Location: crewlisting.php');
This code doesn't work, however when I replace the crew_id with the actual primary key via hard coding the delete function works
Use this (MySQLi Procedural)
In dbfunction.php should be
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
?>
and insert page should be
<?
include ("dbfunction.php"); //include db connection
$id = $_REQUEST['crew_id'];
$sql = "DELETE FROM crewlist WHERE id = '$id' ";
if (mysqli_query($conn, $sql))
{
echo "Record deleted successfully";
}
else
{
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Errors are
There is no function define in getDbConnect()
If you are confusing with 'and " then split the functions
$id = $_REQUEST['crew_id'];
$sql = "DELETE FROM crewlist WHERE id = '$id' ";
Use mysqli_query and mysqli_error in correct format
and error in mysqli_query, You are not passing connection to MySQLi
When ever database part is Finished, Close connection mysqli_close($conn);
Correct your query:
mysqli_query("DELETE FROM crewlist WHERE id ='".$_GET['crew_id']."'") or die('Error: ' . mysqli_error());
I need to only new data to a database table. I am trying to query the database but and only add new data. I am somewhat lost in SQL and PHP.
I have got the code entering to the database but on refresh it will enter the same data again and I only want it to allow new data:
<?php
// DATA BASE CONNECTION
DEFINE ('DB_USERS', 'root');
DEFINE ('DB_PASS', 'root');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'sam_api');
$dbc = #mysqli_connect (DB_HOST, DB_USERS, DB_PASS, DB_NAME) OR die ('could not connect' . mysqli_connect_error());
$user_update = $items['id'];
// Check if file already exists
$query = mysqli_query($con, "SELECT * FROM updates WHERE $user_update ='".$items['id']."'");
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
}
// now inserting the data form the previous page in to the database
$q = "INSERT INTO updates (user_update) VALUES ('$user_update')";
$r = #mysqli_query ($dbc,$q);
// telling you if it has been uploaded or not
if($r){
echo "you have successfully inserted";
} else{
echo "this did not work";
}
?>
Remove $ from user_update, because you want to compare field's value, not value with itself.
$query = mysqli_query($con, "SELECT * FROM updates WHERE user_update ='".$items['id']."'");
I have a very simple bit of code to insert data into database.
It doesn't work. I do not get any error except cannot insert. I could connect to the database so that is not the issue.
The database has 3 fields, emailadd is the 2nd field. The other 2 are auto increment id and creation date, so also a field that on add, it will add current timestamp.
$inquiry = "INSERT INTO subscribe (emailadd) VALUES ('$myemail')";
$res = mysql_query($inquiry) or die("cannot insert");
$inquiry = "INSERT INTO `subscribe` (`emailadd`) VALUES ('$myemail')";
$res = mysql_query($inquiry,$con) or die('Not Inserted : ' . mysql_error());
Some time we need $con variable to identify the database connection, let see more check here
the mysql_query is deprecated, you need to use mysqli like so :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>