I'm using MAMP Server to host a MySQL database to store some information about user accounts.
When I try to insert an entry using the code given by PHPMyAdmin, it won't insert it. Could somebody please tell me what's wrong with my code?
<?php
$username = "username";
$password = "*******";
$hostname = "localhost:8889";
$inputUsername = $_POST["username"];
$inputPassword = $_POST["password"];
$confirmPassword = $_POST["confirmPassword"];
if ($inputPassword != $confirmPassword) {
die("Your two password entries are not the same!");
}
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$sql = mysql_select_db("billet",$dbhandle)
or die("Could not select database");
$sql = mysql_query("INSERT INTO `billet` (`username`, `password' VALUES ('$inputUsername', '$inputPassword')");
echo "Inserted values! <a href='index.html'>Go</a>";
mysql_close($dbhandle);
?>
You need to query the database to insert the data that you want, currently you are just connecting to the database and then closing.
You will need to do something like this (depending on your MySQL table) :
$result = mysql_query("INSERT INTO `billet` (`username`, `password`) VALUES ('$inputUsername', '$inputPassword')");
You should also think about switching to PDO as mysql_ functions are deprecated.
Related
I cannot figure out why the parameter from the value are not saving on the MySQL database. My connection string is working (config.php). But on MySQL database, it is 000-00-00 or 0.000000 The data are not saving. What do you think is the problem here?
This is my URL parameter: http://crbphil-001-site1.1tempurl.com/adddata.php?
addday=2017/10/04&addhour=01:31:00&addlati=14.779623&addlongti=120.993705
adddata.php
<?php
//Connect to MySQL
include("config.php");
//Prepare Query
$query = "INSERT INTO track (tr_date, tr_time, latitude, longitude) VALUES ('".urlencode($_GET["addday"])."','".urlencode($_GET["addhour"])."','".urlencode($_GET["addlati"])."','".urlencode($_GET["addlongti"])."')";
//Execute Query
mysqli_query($connect, $query);
?>
config.php
<?php
$username = "a2a8e2_itrack"; //mysql username
$password = "******"; //mysql password
$servername="mysql****.hostbuddy.com";
$dbname = "db_a2a8e2_itrack";
$connect = mysqli_connect($servername, $username, $password, $dbname);
$selected = mysqli_select_db($connect, $dbname);
?>
You are using urlencode which is changing the format of the data.
For example, you are passing addday=2017/10/04 BUT
urlencode($_GET["addday"] gives 2017%2F10%2F04
Simply remove urlencode and use just $_GET.
So your insert query becomes this :
$query = "INSERT INTO track (tr_date, tr_time, latitude, longitude)
VALUES ('".$_GET["addday"]."', '".$_GET["addhour"]."', '".$_GET["addlati"]."', '".$_GET["addlongti"]."')";
Below is the code I have in my Sublime, but the database isn't being called.
<?php$username="root";
$password="changedpassword";$database="User";
$field1-name=$_POST['name'];
$field2-name=$_POST['password'];
$field3-name=$_POST['email'];
$field4-name=$_POST['sex'];
$field5-name=$_POST['school'];
$field6-name=$_POST['birth'];
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO create_user (name, password, email, sex, school, birth) VALUES('','$field1-name','$field2-name',
'$field3-name','$field4-name','$field5-name','$field6-name')";mysql_query($query);mysql_close();?>
Let's go through this step by step. First, here's your current code, tidied up to be readable:
<?php
$username = "root";
$password = "changedpassword";
$database = "User";
$field1_name = $_POST['name'];
$field2_name = $_POST['password'];
$field3_name = $_POST['email'];
$field4_name = $_POST['sex'];
$field5_name = $_POST['school'];
$field6_name = $_POST['birth'];
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die("Unable to select database");
$query = "
INSERT INTO
create_user
(
name,
password,
email,
sex,
school,
birth
)
VALUES
(
'',
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
";
mysql_query($query);
mysql_close();
?>
I've made only two changes (tidied the whitespace, and used _name instead of -name, as PHP variables cannot contain hyphens), but it's already a big improvement. The code is no longer an eyesore. It does not have syntax errors, and it is readable. There are still, though, a large number of problems.
First, you see that we are inserting seven values into six columns. This will be a problem. Fix that by removing the first blank value:
$query = "
INSERT INTO
create_user
(
name,
password,
email,
sex,
school,
birth
)
VALUES
(
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
";
Now we have something that might actually work. It's painfully insecure, with massive potential for SQL injection attacks, and it won't work on the latest PHP because the mysql_ functions have been removed, but it might actually kind of work somewhere. You wouldn't want to put it into production, but for test purposes, we're getting somewhere.
MySQL is deprecated since PHP 5.6 and is insecure, use PDO or MySQLi instead.
Connecting with MySQLi
<?php
//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());
$field1_name = $_POST['name'];
$field2_name = $_POST['password'];
$field3_name = $_POST['email'];
$field4_name = $_POST['sex'];
$field5_name = $_POST['school'];
$field6_name = $_POST['birth'];
$query = mysqli_query($connection, "INSERT INTO create_user
(name, password, email, sex, school, birth ) VALUES
(
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
");
Use this and you will be good. I hope this has helped you!
I am getting the error on line 26 as shown by my browser.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "tut";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Database connection failed: ".mysqli_connect_error());
}
if (isset($_POST['register']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$pass2=$_POST['password1'];
if(empty($username)||empty ($password)||empty($password1)){
echo "Oops! Can't leave any field blank";
}
elseif($pass!=$pass2){
echo "Passwords don't match";
}
else{
$phash = sha1(sha1($pass."salt")."salt");
$sql=IF NOT EXISTS (SELECT * FROM users WHERE username = '$user')
INSERT INTO users (id, username, password) VALUES ('', '$user', '$phash')
ELSE
RAISERROR 'Username exists, please select a different one';
$result = mysqli_query($conn, $sql);
}
}
?>
Is this not a correct way of writing the IF NOT EXISTS statement. Also when I try to execute this directly in XAMPP I get Unrecognised SQL statement error!
This is how to do it, I have test it and it works:
$sql = "
INSERT INTO users (username, password)
SELECT * FROM (SELECT '$user', '$phash') AS tmp
WHERE NOT EXISTS (
SELECT username FROM users WHERE username = '$user'
) LIMIT 1;
";
This solution is inspired from this answer.
The problem is that you can not combine PHP and MySQL statement like you did, you need to encapsulate all MySQL statements in quote ".
What comes RAISERROR, it is not MySQL function, it belongs to Microsoft.
You could easily make php if statement that checks if $sql contain valid username and return your message. That part is left to your fantasy.
XAMPP has no thing to do with the error, it just a software that provides an Apache and MySQL installation for Windows.
Note: P.S. please learn to use parameterized queries, because your
code is vulnerable to SQL injection. thanks to #BillKarwin for mentioning this.
First i would like to say thank you for letting me ask questions again. I know my previous question was a bit low level of knowledge. Today, I would like to ask if the principle of converting mysql to mysqli in ajax is same with html. Suppose this is my Connect.php
<?php
$host = "localhost";
$dbusername = "root";
$dbpassword = "765632";
$dbname = "student";
$link_id = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link_id));
?>
and my ajax.php is
<?php
//Connect to MySQL Server
include 'Connect.php';
mysql_connect($host, $dbusername, $dbpassword);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Escape User Input to help prevent SQL Injection
$first_name = mysql_real_escape_string(trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysql_query($query) or die(mysql_error());
//Generate the output
$searchResults = '';
if(!mysql_num_rows($result))
What are the changes should i made to convert it to mysqli without changing its logical scheme.
Did you mean this?
$link_id = mysqli_connect($host, $dbusername, $dbpassword);
//Select Database
mysqli_select_db($link_id, $dbname) or die(mysqli_error($link_id));
// Escape User Input to help prevent SQL Injection
$first_name = mysqli_real_escape_string($link_id, trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysqli_query($link_id, $query) or die(mysqli_error($link_id));
//Generate the output
$searchResults = '';
if(!mysqli_num_rows($result))
im having problems in PHP with selecting Infomation from a database where username is equal to $myusername
I can get it to echo the username using sessions from the login page to the logged in page.
But I want to be able to select things like 'bio' and 'email' from that database and put them into variables called $bio and $email so i can echo them.
This is what the database looks like:
Any ideas?:/
You should connect to your database and then fetch the row like this:
// DATABASE INFORMATION
$server = 'localhost';
$database = 'DATABASE';
$dbuser = 'DATABASE_USERNAME';
$dbpassword = 'DATABASE_PASSWORD';
//CONNECT TO DATABASE
$connect = mysql_connect("$server", "$dbuser", "$dbpassword")
OR die(mysql_error());
mysql_select_db("$database", $connect);
//ALWAYS ESCAPE STRINGS IF YOU HAVE RECEIVED THEM FROM USERS
$safe_username = mysql_real_escape_string($X);
//FIND AND GET THE ROW
$getit = mysql_query("SELECT * FROM table_name WHERE username='$safe_username'", $connect);
$row = mysql_fetch_array($getit);
//YOUR NEEDED VALUES
$bio = $row['bio'];
$email = $row['email'];
Note 1:
Dont Use Plain Text for Passwords, Always hash the passwords with a salt
Note 2:
I used MYSQL_QUERY for your code because i don't know PDO or Mysqli, Escaping in MYSQL is good enought but Consider Using PDO or Mysqli , as i don't know them i can't write the code with them for you
Simplistic PDO examples.
Create a connection to the database.
$link = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Use the $link variable when creating (preparing) and executing your SQL scripts.
$stmt = $link->prepare('insert into `history` (`user_id`) values(:userId)');
$stmt->execute(array(':userId' => $userId));
Code below will read data. Note that this code is only expecting one record (with 2 data elements) to be returned, so I'm storing whatever is returned into a single variable (per data element), $webId and $deviceId.
$stmt = $link->prepare('select `web_id`, `device_id` from `history` where `user_id` = :userId');
$stmt->execute(array(':userId' => $userId));
while($row = $stmt->fetch()) {
$webId = $row["web_id"];
$deviceId = $row["device_id"];
}
From the picture I can see you are using phpMyAdmin - a tool used to handle MySQL databases. You first must make a connection to the MySql server and then select a database to work with. This is shown how below:
<?php
$username = "your_name"; //Change to your server's username
$password = "your_password"; //Change to your server's password
$database = "your_database" //Change to your database name
$hostname = "localhost"; // Change to the location of your server (this will prolly be the same for you I believe tho
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db($database, $dbhandle)
or die("Could not select examples");
?>
Then you can write something like this:
<?php
$bio = mysql_query("SELECT bio FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
and
<?php
$email = mysql_query("SELECT email FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
Where *your_database_table_name* is the table in the database you selected which you are trying to query.
When I was answering your question, I was referencing this site: http://webcheatsheet.com/PHP/connect_mysql_database.php. So it might help to check it out as well.