Cant connect to MySQL, wrong code? - php

I have tried to connect to my db, but nothing works...
This is the code that I have created:
$name ='testdb';
$user = 'root';
$password = '';
$host = 'localhost';
$link = new mysqli($name, $user, $password, $host);
$name = $_POST['name'];
$message = $_POST['message'];
$mail = $_POST ['mail'];
$name = $link->real_escape_string($_POST['name']);
$message = $link->real_escape_string($_POST['message']);
$mail = $link->real_escape_string($_POST['mail']);
$sql = "INSERT INTO test (Name, Message, Mail) VALUES ('$name','$message', '$mail')";
$result = $link->query($sql);
I have allready double-checked all the spellings.
Can anyone give me some tips? I may have gone blind.

Seems you did not initialize mysqli connection properly
error_reporting(E_ALL);//display all errors
$name ='testdb';
$user = 'root';
$password = '';
$host = 'localhost';
$link = new mysqli($host, $user, $password, $name);
Use prepared statements(Prevents SQL injection)
$sql = "INSERT INTO test (Name, Message, Mail) VALUES (?,?,?)";//placeholders (3placeholders for 3values)
$statement = $link->prepare($sql);//prepare query. returns true/false
$statement->bind_param('sss',$name, $message, $mail);//you dont need to escape anymore
$statement->execute(); //execute safely

The first parameter of mysqli is the hostname, you swapped hostname and databasename Connect to MySQL
$link = new mysqli($host, $user, $password, $name);
You can also use prepared statement, to prevent SQL injections
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
$sql = "INSERT INTO test (Name, Message, Mail) VALUES (?,? ?)";
$stmt = $link->prepare($sql);
$stmt->bind_param("sss",$name, $message, $mail);
$result = $stmt->execute();
if ($result) {
// query was successful
}else {
// query failure
}

Please use this below code it will help you
$name ='testdb';
$user = 'root';
$password = '';
$host = 'localhost';
$link = new mysqli($host,$user,$password,$name);
// Check connection
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$name = $_POST['name'];
$message = $_POST['message'];
$mail = $_POST ['mail'];
$name = $link->real_escape_string($_POST['name']);
$message = $link->real_escape_string($_POST['message']);
$mail = $link->real_escape_string($_POST['mail']);
$sql = "INSERT INTO test (Name, Message, Mail) VALUES ('$name','$message', '$mail')";
if ($link->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link->error;
}
$link->close();
To learn basic things in PHP and MYSQL refer this link
https://www.w3schools.com/php/

Related

