Converting To MYSQLI - php

I'm working to convert to MYSQLi. something i'm not entirely confident in just yet. I'm getting an error trying to breakdown this portion of my script.
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$level = ($_POST['level']);
// See if that product name is an identical match to another product in the system
include "includes/db_conx.php";
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
$productMatch = mysqli_num_rows($sql); // count the output amount
if ($productMatch > 0) {
header("location: message.php?msg=usererror");
exit();
}
// Add this product into the database now
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['username']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
$email = mysqli_real_escape_string($_POST['email']);
$p_hash = md5($password);
$sql = mysqli_query("INSERT INTO users (username, password, ip, email, level, date_added)
VALUES('$username','$p_hash','$ip','$email','$level',now())") or die (mysql_error());
header("location: order_complete.php");
exit();
}
?>
I believe I've got most of it down, but the second half of this is giving me fits. I'm trying to establish past
// Add this product into the database now
a mysqli conversion. I just can't seem to keep myself from mangling the script and throwing all kinds of errors. I believe I'm about half way there, but introducing select is throwing me off. Can someone help me to figure out this.

You are passing the $sql as a param to mysqli_num_rows() and it should be the result of a mysqli_query().
So change to this.
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
$productMatch = mysqli_num_rows($user_query); // count the output amount
A better name for that variable might be $user_result or something with the word result in.

Check the below mentioned code.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$level = ($_POST['level']);
// See if that product name is an identical match to another product in the system
include "includes/db_conx.php"; // I guess it has $db_conx = mysqli_connect("localhost", "my_user", "my_password", "world");
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
$productMatch = mysqli_num_rows($user_query); // count the output amount
if ($productMatch > 0) {
header("location: message.php?msg=usererror");
exit();
}
// Add this product into the database now
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['username']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
$email = mysqli_real_escape_string($db_conx, $_POST['email']);
$p_hash = md5($password);
$sql = mysqli_query($db_conx, "INSERT INTO users (username, password, ip, email, level, date_added) VALUES('$username','$p_hash','$ip','$email','$level',now())") or die (mysqli_error($db_conx));
header("location: order_complete.php");
exit();
}

Related

Won't Query on the UPDATE part of the program

I'm having a hard time identifying the cause of the problem of my code, which is, it won't query on the "UPDATE" part but the "SELECT" part does work. when i tried using the print_r function, it gives an errors/warnings namely:
"Warning: mysqli_query(): Couldn't fetch mysqli"** and **"Warning:
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null
given"
if(!isset($_POST['n_pass'])&&!isset($_POST['n_pass'])){
if(!isset($_POST['password'])||$_POST['password']==""){
echo 'enter current password';
die;
} else {
include 'include/database.php';
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn,$_POST['lname']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$username = mysqli_real_escape_string($conn,$_POST['uname']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
//Check if the password is equal to the password inside database
$sql = "SELECT password FROM users where id = $id";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$cpass = $row['password'];
$verify_pass = password_verify($password,$cpass); //check if current password is equal to the existing password
if($verify_pass != 1){
echo 'incorrect password';
die;
} else {
**//Update Data
$sql="UPDATE users SET firstname=$fname, lastname=$lname, email=$email, username=$username where id=$id";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
print_r($row['firstname']);
die;
header("Location: profile.php?successfullyupdated");
}
}
}
Your query is missing the quotes around the strings:
$sql="UPDATE users SET firstname='$fname', lastname='$lname', email='$email', username='$username' where id=$id";
You can skip only the id field since it is an Integer.
Sidenote: you are wide open to SQL Injections. You should use prepared statements.
There are plenty of resources on google to start with this topic
Finally, note that
$row = mysqli_fetch_assoc($result);
print_r($row['firstname']);
is completely useless since you are not returning anything from the UPDATE query.
You can do:
if(mysqli_query($conn, $sql)){
//query was successful - run your code here for success
}else{
//query failed - run your code here for fail
}

how to store session value in another table?

I have one login page and its database. i want to take the email from there and store it in another table of the same database. Code is give below please have a look and tell me.
Table 1
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
include 'connection.php';
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 0)
{
echo "Username Password Incorrect";
}
else
{
$_SESSION['email'] = $email;
header("location:home2.php")
}
?>
Table 2
<?php
$email= (HOW TO GET IT FROM SESSION?)
$company = $_POST['company'];
$project = $_POST['project'];
$duration = $_POST['duration'];
$key_learning = $_POST['key_learning'];
include 'connection.php';
$sql = "INSERT INTO `internship`(`id`, `email`, `company`, `project`, `duration`, `key_learning`) VALUES ('', '$email', '$company','$project', '$duration', '$key_learning')";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 1)
{
echo "Fail";
}
else
{
$_SESSION['email'] = $email;
header("location:home3.php");
}
?>
From table 1 i want to take email if using session and want to store it in table 2. How to do it?
$email= (HOW TO GET IT FROM SESSION?)
If the 2nd code block is in the same execution context as the first, you can just use the variable $email that you created.
If you're trying to retrieve data from session as the user navigates to a new page, you do:
<?php
session_start();
$email = isset($_SESSION['email'])? $_SESSION['email'] : null;
By the way, in the 2nd code block you're trying to use mysql_num_rows to analyze the effect of an INSERT query. You can't do that. According to the manual:
[mysql_num_rows] retrieves the number of rows from a result set. This
command is only valid for statements like SELECT or SHOW that return
an actual result set. To retrieve the number of rows affected by a
INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$res = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows()){
//success
}else{
//failure
}
You should not be using mysql_ functions anyway and you should most definitely not be inserting user provided values (username, email, password) directly in your SQL statement

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.

unable to update table specific row

I had been trying many methods to update a specific row in my sql data base named juytdb having table users having colum names username and email. First I tried to connect and connection was successfull,
$localhost = "localhost";
$dbuser = "google";
$dbpass = "";
$dbname = "juytdb";
$connect = mysql_connect($localhost ,$dbuser ,$dbpass);
mysql_select_db($dbname, $connect);
Now while I wanted to update a specific row I used
session_start();
$username = $_SESSION['var']; //acutally users are logged so I just need to add their email
$email = $_POST['email']; //value I got from an inputbox
UPDATE users
SET email='google#gmail.com';
WHERE username='billy';
this does not work, I also tried
$sql = "UPDATE 'users' SET 'email' = '$email' WHERE 'username' = '$username'";
mysql_query($sql);
additionally the default values of email is set to "not added"
You have single quotes where you should have backquotes. Try this:
$sql = "UPDATE `users` SET `email` = '$email' WHERE `username` = '$username'";
Try this:
$sql = "UPDATE users SET email = '".$email."' WHERE username = ".$username;

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