What I'm trying to do is make a username (just username) get sent to a MySQL database, if it isn't already there.
Basically, I'm getting the input, checking it against all other rows in my username column, and, if the input is not the same as any of them, then add the input to the database. Here is my code:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if( isset( $_POST["submit"] ) ) {
$sql="INSERT INTO users (username)
VALUES('$_POST[username]')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["username"] == $_POST[username]) {
die("Username is already in use!");
}
}
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
die("Error, please consult an admin: " . $sql . "<br>" . $conn->error);
}
$conn->close();
No error is reported, but it simply creates the data twice, and doesn't check the input. I can't see how. This is how I've tried. It looks logical that is should work, but it's not. Why?
I'm using MySqli Object-Orientated
Try this code...
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if( isset( $_POST["submit"] ) ) {
$sql="INSERT IGNORE INTO users (username)
VALUES('$_POST[username]')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["username"] == $_POST[username]) {
die("Username is already in use!");
}
}
echo "New record created successfully";
}else {
die("Error, please consult an admin: " . $sql . "<br>" . $conn->error);
}
$conn->close();
You are executing the $conn->query($sql) twice. The first one is in $result = $conn->query($sql); and the second if ($conn->query($sql) === TRUE). That is why you get 2 entries in the for one request.
First check for the user you are prepering to insert and if it returns 0 statements then go with the second if you have wrote.
Edit 2:
Try use PDO:
The code will look something like this:
if( isset( $_POST["submit"] ) ) {
$stmt = $pdo->prepare("SELECT username FROM users WHERE username LIKE ?");
$stmt->execute( array( $_POST["username"] ) );
$_results = $stmt->get_result();
if( count( $_results ) > 0 ) {
die("Error, please consult an admin!");
} else {
$stmt = $pdo->prepare('INSERT INTO users (username) VALUES( ? )' );
$stmt->bindParam( 1, $_POST['username'] );
if( $stmt->execute() ) {
echo 'Success';
} else {
echo 'Whoops, you have an error mate!';
}
}
}
Hope it helps
Related
I'm trying to create an upvote system where, after checking to see if you're logged in and after getting your userid, it checks if the table has your userid with the postid already in it and if it does then it means it was already upvoted. I just want to know what's wrong in my code, this is being used for learning, I don't need any complex thing.
Code:
if (isset($_GET['upvote'])) {
if ($_SESSION["loggedin"] == true) {
$upvoteid = $_GET["upvote"];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM users WHERE username=".$_SESSION["loggedinusername"];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$userid = $row["id"];
}
$sql2 = "SELECT userid, postid FROM upvotedposts WHERE userid='".$userid."' AND postid='".$upvoteid."'";
$result2 = $conn->query($sql);
if (!$result2->numrows > 0) {
$sql = "UPDATE posts SET upvotes = upvotes + 1 WHERE id = ".$upvoteid;
if ($conn->query($sql) === TRUE) {
echo "Sucessfully upvoted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
} else {
echo "Failed;
}
$conn->close();
}
}
When I do click the upvote button, it simply does nothing. The issue here is that as far as I know it looks like it would work but I may be forgetting something that I am unaware of or incorrectly using something.
You are missing a closing "
echo "Failed;
should be:
echo "Failed";
I have a search form that is able to retrieve the username of a user, however I can't figure out how to get it to return more than that, I want it to display the first names and last names too.
Below is the code at the minute that works, but when I try and add in more variables, for example if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?")) then it doesn't return anything at all and asks to insert a search query.
I have also tried if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE %?%")) and LIKE "%?%")), but no results.
search.php
<?php
include 'connection.php';
if(isset($_POST['searchsubmit']))
{
include 'searchform.php';
$name=$_POST['name'];
if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?"))
{
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($personresult);
$stmt->fetch();
?>
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2>
<BR>
<?php
print_r($personresult);
?>
</center>
<?php
}
else
{
echo "<p>Please enter a search query</p>";
}
}
else
{
echo "NOT SET!";
}
You are only calling Username .. You need to be calling *
SELECT * FROM users WHERE Username LIKE ?
This is my personal script I use:
<?php
$dbservername = "localhost";
$dbusername = "db_user";
$dbpassword = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!empty($_POST["username"])) {
$username = $_POST["username"];
}
if (!empty($_POST["password"])) {
$password = $_POST["password"];
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row["Username"] . " " . $row["Firstname"] . " " . $row["Lastname"] . "<br>";
if ($row["Username"] == $username && $row["Password"] == $password) {
echo "success";
// do more stuff here like set session etc
} else {
$echo "incorrect username and/or password";
}
}
}
?>
Are you initializing the statement object with mysqli_stmt_init?
See mysqli_stmt_init and mysqli-stmt.prepare
If the database server cannot successfully prepare the statement,
PDO::prepare() returns FALSE or emits PDOException (depending on error
handling)
add this line in connection.php right after creating connection object:
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
At least, you can trace possible errors
<?php
include 'connection.php';
if( isset( $_POST['searchsubmit'] ) ) {
include 'searchform.php';
$name=$_POST['name'];
if ( $stmt = $connection->prepare ("SELECT `Username`,`firstname`,`lastname` FROM `users` WHERE `Username` LIKE ?") ) {
/* not 100% sure about whether this is required here like this or not but usually a like expression uses '%' as a wildcard */
$var='%'.$name'.%';
$stmt->bind_param('s', $var );
$res=$stmt->execute();
/* 3 columns selected in query, 3 columns bound in results */
$stmt->bind_result( $personresult, $firstname, $lastname );
if( $res ){
$stmt->fetch();
echo "
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2><!-- 3 columns/variables -->
{$personresult},{$firstname},{$lastname}
<BR>
</center>";
}
} else {
echo "<p>Please enter a search query</p>";
}
} else {
echo "NOT SET!";
}
$stmt->close();
$connection->close();
?>
i have been trying to get this script done for a while now - im kind of new to php and mysql but i have been trying to get this to check the db for the username and then if the username exists - stop checking the db and if it doesn't exists add it to the db.
here is my code:
//input from application
$test = "wheelsmanx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT mainusername FROM CCCpro_test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["mainusername"] === $test) {
echo "User Name Already In Use.";
}if($row["mainusername"] !== $test){
echo "this statement";
[code that inserts into db i can do this part myself]
}
}
$conn->close();
} else {
echo "0 results";
}
$conn->close();
The problem with your code is that you do the INSERT of the new name inside an if statement that has confirmed the existence of that user already. In addition I think you messed up your SELECT statement by selecting all the users.
Look into INSERT ON DUPLICATE for a better way to do it, or revise your code as below.
$sql = "SELECT mainusername FROM CCCpro_test WHERE mainusername = $test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "User Name Already In Use.";
}
else{ //no rows selected therefore the user doesn't exist
[code that inserts into db i can do this part myself]
}
$conn->close();
PLEASE READ I have somewhere to go so I am being lazy so I did not bind the $test variable therefore DO NOT copy and paste this code without updating it to bind the $test variable. Please read this post about PDO and variable binding to prevent SQL injection.
here is my full working code if anyone needs it - it uses the post method - from an html form .... in case some one needs to hack it to pieces for something else
well guys i appreciate all of your help :D but i have found an answer or a way around it i suppose- i thought of it all night and day on how i could make it work and i came up with this
$servername = "127.0.0.1";
$username = "TESTUSER";
$password = "TESTPASS";
$dbname = "TESTDB";
$testusername = $_POST['mainusername'];
$testpassword = $_POST['mainpassword'];
//input from application
$test = $_POST['mainusername'];
$test2 = "0";
//Count switch
$countswitch = "0";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "INSERT INTO CCCpro_test ( mainusername, mainpassword ) VALUES ('$testusername','$testpassword' )";
$sql = "SELECT mainusername FROM CCCpro_test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["mainusername"] === $test) {
echo "Im Sorry Username Already In Use";
$countswitch ++;
}
}
if($countswitch == $test2){
echo "User Name Registered";
$db_handle = mysql_connect($servername, $username, $password);
$db_found = mysql_select_db($dbname, $db_handle);
if ($db_found) {
$result1 = mysql_query($sql1);
mysql_close($db_handle);
}
}
if ($countswitch == 3){
echo "this";
}
} else {
echo "0 results";
}
$conn->close();
I am doing an update of values inside a MySQL database using PHP
and here is my code to update
$id = $_REQUEST['uid'];
$name = $_REQUEST['name'];
$company = $_REQUEST['company'];
$contact = $_REQUEST['contact'];
$email = $_REQUEST['email'];
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
echo "$id "."$name". "$company" . "$contact" . "$email";
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
$sql = "UPDATE `users` SET `userName`='$name',`userEmail`='$email',`userCompany`='$company',`userContact`='$contact' WHERE userID = $id";
if (mysqli_query($conn, $sql))
{
mysqli_commit($conn);
echo "success";
}
else
{
echo "error";
}
}
mysqli_close($conn);
it does the update and changes the value in the db.
But when I login using the previous username and password, it still accepts it
code for login
$uname= $_REQUEST['loginusername'];
$pword= $_REQUEST['loginpassword'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else
{
$sql = "SELECT * FROM `users` WHERE userName = '$uname' AND userPassword = '$pword'";
$return = mysqli_query($conn, $sql);
if(mysqli_num_rows($return) > 0)
{
echo 'found';
}
else
{
echo 'not found';
}
}
$conn->close();
thanks in advance
You don't update your Password field in
UPDATE `users` SET `userName`='$name',`userEmail`='$email',`userCompany`='$company',`userContact`='$contact' WHERE userID = $id
and it isn't a good practice to save clear text passwords. Its better to hash it with an hash algorithm (for example sha256) and salt it.
I have the following error, and this is the exact same form processing file I use for registering a user, but I changed it for the appropriate table and columns. While the reg works fine every time.
Here is the code where the error is located:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
Here is the full code:
<?php
$servername = "localhost";
$username = "root";
$password = "Af2vaz93j68";
$dbname = "pdo_ret";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$eventname = $_POST['eventname'];
$about = $_POST['about'];
$website = $_POST['website'];
if($eventname == '') {
$errmsg_arr[] = 'You must enter your Email';
$errflag = true;
}
if($about == '') {
$errmsg_arr[] = 'You must enter your Password';
$errflag = true;
}
if($website == '') {
$errmsg_arr[] = 'You must enter First Name';
$errflag = true;
}
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Youre confusing PDO and mysqli. mysqli does not support named parameters so you stmt is not compiling and Mysqli::prepare is returning false. Additionally mysqli does not support passing the param to be bound through mysqli_stmt::execute so even if you switch to positional placeholders your execute will fail.
This is what you would need for mysqli:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
// check to make sure the statement was prepared without error
if ($stmt) {
// the statement is good - proceed
$stmt->bind_param('sss', $eventname, $about, $website);
$stmt->execute();
}
Additionally this makes no sense at all:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This will just run the same query again either inserting a second row of the exact same data, or perhaps creating a duplicate key error depending upon your schema.
If you want to test that the previous query succeeded you would do something like:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
if ($stmt) {
$stmt->bind_param('sss', $eventname, $about, $website);
$success = $stmt->execute();
} else {
$success = false;
}
if ($success === true) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
If you want to use PDO (which i prefer and usually recommend) your code would look something like this:
$conn = PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
echo "New record created successfully";
} catch (PDOException $e) {
echo "Error: " . $sql . "<br>" . $e->getMessage();
}