How do I get the value of the form into a MySQL table? [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
All I want is to get the var1 from the input into my SQL table. It always creates a new ID, so this is working, but it leaves an empty field in row Email. I never worked with SQL before and couldn't find something similar here. I thought the problem could also be in the settings of the table, but couldn't find anything wrong there.
<input name="var1" id="contact-email2" class="contact-input abo-email" type="text" placeholder="Email *" required="required"/>
<form class="newsletter-form" action="newsletter.php" method="POST">
<button class="contact-submit" id="abo-button" type="submit" value="Abonnieren">Absenden
</button>
</form>
<?php
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
// Connection to DBase
$con = new mysqli($host, $user, $password, $dbase) or die("Can't connect");
$var1 = $_POST['var1'];
$sql = "INSERT INTO table (id, Email) VALUES ('?', '_POST[var1]')";
$result = mysqli_query($con, $sql) or die("Not working");
echo 'You are in!' . '<br>';
mysqli_close($con);
is the id a unique id? that's auto-incremented??
if so you should do something like this
<?php
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
$mysqli = new mysqli($host,$user,$password,$dbase);
$email = $_POST['var1'];
// you might want to make sure the string is safe this is escaping any special characters
$statment = $mysqli->prepare("INSERT INTO table (Email) VALUES (?)");
$statment->bind_param("s", $email);
if(isset($_POST['var1'])) {
$statment->execute();
}
$mysqli->close();
$statment->close();
Simple answer
There are a few things wrong here; but the simple answer is that:
$sql = "INSERT INTO table (id, Email) VALUES ('?', '_POST[var1]')";
...should be:
$sql = "INSERT INTO {$table} (id, Email) VALUES ('?', '{$var1}')";
...OR assuming id is set to auto-increment etc. etc.
$sql = "INSERT INTO {$table} (Email) VALUES ('{$var1}')";
More involved answer
You should really take the time to use prepared statements with SQL that has user inputs. At the very least you should escape the strings yourself before using them in a query.
mysqli
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
$mysqli = new mysqli($host, $user, $password, $dbase); // Make connection to DB
if($mysqli->connect_error) {
die("Error: Could not connect to database.");
}
$email = $_POST["var1"]; // User input from form
$sql = "INSERT INTO {$table} (Email) VALUES(?)"; // SQL query using ? as a place holder for our value
$query = $mysqli->prepare($sql); // Prepare the statement
$query->bind_param("s", $email); // Bind $email {s = data type string} to the ? in the SQL
$query->execute(); // Execute the query
PDO
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
try {
$pdo = new pdo( "mysql:host={$host};dbname={$dbase}", $user, $password); // Make connection to DB
}
catch(PDOexception $e){
die("Error: Could not connect to database.");
}
$email = $_POST["var1"]; // User input from form
$sql = "INSERT INTO {$table} (Email) VALUES(?)"; // SQL query using ? as a place holder for our value
$query = $pdo->prepare($sql); // Prepare the statement
$query->execute([$email]); // Execute the query binding `(array)0=>$email` to place holder in SQL

using variable inside mysql update query in php

<?php
require 'functions/connection.php';
$conn = Connect();
$e_id = $conn->real_escape_string($_POST['e_id']);
$first_name = $conn->real_escape_string($_POST['first_name']);
$last_name = $conn->real_escape_string($_POST['last_name']);
$e_salary = $conn->real_escape_string($_POST['e_salary']);
$e_startdate = $conn->real_escape_string($_POST['e_startdate']);
$e_department = $conn->real_escape_string($_POST['e_department']);
$sql = "UPDATE employee SET firstname='$first_name' WHERE id=$e_id";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
I'm trying to use the first_name variable inside the update query.
I tried echo the variable and its working...
this is my connection code that im using.
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "company";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
if i i replace the variable with anything between "" the database is getting updated
I'd suggest making it more secure and using prepared statements. This is an example using mysqli, but I prefer PDO:
<?php
require 'functions/connection.php';
$conn = Connect();
// Prepare the query
$myQuery = $conn->prepare("UPDATE employee SET firstname=? WHERE id=?");
$e_id = $conn->real_escape_string($_POST['e_id']);
$first_name = $conn->real_escape_string($_POST['first_name']);
$last_name = $conn->real_escape_string($_POST['last_name']);
$e_salary = $conn->real_escape_string($_POST['e_salary']);
$e_startdate = $conn->real_escape_string($_POST['e_startdate']);
$e_department = $conn->real_escape_string($_POST['e_department']);
// Bind your variables to the placemarkers (string, integer)
$myQuery->bind_param('si', $first_name, $e_id);
if ($myQuery->execute() == false) {
echo 'Error updating record: ' . $mysqli->error;
}
else {
echo 'Record updated successfully';
}
$myQuery->close();
?>
Note: The 'cleansing' you're doing in the middle I have left, but it's not really necessary with prepared statements.
functions/connection.php (Now an object):
<?php
class Connect
{
private $dbhost = "localhost";
private $dbuser = "root";
private $dbpass = "";
private $dbname = "company";
public $conn;
public function __construct()
{
if($this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname))
{
//connection established
//do whatever you want here
}
else
{
//Error occurred
die($this->conn->error);
}
}
//other functions here
}
?>
Change mysqli_query to: $conn->conn->query($sql);
Prepared statement:
Avoid SQLI injection
if($stmt = $conn->conn->prepare("UPDATE employee SET firstname = ? WHERE id = ?"))
{
$stmt->bind_param('si', $first_name, $e_id);
$stmt->execute();
echo $stmt->affected_rows;
}
Final code:
<?php
require 'functions/connection.php';
$conn = new Connect();
$e_id = $conn->conn->real_escape_string($_POST['e_id']);
$first_name = $conn->conn->real_escape_string($_POST['first_name']);
$last_name = $conn->conn->real_escape_string($_POST['last_name']);
$e_salary = $conn->conn->real_escape_string($_POST['e_salary']);
$e_startdate = $conn->conn->real_escape_string($_POST['e_startdate']);
$e_department = $conn->conn->real_escape_string($_POST['e_department']);
if($stmt = $conn->conn->prepare("UPDATE employee SET firstname = ? WHERE id = ?"))
{
$stmt->bind_param('si', $first_name, $e_id);
$stmt->execute();
echo $stmt->affected_rows;
}
$conn->conn->close();
?>

PDO Insert not working (PHP/MySQL)

