MySql/PHP data not getting removed - php

<?php
session_start();
//get the location name/address.
$address = $_POST['table'];
$_SESSION['myaddress'] = $address;
$username = $_SESSION['username'];
//connection details.
$sev_host = "localhost";
$sev_username = "root";
$sev_password = "";
$sev_db = "mydata";
//Connecting server with db.
$conn = mysqli_connect($sev_host, $sev_username, $sev_password, $sev_db);
if (!$conn) {
die("Error : " . mysqli_connect_error());
}
//Check if the table exist, and if not then create the table
$pre_check = "select location from users where username='$username";
$result_pre_check = mysqli_query($conn, $pre_check);
$pre_remove = "delete from $result_pre_check where username='$username'";
mysqli_query($conn, $pre_remove);
$pre_insert = "update users set location='$address' where username='$username'";
mysqli_query($conn, $pre_insert);
$sql = "CREATE TABLE $address (id int(6) unsigned auto_increment primary key, username varchar(255) not null, src varchar(255) not null)";
$sql2 = "INSERT INTO $address (id, username, src) VALUES ('', '$username', '')";
mysqli_query($conn, $sql);
mysqli_query($conn, $sql2);
?>
This is my php code, and I seem to have a problem in it. This code is attached to a button and runs when it is clicked, but it's not giving me the required result. As you can see that I am deleting a row on $pre_remove statement, but when the code runs everything works except that the required row is not removed from the table.
The code works fine and it doesn't give out any debug errors. Any ideas?

The reason this doesn't work lies within your query on $pre_remove
A good way to debug your code, would be to use functions like var_dump, print_r etc. to see what your variables actually contains.
In this specific case, the problem lies within delete from $result_pre_check
$result_pre_check is not a variable. Again, you can do a var_dump($result_pre_check) to see what this variable is / contains.
Your query to delete a user based on username would however work if it was:
$pre_remove = "delete from users where username='$username'";

You can try something like this,
$pre_remove = "DELETE FROM users WHERE username IN (
SELECT location FROM users WHERE username='$username'
)";
mysqli_query($conn, $pre_remove);
instead of ,
$pre_check = "select location from users where username='$username";
$result_pre_check = mysqli_query($conn, $pre_check);
$pre_remove = "delete from $result_pre_check where username='$username'";
mysqli_query($conn, $pre_remove);

Related

How to change from simple mysqli query to prepared statement?

I did 3 queries (SELECT, INSERT, UPDATE) it works but at the current state looks ugly and not safe.
Is there any way to make these SELECT, INSERT, UPDATE queries more readable and safer than this with the prepared statement?
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES ('".$_POST["commentID"]."', '".$_POST["comment"]."', '$username', '$id')";
mysqli_query($connect, $sql) or die("ERROR: ". mysqli_error($connect));
/// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$sql1 = "UPDATE user_comments SET id = id +1 WHERE custom_id = '$id'";
mysqli_query($connect, $sql1) or die("ERROR: ". mysqli_error($connect));
Give this a try. You can use $ex->insert_id to get the last entered ID. This may come in handy when mass inserting into a DB. I generally use PDO as I find the code looks cleaner but it's all preference I suppose. Keep in mind for the ->bind_param line that "isii" is referring to the type(s) of data which you are entering. So, in this case, its Integer, String, Integer, Integer (I may have got this wrong).
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$commentID = $_POST["commentID"];
$comment = $_POST["comment"];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES (?, ?, ?, ?)";
$ex = $connect->prepare($sql);
$ex->bind_param("isii", $commentID, $comment, $username, $id);
if($ex->execute()){
// query success
// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$lastInsertID = $ex->insert_id;
$sql1 = "UPDATE user_comments SET id = id + 1 WHERE custom_id = ?";
$ex1 = $connect->prepare($sql1);
$ex1->bind_param("i",$lastInsertID);
if($ex1->execute()){
// query success
}else{
// query failed
error_log($connect->error);
}
}else{
//query failed
error_log($connect->error);
}

Unable to post to a database MySQL

I am attempting to post a column into my database here as a test and I am unable to do so. I've used the code below and it doesn't seem to be posting. Unless I am missing a trick with PHPmyAdmin I cannot seem to get it working. Any chance anyone could help? Thanks in advance!
<?php
$link = mysqli_connect("XXXX", "XXXX",
"XXXX", "XXXX");
if (mysqli_connect_error ()) {
die("The connection has failed");
}
$query = "INSERT INTO `users` (`email`, `password`)
VALUES('owen#owen.com', 'hfudhf8ahdfufh')";
mysqli_query($link, $query);
$query = "SELECT * FROM users";
if($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
echo"Your Email is ".$row["email"];
echo" and your Password is ".$row["password"];
}
?>
The problem is that you're only fetching one row of results. Unless the table was empty before you ran the script, there's no reason to expect that row to be the one that you just added.
If the table has an auto-increment ID field, you can fetch that row:
$query = "SELECT * FROM users WHERE id = LAST_INSERT_ID()";

