I've looked at some of the other answers on here regarding this but I keep getting errors so here goes.
Whenver a user visits the site, they are asked to provide their name and are assigned a random integer. When they hit submit to enter their name the form gets submitted and saved to the database and the user gets redirected back to the main page. If the random number once again matches a number saved in the database, that name gets displayed.
I have no problem inserting values into the database but I am having some issues retrieving them back out.
My connection to the database is fine, just left the values generic for the purpose of this question.
<?php
$min=1;
$max=100;
$rand_number = rand($min,$max);
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
//Set PDO Error Mode to Exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL
$stmt = $conn->prepare("select nickname from users where number=".$rand_number);
$stmt->execute();
if (!$stmt) {
foreach($result as $row) {
echo $row['nickname'];
}
}
}
?>
I'm getting an error that something is wrong around the part where I'm matching the query to the variable.
The only thing I really see missing is where you would fetch the data. You can either use one of the fetch* methods of PDOStatement or simply iterate the statement itself (it implements Traversable).
Also, you should use parameter binding.
$stmt = $conn->prepare('SELECT `nickname` FROM `users` WHERE `number` = ?');
$stmt->execute([$rand_number]);
while($nickname = $stmt->fetchColumn()) {
echo $nickname;
}
Related
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 2 years ago.
I am creating a very simple registration form in php, currently when the user tries to register there will popup a javascript alert with a succes or fail message.
Now I want to catch the sql exception to show if the username or email already excists in the database instead of a standard fail message.
This is the code I have so far:
if(isset($_POST['btn-signup']))
{
$uname = mysql_real_escape_string($_POST['uname']);
$email = mysql_real_escape_string($_POST['email']);
$upass = md5(mysql_real_escape_string($_POST['pass']));
if(mysql_query("INSERT INTO user(username,password,email) VALUES('$uname','$upass','$email')"))
{
?>
<script>alert('successfully registered ');</script>
<?php
}
else{
?>
<script>alert('error while registering you...');</script>
<?php
}
}
?>
How can I check if the email or username already excists in the database? Both variable's are already unique in the database.
From Comments:
I don't want 2 queries while the database can return an exception for me. If there are about 10 million records in that table, I don't want to check them all before inserting a new one.
Ok, so you have one query to insert and check is unique? So you have to INSERT on a UNIQUE_INDEX MySQL column, you can catch these sort of exceptions with the following style of answer shameless stolen from this answer to this question:
In the case of this answer we'll assume you're using PDO, because you should. Please read up about it.
// Pre-setup the database connection somewhere, usually an include (or a class)
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbusername,$dbpassword);
// PDO needs to be set in Exception mode:
$link->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Input Processing functions.
// (entirely optional)
$uname = MyCleanerFunction($_POST['uname']);
$email = MyCleanerFunction($_POST['email']);
//please see note below re:MD5
//$upass = md5($_POST['pass']);
$options['cost'] = 12;
$upass = password_hash($_POST['pass'],PASSWORD_BCRYPT,$options);
//now reach the code part:
try {
//PDO query execution goes here:
$statement = $link->prepare("INSERT INTO user(username,password,email) VALUES(:uname, :email, :pass)"));
$statement->bindValue(":uname", $uname);
$statement->bindValue(":email", $email);
$statement->bindValue(":pass", $upass);
$statement->execute();
//reaching here everything is ok!
}
catch (\PDOException $e) {
if ($e->errorInfo[1] == 1062) {
// The INSERT query failed due to a key constraint violation.
// THIS means that it failed because the Primary Key
// (the email) appears already in the database table.
}
if($e->errorInfo[1] == 9999){
// possible other IF clauses for other errors in INSERT.
}
}
You would also do well to read up about catching and outputting PDO errors. As well as all about MySQL Unique Key Constraints.
Also very useful alternative viewpoint that you Should not catch PDO exceptions.
Also please note that MD5 is an extremely weak hash for storing passwords and that PHP password_hash function is the much preferred way of doing it.
PLEASE use Prepared Statements for your MySQL interactions, the layout above is a rough guide to how they look and is very similar for MySQLi and PDO. Prepared Statements go a long way towards securing your data from malicious user input.
$con=mysqli_connect("localhost","root","","my_db");
$check="SELECT COUNT(*) FROM persons WHERE Email = '$_POST[eMailTxt]'";
if (mysqli_query($con,$check)>=1)
{
echo "User Already in Exists<br/>";
}
else
{
$newUser="INSERT INTO persons(Email,FirstName,LastName,PassWord) values('$_POST[eMailTxt]','$_POST[NameTxt]','$_POST[LnameTxt]','$_POST[passWordTxt]')";
if (mysqli_query($con,$newUser))
{
echo "You are now registered<br/>";
}
else
{
echo "Error adding user in database<br/>";
}
}
When I send my content from my frontend it successfully reaches my if (!empty)-statement but the table in my phpmyadmin/mysql-database does not recieve the information and does not add it.
I have two tables. One varchar (text) named "photo" and a ID called "id" which is A_I.
With my current code I only send (well attempt to send) the text about "photo" but nothing about the ID as it is A_I? Maybe I need to add some addiotional code to that as well and that might be the issue here and the reason the database does not seem to add the content that I send?
<?php
$value = json_decode(file_get_contents('php://input'));
$mysql_pekare= new mysqli ("", "","", "");
if(!empty($value)) {
echo "You reached the IF-statement";
$stmt = $mysql_pekare->prepare("INSERT INTO photoAlbum(`photo`) VALUES(?)");
$stmt->bind_param("s", $value['photo']);
$stmt->execute();
$stmt->close();
$mysql_pekare->close();
}
?>
In my frontend when I send the content I recieve this in the log:
{"photo":"test"}
And I also recieve this in the log, the echo call I did if it reaches the IF function which it successfully does:
"You reached the IF-statement"
By default, json_decode() returns an object, so your value is in $value->photo.
So your INSERT code should be -
if(!empty($value)) {
echo "You reached the IF-statement";
$stmt = $mysql_pekare->prepare("INSERT INTO photoAlbum(`photo`) VALUES(?)");
$stmt->bind_param("s", $value->photo);
$stmt->execute();
$stmt->close();
$mysql_pekare->close();
}
you must put the value for mysqli constructor required like localhost or ip , username of database , password of your database and database name then it will work fine for Example:-
$mysql_pekare=new mysqli ("localhost", "username","password", "databasename");
I'm making a luck based website and I want to make sure they have enough spins on their account before they spin.
I did see http://www.w3schools.com/php/php_mysql_select.asp but its not really what I'm looking for.
I have these rows with the names: id username email password spins.
I can deduct amounts from spins but I can't put the exact amount of their spins on a PHP variable to put in a $SESSION for a different page.
Here's how much I have so far.
$numSpin = "SELECT * FROM $tbl_name WHERE spins";
Then put it in a $SESSION
$_SESSION['spinNum'] = $numSpin;
How would I go on to doing this? This does not work as is.
It seems as if you are extremely new to coding so I'll try to help you out.
Here is the code you can use and I'll explain below.
<?php
session_start();
$host = 'localhost'; $db = 'db-name'; $user = 'db-user'; $pw = 'db-pwd';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$tbl_name = 'table-name-here';
$un = $username;
$sql = "SELECT * FROM $tbl_name WHERE username=:un";
$query = $conn->prepare($sql);
$query->bindValue(':un', $un, PDO::PARAM_STR);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die("Could not get the data: " . $e->getMessage());
}
$_SESSION['spinNum'] = $row['name-of-your-field-with-spin-numbers'];
?>
Then...
if($_SESSION['spinNum'] >= 1) {
// allow them to do something
} else {
echo "I'm sorry. It looks like you don't have any spins left. Please try again later.";
}
This code is written using pdo_mysql. You might want to read up on it here.
Line 2 starts your session
Lines 3-5 creates a connection to your database. Make sure to replace "db-name", "db-user" & "db-pwd" with your information.
On line 8 replace "table-name-here" with your database table name
On line 9 you can set "10" to whatever minimum number you want to make sure the account holder has.
On line 19 change "name-of-your-field-with-spin-numbers" to the actual name of the field in your database table that stores the account users available spins.
Now you can use $_SESSION['spinNum'] on your other pages.
Don't forget to use session_start(); at the top of any page where you want to use session variables.
I'm trying to check for an existing entry in MySQL before executing the INSERT statement. If the user enters a name already in the database (field is set to unique) then they should be prompted to re-enter the name.
The problem I'm having is that if the new entry matches a record in any form then the error message displays and no INSERT happens.
For example, if the user enters DUMMY_NEW and there is a record DUMMY_OLD they aren't able to add the record even though DUMMY_NEW does not exist in the table.
I've searched and tried other answers already but can't seem to get this to work.
Code with extraneous bits removed for clarity:
//Create connection to database using mysqli
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
//Set variables according to user input on previous form
$Server_Name = $_POST['Server_Name'];
//Check for duplicate server name - if exists inform user else run INSERT ($stmt)
$checkdup = "SELECT * FROM dcr_table WHERE SERVER_NAME = '".$Server_Name."'";
$dupresult = $conn->query($checkdup);
if($dupresult = 1)
{
print "<br>Error! <p></p>";
echo "" . $Server_Name . " already exists in the DCR";
print "<p></p>Please check the Server Name and try again";
}
else {
//Define the INSERT statement
$stmt = "INSERT INTO dcr_master (Server_Name, Description,..., ... , ... )";
//Execute the INSERT statement
$conn->query($stmt);
//Success and return new id
echo "<br><p></p>Record Added!<p></p>";
echo "New id: " . mysqli_insert_id($conn);
//Drop the connection
$conn->close();
};
Edit:
I'm aware of the injection vulnerability. The MySQL account only has SELECT, INSERT and UPDATE rights to the table. The end user must supply the password or submit will fail. This is small app with limited user access at the moment. MySQL escape strings will be implemented after current issue is resolved.
Edit 2:
Using Hobo Sapiens method does work in reporting an existing entry however a new (empty) row is still added to the table. The record ID still auto-increments so what I get is id#300 - record, id#301 - blank, id#302 - record. Is this a result of the IGNORE in the INSERT statement?
Your code creates a race condition if two people attempt to create the same ame at the same time and you're not handling the fallout properly.
If you have set the SERVER_NAME column to UNIQUE then you needn't check for the existence of a server name before you perform your INSERT as MySQL will do that for you. Use INSERT IGNORE ad check the number of affected rows after the query has executed to find out if it worked:
//Create connection to database using mysqli
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
//Set variables according to user input on previous form
$Server_Name = $_POST['Server_Name'];
//Define the INSERT statement with IGNORE keyword
$stmt = "INSERT IGNORE INTO dcr_master (Server_Name, Description,..., ... , ... )";
if ($conn->query($stmt) === false) {
die("Database error:".$conn->error);
}
// Check for success
if ($conn->affected_rows == 0) {
print "<br>Error! <p></p>";
echo "" . $Server_Name . " already exists in the DCR";
print "<p></p>Please check the Server Name and try again";
} else {
//Success and return new id
echo "<br><p></p>Record Added!<p></p>";
echo "New id: " . $conn->insert_id;
}
This is an atomic operation so no race condition, and it involves only one call to the database.
I recommend you use either the OOP style or the procedural style for mysqli_*() but don't mix them. Usual warnings about SQL injection apply.
Use mysqli_num_rows
$row_cnt = $dupresult->num_rows;
if ($row_cnt > 0) {
echo "There is a matching record";
}else {
//insert into table
}
This statement:
if($dupresult = 1)
will always return 1. You should first retrieve the first query result (if any), like so:
$row=$dupresult->fetch_array(MYSQLI_NUM);
and then compare the result against NULL:
if(!$row)
I have to following code:
session_start();
if(isset($_SESSION['Username']))
{
//User has selected auto sign-in re-fill session variables.
$mysqli = new mysqli('****','****','****','****');
if($mysqli->errno)
{
//Error connecting
}
else
{
//No error connecting to database
$stmt = $mysqli->prepare("SELECT Expires FROM Subscribers WHERE UName=?");
$stmt->bind_param('s', $_SESSION['Username']);
$stmt->execute();
$stmt->bind_result($Expires);
$stmt->store_result();
while($row = $stmt->fetch())
{
if($Expires < time())
{
//Deny user
$pageToShow = "Payment";
}
else
{
//Accept
$pageToShow = "Content";
}
}
}
}
else
{ ... }
I am getting the error Fatal error: Call to a member function bind_param() on a non-object in /home/content/42/7401242/html/****/wp-content/themes/****/archive.php on line 15
I just had an error like this about 30min ago on a different page, and I had for gotten the FROM from the sql query, but I have read, re-read, re-checked, every single letter of the code, over and over. I am about to pull all of my hair out...
What am I doing wrong?
That's simple.
You're not handling errors.
And not even asking how to do that.
In your other question they showed you error itself instead of showing you the way how can you see the error yourself.
In the present question the answer is "check your query" which is not too helpful too.
Instead of asking other people to find typos in your queries, you have to ask mysqli to do that. That's way more efficient, especially because there could be another mistake, not in the query but somewhere else.
So, you have to check every database interaction result and translate it into PHP error.
$sql = "SELECT Expires FROM Subscribers WHERE UName=?";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error);
...
$stmt->execute() or trigger_error($mysqli->error);
so, you will immediately know what's going wrong.
The error tells you that your SQL query is returning an empty result.
two things you must do:
check that you are connected to the database properly and that you
have the permissions to access the data in the database
check your query and see if it returns any results in your SQL
database.