After days of trial and error, I finally replaced my standard mysql code with PDO. Everything seems to be working just fine except for the last part where the app needs to INSERT user (name, email and time of signup) into database. After clicking submit, page just turns blank.
I don't see what is wrong with the code, so I would appreciate if you could help me out.
<?php
////Database connection values
$dsn = 'mysql:host=host; dbname=name; charset=utf8';
$db_user = 'username';
$db_pass = 'password';
//Database connection
$db = new PDO($dsn, $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Enable Exception error mode
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // Use PDO safely = Turn off prepare emulation
// Databse connection check
if($db){
print "connected to the db " . "<br />";
}
//Declare values
$name = "";
$email = "";
$userMsg = "";
if ($_POST['name'] != "") {
$name = $_POST['name'];
$email = $_POST['email'];
//MySQL SELECT Query
$stmt = $db -> prepare ("SELECT * FROM newsletter WHERE email=?");
$stmt-> bindValue(1, $email);
$stmt -> execute ();
//Error - No email
if (!$email) {
$userMsg = '<br /><br /><h4><font color="FF0000">Please type an email address ' . $name . '.</font></h4>';
} // End email-input check
//Error - Email already in the system
else if ($stmt -> rowCount() > 0) {
$userMsg = '<br /><br /><h4><font color="FF0000">' . $email . ' is already in the system.</font></h4>';
} // End Row check
//OK - insert user into database
else {
$insert = $db -> prepare ("INSERT INTO newsletter (name, email, dateTime) VALUES(:name, :email, ,NOW())");
$insert -> execute(array(':name' => $name, ':email' => $email));
//Success! - Notify user
$userMsg = '<br /><br /><h4><font color="0066FF">Thanks ' . $name . ', you have been added successfully.</font></h4>';
$name = "";
$email = "";
} // End INSERT
}
?>
VALUES(:name, :email, ,NOW())"
should be
VALUES(:name, :email, NOW())"

MySql PHP Update Error

I've been messing about with this code for a few hours now and can't work out why it's not working. It's a profile update php page that is passed through JQuery and all seems to be fine except for it actually updating into the table. Here is the code I'm using:
session_start();
include("db-connect.php");//Contains $con
$get_user_sql = "SELECT * FROM members WHERE username = '$user_username'";
$get_user_res = mysqli_query($con, $get_user_sql);
while($user = mysqli_fetch_array($get_user_res)){
$user_id = $user['id'];
}
$name = mysqli_real_escape_string($con, $_REQUEST["name"]);
$location = mysqli_real_escape_string($con, $_REQUEST["location"]);
$about = mysqli_real_escape_string($con, $_REQUEST["about"]);
$insert_member_sql = "UPDATE profile_members SET id = '$user_id', names = '$name', location = '$location', about = '$about' WHERE id = '$user_id'";
$insert_member_res = mysqli_query($con, $insert_member_sql) or die(mysqli_error($con));
if(mysqli_affected_rows($con)>0){
echo "1";
}else{
echo "0";
}
All I get as the return value is 0, can anybody spot any potential mistakes? Thanks
To begin with, use
require("db-connect.php");
instead of
include("db-connect.php");
And now, consider using prepared statements, your code is vulnerable to sql injections.
Consider using PDO instead of the mysql syntax, in the long run I find it much better to use and it avoids a lot of non-sense-making problems, you can do it like this (You can keep it in the db-connect file if you want, and even make the database conncetion become global):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host, $databaseName, $user, $pass);
Now, here's how you can solve your problem (Using prepared statements, avoiding sql injection):
function userId($db, $user_username)
{
$query = "SELECT * FROM members WHERE username = :username;";
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(
':username' => $user_username
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['user_id'];
}
return false
}
function updateProfile($db, $userId, $name, $location, $about)
{
$query = "UPDATE profile_members SET name = :name, location = :location, about = :about WHERE id = :userId;";
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':userId' => $userId,
':name' => $name,
':location' => $location,
':about' => $about
));
if($result)
{
return true;
}
return false
}
$userId = userId($db, $user_username); // Consider if it is not false.
$name = $_REQUEST["name"];
$location = $_REQUEST["location"];
$about = $_REQUEST["about"];
$updated = updateProfile($db, $userId, $name, $location, $about);
You should check the queries though, I fixed them a little bit but not 100% sure if they work.
You can easily make another function which inserts into tha database, instead of updating it, or keeping it in the same function; if you find an existance of the entry, then you insert it, otherwise you update it.

Convert php code with Mysql ext to PDO won't work

I have decided for security to convert my simple php with mysql code to PDO,since it will tighten my security.My old code:
$host = "localhost";
$user = "username";
$pass = "pass";
$database = "mydatabase";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$name=$_POST['name'];
$message=$_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$query="INSERT INTO table (date_time, name, message,ip) VALUES (NOW(),'$name','$message','$ip')";
If (mysql_query($query,$linkID)){
//Success
}else{
//Failure
}
My new code is:
$hostname = 'localhost';
$username = 'username';
$password = 'pass';
$dbname = 'mydatabase';
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
if($_POST['name'] && $_POST['message']) {
$name = $_POST['name'];
$message = $_POST['message'];
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO table (date_time, name, message,ip)VALUES (NOW(), :name, :message,'$ip')";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':message', $message, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "OK";
}
}
It's very strange that when i point my browser to index.php?name=someName&message=someMessage my PDO code won't echo a single thing(even echo "ok" ) or an error so i can fugure out where is the problem.
I can confirm that no data is inserted to the database.
I've even added try catch but nothing changed. My php is supporting PDO and the simple Mysql code is working.
Any ideas? Thanks
In your case,
if($_POST['name'] && $_POST['message']) {
Should be:
if($_GET['name'] && $_GET['message']) {

Categories