MAMP can't establish database connection - php

I'm trying to save data from a multi-page form into a database. I followed this tutorial but the connection always fails. I had to change to function from mysql_connect to mysqli_connect as I am running PHP7, so this could be part of the issue. Here is the code:
<?php
session_start();
if (isset($_POST['state'])) {
if (!empty($_SESSION['post'])){
if (empty($_POST['address1'])
|| empty($_POST['city'])
|| empty($_POST['pin'])
|| empty($_POST['state'])){
// Setting error for page 3.
$_SESSION['error_page3'] = "Mandatory field(s) are missing, Please fill it again";
header("location: finder-step-3.php"); // Redirecting to third page.
} else {
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
extract($_SESSION['post']); // Function to extract array.
$connection = mysqli_connect("localhost", "root", "root");
$db = mysqli_select_db($connection, "finder_form"); // Storing values in database.
$query = mysqli_query($db, "insert into detail (name,email,contact,password,religion,nationality,gender,qualification,experience,address1,address2,city,pin,state) values('$name','$email','$contact','$password','$religion','$nationality','$gender','$qualification','$experience','$address1','$address2','$city','$pin','$state')", $connection);
if ($query) {
echo '<p><span id="success">Form Submitted successfully..!!</span></p>';
} else {
echo '<p><span>Form Submission Failed..!!</span></p>';
}
unset($_SESSION['post']); // Destroying session.
}
} else {
header("location: finder-step-1.php"); // Redirecting to first page.
}
} else {
header("location: finder-step-1.php"); // Redirecting to first page.
}
?>
Can anyone spot where I am going wrong? Thanks in advance!
Update 1:
#Damon Swayn, I have changed it to the below but still receive the form submission failed message:
$connection = mysqli_connect("localhost", "root", "root", "finder_form");
$query = mysqli_query($connection, "insert into detail (name,email,contact,password,religion,nationality,gender,qualification,experience,address1,address2,city,pin,state) values('$name','$email','$contact','$password','$religion','$nationality','$gender','$qualification','$experience','$address1','$address2','$city','$pin','$state')", $connection);
if ($query) {
echo '<p><span id="success">Form Submitted successfully..!!</span></p>';
} else {
echo '<p><span>Form Submission Failed..!!</span></p>';
}
#lps, I setup the following on a test.php page in the same directory and it connected successfully:
<?php
$con = mysqli_connect('localhost', 'root', 'root') or die('Could not connect the database : Username or password incorrect');
mysqli_select_db($con, 'finder_form') or die ('No database found');
echo 'Database Connected successfully';
?>
Update 2: Solved
The changes suggested by Damon Swayn worked, I just had to remove the $connection at the end of the query. Here is the working code:
$connection = mysqli_connect("localhost", "root", "root", "finder_form");
$query = mysqli_query($connection, "insert into detail (name,email,contact,password,religion,nationality,gender,qualification,experience,address1,address2,city,pin,state) values('$name','$email','$contact','$password','$religion','$nationality','$gender','$qualification','$experience','$address1','$address2','$city','$pin','$state')");
if ($query) {
echo '<p><span id="success">Form Submitted successfully..!!</span></p>';
} else {
echo '<p><span>Form Submission Failed..!!</span></p>';
}

mysqli_connect() can take 4 parameters, the fourth being the database name.
you are using the return value of mysqli_select_db() as the connection param for every following call, mysqli_select_db() returns a boolean true/false value, try replacing the $db param in the following calls after mysqli_select_db() with the $connection variable.

Related

I want to update the one column in database on click the vote button