Turn SQL value to variable

so I have a database table with some user information, like ID, username, etc. and I have been trying to turn a value, for example, Bob's ID into a variable $id from the table. This is what I have right now:
$db = mysqli_connect(THIS WORKS FINE AND CONTAINS SECRET INFO :));
$sql = "SELECT ID FROM users WHERE username='$prompt'";
$result = mysqli_query($db, $sql);
and I need to turn it into a variable, because I am combining everything into a sentence so it could be $username has the id of $id. Thanks
Try like this.use sprintf().The sprintf() function writes a formatted string to a variable.
$db = mysqli_connect(THIS WORKS FINE AND CONTAINS SECRET INFO :));
$sql = "SELECT ID,username FROM users WHERE username='$prompt'";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
$sentence = sprintf("%s has the id of %u.",$row['username'],$row['ID']);
echo $sentence;
For more see sprintf

MySqli not working correctly

My goal is to recieve 2 strings, an IP and UUID, and look in the database. If the UUID is already there, it adds the IP onto a list of IPs in the database. If not, it makes a new row in the database with that UUID and IP. Purpose is tracking user activity (Nothing malicious)
Code:
<?php
$cip = $_POST['ipaddr'];
$cid = $_POST['id'];
$conn = mysqli_connect('localhost', '*****', '*****', '*****');
$query = mysqli_query($conn, "SELECT * FROM sls WHERE asid='".$cid."'");
if(mysqli_num_rows($query) > 0){
$sql = "SELECT asid, ips FROM sls WHERE asid=$cid";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$cipdata = $row["ips"];
}
$sql = "UPDATE sls SET ips='$cipdata , $cip' WHERE id=2";
mysqli_query($conn, $sql);
} else {
$sql = "INSERT INTO sls (asid, ips) VALUES ('$cid', '$cip')";
mysqli_query($conn, $sql);
}
?>
Right now, it just adds a new row for every IP, regardless of UUID.
What did I do wrong?
-- Edit: Fixed typo, now it just adds the first IP, but after that does not add any more to the row.
Perhaps there is a small typo on this line:
$query = mysqli_query($con, "SELECT * FROM sls WHERE asid='".$cid."'");
Did you mean $conn, not $con? As in:
$query = mysqli_query($conn, "SELECT * FROM sls WHERE asid='".$cid."'");
Your connection param is $conn so just used this in every query command. some where you are using $con and somewhere $conn.
Check your code.

MySQL Value as PHP Session

I have a registration script where the user id is saved as a session variable after registration and the user is redirected to their homepage. For some reason the user id is not being stored in the session variable. This exact same script worked on a different project, I simply took the project and changed the database connection settings and now it's not working.
Here is the registration script:
mysqli_connect($db_host, $db_user, $db_pass) OR DIE (mysqli_error());
// select the db
mysqli_select_db ($link, $db_name) OR DIE ("Unable to select db".mysqli_error($db_name));
// our sql query
$sql = "INSERT INTO seekers (first_name, last_name, username, email, password, salt) VALUES ('$firstName', '$lastName', '$username', '$email', '$hashedPW', '$salt');";
//save the updated information to the database
$result = mysqli_query($link, $sql) or die("Error in Query: " . mysqli_error($link));
if (!mysqli_error($link)) {
$row = mysqli_fetch_assoc($result);
$_SESSION['user_id'] = mysqli_insert_id($link);
$_SESSION['loggedin'] = TRUE;
header("Location: ../index.php");
}
And here is the session checking and db query on the protected page:
session_start();
if(isset($_SESSION['loggedin']) && $_SESSION['user_id'] != 'user_id') {
include_once('includes/user.header.php');
//set user_id
$user_id = $_SESSION['user_id'];
//include the logged in user header
include_once('includes/user.header.php');
//select user information according to their logged in user_id
$sql = $link->query('SELECT * FROM seekers WHERE id = "'.$user_id.'"');
$row = mysqli_fetch_assoc($sql);
//create piece name together
$firstName = $link->real_escape_string($row['first_name']);
$lastName = $link->real_escape_string($row['last_name']);
$fullName = $firstName. " " .$lastName;
//get username
$username = $link->real_escape_string($row['username']);
When I am redirected to the index.php page, everything looks fine, except none of the user information is being queried from the DB.
Can anyone see what is wrong here? I know it's got to be something little and I'm just over looking it.
Please any help would be greatly appreciated.
EDIT: All information is being stored in the database successfully as well.
You are trying to use user_id without a select query ... indeed you must get the last insert id
changed line ;
$_SESSION["user_id"]=mysql_insert_id();
and
if (!mysqli_error($link))
should be
if (!mysqli_error($result))
and
$sql = $link->query('SELECT * FROM seekers WHERE id = "'.$user_id.'"');
to
$sql = $link->query('SELECT * FROM seekers WHERE user_id = "'.$user_id.'"');

Categories