I started writing code for a basic voting system. But I got this error message.
Warning: mysqli_query() expects parameter 1 to be mysqli, bool given
in E:\My-WORLD\xampp\htdocs\php-tut\voting\vote.des.php on line 6
<?php
$con = mysqli_connect("localhost","root","","voting") || die("not
connected");
echo "connected";
if(isset($_POST['ele'])){
global $con;
$vote_ele = "update votes set ele = ele + 1";
$run = mysqli_query($con,$vote_ele);
if($run){
echo "voted to electronics";
}
else{
echo mysqli_error($run);
}
}
?>
Neither || or or should be ever written in connection to any mysqli function.
How to properly connect with mysqli:
$host = '127.0.0.1';
$db = 'voting';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$con = mysqli_connect($host, $user, $pass, $db);
mysqli_set_charset($con, $charset);
} catch (\mysqli_sql_exception $e) {
throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
}
Given this script is not the only one uses a mysql connection, store this code in a separate file named mysqli.php and then include it in other files. Therefore your current code will become
<?php
include 'mysqli.php';
if(isset($_POST['ele']))
{
$vote_ele = "update votes set ele = ele + 1";
$run = mysqli_query($con,$vote_ele);
echo "voted to electronics";
}
See - it is concise, tidy and reusable.
When you use $con = mysqli_connect("localhost","root","","voting") || die("not
connected"); you are assigning a bool to $con variable. So it is not mysqli anymore.
Also, When you use global $con you are overriding $con value, So it is not mysqli which you assigned in the pervious line anymore.
try this:
$con = mysqli_connect("localhost", "root", "", "voting");
if (mysqli_connect_errno())
die("Failed to connect to MySQL: " . mysqli_connect_error());
echo "connected";
if (isset($_POST['ele'])) {
// This will override $con value!!
// global $con;
$vote_ele = "update votes set ele = ele + 1";
$run = mysqli_query($con, $vote_ele);
if ($run) {
echo "voted to electronics";
}
else {
echo mysqli_error($run);
}
}

Running php functions on the same screen

Hi I'm very very new to php and playing with codes to learn. I have a very basic login form that has username and password input and two input buttons
one to create entries in the database and other to read from database.
JsFiddle: https://jsfiddle.net/e93kcpto/
My sign up and read functions are located in functions.php file
function signUpFunct(){
if(isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$connection = mysqli_connect('localhost','root','','loginPage');
if($connection){
$query = "INSERT INTO users(username,password) VALUES ('$username','$password')";
if($query){
mysqli_query($connection,$query);
}
else{
die("Sign Up Failed");
}
}
else{
die("Failed to Connect Database");
}
}
}
function readAll(){
$connection = mysqli_connect('localhost','root','','loginPage');
if($connection){
$query = "SELECT * FROM users";
if($query){
$result = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($result)){
?>
<pre>
<?php print_r($row);?>
</pre>
<?php
}
}
else{
die("Sign Up Failed");
}
}
else{
die("Failed to Connect Database");
}
}
and this is how I call these two functions in the functions.php file(I'm not sure if this is a good approach so if there is a better way please let me know)
if(isset($_POST['signUp'])){
signUpFunct();
}
else if(isset($_POST['display'])){
readAll();
}
both functions work fine but the problem is when I click on the display button in the browser I am at http://localhost.../functions.php
what I would like to do is to display the data on the form page when I click on the Display button. How can I do this?

php mysql script not working

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']))
{

Inserting user updates into SQL with PHP

I think I am really close now - there are no more nasty Orange boxes with errors in - the only problem I can see at the moment is that once I update the table (after the
$qry = "UPDATE 'members' ('employer', 'flat') WHERE login='$login_name' VALUES ". " ('$employ', $address')";
) I get the message "No rows updated" echo to the screen!
Any ideas what the problem is?
Thanks.
<?php
//Start session
session_start();
$_SESSION['SESS_LOGIN'];
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$employ = clean($_POST['employer']);
$address = clean($_POST['flat']);
?>
<?Php
//Insert employer and address into database row for logged in user.
$login_name = $_POST['login_name'] ;
$qry = "UPDATE 'members' ('employer', 'flat') WHERE login='$login_name' VALUES ". " ('$employ', $address')" ;
$result = #mysql_query($link, $qry);
//Check whether the query was successful or not
if(!$result) {
echo "No rows updated";
exit();
}else {
echo "Success";
}
?>
Don't use VALUES, use SET:
"UPDATE `members` SET `employer` = '".$employ."', `flat` = '".$address."' WHERE `login`='".$login_name."'"
First of all you should not suppress error messages by using the # opperator if you are looking for issues in your code. Also you are using the wrong parentheses (' instead of `). The rest of your code looks fine. maybe you need to give us some info about the database structure otherwise

php mysql prepare statement not working [duplicate]

This question already has answers here:
Fatal error: Call to a member function prepare() on a non-object in
(2 answers)
Closed 6 years ago.
I'm currently learning php and mysql and am trying to build an authentication webpage where the user registers and is able to log in to a member protected page. The registration process works fine but for some reason I'm getting this error in my login execution script.
Fatal error: Call to a member function prepare() on a non-object in /homepages/8/d459264879/htdocs/tymbi_reg/login_exec.php on line 40
Line 40 is here if($stmt = $mysqli->prepare("SELECT * FROM member WHERE username=? AND password =?"))
I've been trying hard to find where the problem is without any success.
This is the code that I'm using in my login script
<?php
session_start();
require_once('connection.php');
$errmsg_arr = array();
$errflag = false;
$username = $_POST['username'];
$password = $_POST['password'];
if($username == '') {
$errmsg_arr[] = 'Username missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: index.php");
exit();
} else {
if($stmt = $mysqli->prepare("SELECT * FROM member WHERE username=? AND password =?"))
{
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->store_results();
if($stmt->num_rows > 0)
{
$SESSION['username'] = $username;
header("Location: home.php");
}
else
{
$error['alert'] = "Username or password are incorrect";
}
}
}
?>
Here's my connection.php code
<?php
$con=new mysqli("test","test","test","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
And yes, I have replaced the test values with my details
make sure you have $mysqli defined properly
$mysqli = new mysqli('host','user','pass','database_name');
You haven't defined $mysqli - your connection. That is why it's not working.
Unless it's defined in connection.php. Could you try var_dump $mysqli and see what you get?
$link = mysqli_connect("localhost", "user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
this helps in reading the connection error.
or you can also use
try
{
//your connection
}catch(Exception $e)
{
echo $e->getMessage();
}
I would recommend going all-in on using the Mysqli object and not mixing in the procedural functions. You would have caught your error earlier if you had written the connection logic like so:
$con = new mysqli("host","user","pass","db");
if ($mysqli->errno)
{
echo "Failed to connect to MySQL: " . $mysqli->error;
}
The OP declared the connection as $con and later tried to access it as $mysqli. mysqli_connect_errno() reports that $con is ok, but $mysqli->errno will fail because $mysqli is not an object at that point, because he named the the connection $con not $mysqli

Categories