mysqli_num_rows not working in MySQLi with PHP - php

I would like to check if there already exists a record before inserting a new one. But it doesn't work so far, here is the script:
<?php
session_start();
$uname = $_SESSION['username'];
$friend = $_GET["newfriend"];
$db = new mysqli("localhost", "...", "....", "...");
if($db->connect_errno > 0){
die("Unable to connect to database: " . $db->connect_error);
}
$checkexist = $db->query("SELECT * FROM friends WHERE (username_own='$uname', username='$friend')");
//create a prepared statement
$stmt = $db->prepare("INSERT INTO friends (`username_own`, `username`) VALUES (?,?)");
//bind the username and message
$stmt->bind_param('ss', $uname, $friend);
if ($checkexist->mysqli_num_rows == 0) {
//run the query to insert the row
$stmt->execute();
}

Try something like this:
<?php
/* Check if user exists */
$query = "SELECT count(1) FROM friends WHERE username_own=? AND username=?";
if($stmt = $db->prepare($query)){
$stmt->bind_param('ss', $uname, $friend);
$stmt->execute();
$stmt->bind_result($count_rows);
$stmt->fetch();
$stmt->close();
}else die("Failed to prepare");
/* If user doesn't exists, insert */
if($count_row == 0){
$query = "INSERT INTO friends (`username_own`, `username`) VALUES (?,?)";
if($stmt = $db->prepare($query)){
$stmt->bind_param('ss', $uname, $friend);
$stmt->execute();
$stmt->close();
}else die("Failed to prepare!");
}

Try this:
//create a prepared statement
$stmt = $db->prepare("INSERT INTO friends (`username_own`, `username`) VALUES (?,?)");
//bind the username and message
$stmt->bind_param('ss', $uname, $friend);
if ($checkexist->mysqli_num_rows == 0 || $checkexist->mysqli_num_rows <> 0) {
//run the query to insert the row
$stmt->execute();
}

$checkexist->mysqli_num_rows is wrong. It's just
$checkexist->num_rows
or you can use
mysqli_num_rows($checkexist)
Hope this helps.

Replace most of your code with a simple INSERT IGNORE ... or INSERT ... ON DUPLICATE KEY UPDATE ....
The latter lets you change columns if the record already exists (based on any PRIMARY or UNIQUE key(s)).

Related

Join generate Unique ID in username INSERT POST

I have a function to insert username in database, while the database generate unique_id column.
how do i make username get additional suffix, from unique_id column
so it will be looks like this.
username+unique_id
example:John92749
so Input Post Field will add suffix from this column.
below are my function :
//Create user
function addUser($username, $reference_user_id, $user_ip_addr) {
global $conn;
$unique_id = mt_rand(10000,99999);
$stmt = $conn->prepare("SELECT p.id FROM plans p where is_default = 1");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$res = $stmt->fetch();
$stmt = $conn->prepare("INSERT into users (username, plan_id, reference_user_id, ip_addr, unique_id)
VALUES (:un, :pid, :ref_id, :ip_addr, :unique_id)");
$stmt->bindParam(':un', $username);
$stmt->bindParam(':pid', $res['id']);
$stmt->bindParam(':ref_id', $reference_user_id);
$stmt->bindParam(':ip_addr', $user_ip_addr);
$stmt->bindParam(':unique_id', $unique_id);
$stmt->execute();
$uid = $conn->lastInsertId();
$stmt = $conn->prepare("INSERT into user_plan_history (user_id, plan_id,status,created_at) VALUES (:uid, :pid,'active',:date)");
$stmt->bindParam(':date', date('Y-m-d H:i:s'));
$stmt->bindParam(':uid', $uid);
$stmt->bindParam(':pid', $res['id']);
$stmt->execute();
}
You have to merge two variable
like
$uname = $username.''.$unique_id;
Then your code look like :
//Create user
function addUser($username, $reference_user_id, $user_ip_addr) {
global $conn;
$unique_id = mt_rand(10000,99999);
$uname = $username.''.$unique_id;
$stmt = $conn->prepare("SELECT p.id FROM plans p where is_default = 1");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$res = $stmt->fetch();
$stmt = $conn->prepare("INSERT into users (username, plan_id, reference_user_id, ip_addr, unique_id)
VALUES (:un, :pid, :ref_id, :ip_addr, :unique_id)");
$stmt->bindParam(':un', $uname);
$stmt->bindParam(':pid', $res['id']);
$stmt->bindParam(':ref_id', $reference_user_id);
$stmt->bindParam(':ip_addr', $user_ip_addr);
$stmt->bindParam(':unique_id', $unique_id);
$stmt->execute();
$uid = $conn->lastInsertId();
$stmt = $conn->prepare("INSERT into user_plan_history (user_id, plan_id,status,created_at) VALUES (:uid, :pid,'active',:date)");
$stmt->bindParam(':date', date('Y-m-d H:i:s'));
$stmt->bindParam(':uid', $uid);
$stmt->bindParam(':pid', $res['id']);
$stmt->execute();
}
this will give output : John92749
Try this
$username = $username.$unique_id; //Append username and unique_id

How to tell which query had an error? [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
I am trying to convert my mysqli database that was very vulnerable to PDO prepared statements. I think i almost got it since it actully inputs the registration data to the database but not to the other databases. So i think there must be some issues on those queries but i can't figure it out. Here below is my code.
<?php
session_start();
// DATABASE CONNECTION
$user = '****';
$pass = '****';
//CREATE CONNECTION
// $conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
$pdo = new PDO('mysql:host=localhost;dbname=****', $user, $pass);
// ASSIGN VARIABLE FROM FORM
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$password = password_hash($password, PASSWORD_BCRYPT);
// CHECK IF USER IS UNIQUE
$stmt = $pdo->prepare("SELECT username FROM users WHERE username = :name");
$stmt->bindParam(':name', $username);
$stmt->execute();
if ($stmt->rowCount() > 0) {
echo "That username already exist!";
} else {
//INSERT DATA INTO DATABASE
$sql = "INSERT INTO users ( username, password, email )
VALUES ( :username, :password, :email )";
$sql1 = "INSERT INTO stats (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
$sql2 = "INSERT INTO progression (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
$sql3 = "INSERT INTO powervalues (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
// EXECUTE AND PREPARE
$query = $pdo->prepare($sql);
$query1 = $pdo->prepare($sql1);
$query2 = $pdo->prepare($sql2);
$query3 = $pdo->prepare($sql3);
$result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
$result1 = $query1->execute(array( ':username'=>$username ));
$result2 = $query2->execute(array( ':username'=>$username ));
$result3 = $query3->execute(array( ':username'=>$username ));
//EXECUTE QUERY
if ($result && $result1 && $result2 && $result3) {
$_SESSION['Accountsucess'] = "Account has been added sucessfully.";
header("location: ../../index.php?page=index");
} else {
echo "Error database failure";
}
}
Instead of continually selecting various parts of information, once you have inserted the user in the users table, fetch the last insert ID and then use that in subsequent calls...
$sql = "INSERT INTO users ( username, password, email )
VALUES ( :username, :password, :email )";
$sql1 = "INSERT INTO stats (id, username)
VALUES (:id,:username)";
// EXECUTE AND PREPARE
$query = $pdo->prepare($sql);
$query1 = $pdo->prepare($sql1);
$result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
// Fetch id of new user
$id = $pdo->lastInsertId();
$result1 = $query1->execute(array( ':id' => $id, ':username'=>$username ));
Repeat this same logic for each of the other statements.

How to avoid Query doubles INSERT into database?

Problem:
I have made a simple form that uses PHP to pass information to my database via a INSERT query. However, every time I run it, it tries to put the information in twice. How can I avoid this?
Explanation:
I first insert the answers, into my answers table, save the AnswerID as a variable. Then do the save with my question table and lastly I use the two saved variables containing the ID's into my question_answers table.
My code:
if (isset($_POST['textinput1']) && !empty($_POST['textinput1'])) {
$text1 = mysqli_real_escape_string($conn, $_POST['textinput1']);
$text2 = mysqli_real_escape_string($conn, $_POST['textinput2']);
$q_text = mysqli_real_escape_string($conn, $_POST['textarea']);
$stmt = $conn->prepare("INSERT INTO answers (Answer1Text, Answer2Text) VALUES (?, ?)");
$stmt->bind_param('ss', $text1, $text2);
$stmt->execute();
$answerid = $stmt->insert_id;
$stmt = $conn->prepare("INSERT INTO question (QuestionText) VALUES (?)");
$stmt->bind_param('s', $q_text);
$stmt->execute();
$questionid = $stmt->insert_id;
if ($stmt->execute()) {
$stmt = $conn->prepare("INSERT INTO question_answers (AnswerID, QuestionID) VALUES (?, ?)");
$stmt->bind_param('ss', $answerid, $questionid);
$stmt->execute();
echo "<h2>Dit spørgsmål er nu lagt op på siden!</h2>";
echo "<h3>Tusinde tak for din interesse for SMIL - Skodfri Århus.</h3>";
}
else
{
echo "ERROR: Could not able to execute . " . mysqli_error($conn);
}
}
// close connection
mysqli_close($conn);
?>
My tables of importance:
question: QuestionID(PK), QuestionText
answers: AnswerID(PK), Answer1Text, Answer2Text
question_answers: QuestionAnswerID(PK), QuestionID(FK), AnswerID(FK)
Ps. I prefer not to use composite unique constraint as a solution.
Also a side-question, should $stmt->insert_id variables be mysqli_real_escape_string?
Your problem is that you have executed the second query TWICE
if (isset($_POST['textinput1']) && !empty($_POST['textinput1'])) {
$text1 = mysqli_real_escape_string($conn, $_POST['textinput1']);
$text2 = mysqli_real_escape_string($conn, $_POST['textinput2']);
$q_text = mysqli_real_escape_string($conn, $_POST['textarea']);
$stmt = $conn->prepare("INSERT INTO answers (Answer1Text, Answer2Text) VALUES (?, ?)");
$stmt->bind_param('ss', $text1, $text2);
$stmt->execute();
$answerid = $stmt->insert_id;
$stmt = $conn->prepare("INSERT INTO question (QuestionText) VALUES (?)");
$stmt->bind_param('s', $q_text);
$stmt->execute();
$questionid = $stmt->insert_id;
// THIS IS THE SECOND EXECUTION OF QUERY 2
if ($stmt->execute()) {
$stmt = $conn->prepare("INSERT INTO question_answers (AnswerID, QuestionID) VALUES (?, ?)");
$stmt->bind_param('ss', $answerid, $questionid);
$stmt->execute();
echo "<h2>Dit spørgsmål er nu lagt op på siden!</h2>";
echo "<h3>Tusinde tak for din interesse for SMIL - Skodfri Århus.</h3>";
}
else
{
echo "ERROR: Could not able to execute . " . mysqli_error($conn);
}
}
// close connection
mysqli_close($conn);
?>
Instead try this as the IF test
//if ($stmt->execute()) {
if ( isset($answerid,$questionid) ) {
if ($stmt->execute()) {
this runs one of your statements a second time. You should assign the return value to a variable if you need it for something later.

Why is this PHP while query not working?

I have this simple pre-sort database input thing, I've created this before, what I'm screwing up is the while aspect.
There are two different tables: a table that keeps track of keyword frequencies and a table for the entries themselves paired with the keyword.
What I'm doing is saving something by a keyword, I check if the keyword exists, if it does, I increment the count of that keyword and then proceed to add the entry to the entry database, if not I create a new entry of that keyword in the keyword table and set the count as 1, then add the entry to the entry database.
$query = "SELECT COUNT(*) FROM key WHERE key=?";
if($stmt = $link->prepare($query)){
$stmt->bind_param('s',$key);
$stmt->execute();
while ($row = $stmt->fetch_row()){
$count = $row[0];
}
// count comes out here
// echo $count;
if($count==0){
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss',$id,$poster,$key,$entry,$date);
$stmt->execute();
// insert new key
$stmt = mysqli_prepare($link, "INSERT INTO key VALUES (?,?,?)");
$stmt->bind_param('isi',$id,$key,$numtimes);
$stmt->execute();
} else {
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss',$id,$poster,$key,$entry,$date);
$stmt->execute();
// update key count
$stmt = mysqli_prepare($link, "UPDATE key SET numtimes=key+1 WHERE key=$key");
$stmt->bind_param('s',$key);
$stmt->execute();
}
}
<?php
$query = "SELECT COUNT(*) FROM key WHERE key=?";
if($stmt = $link->prepare($query)){
$stmt->bind_param('s', $key);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_row()){
$count = $row[0];
}
$stmt->close();
// count comes out here
// echo $count;
if($count == 0){
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss', $id, $poster, $key, $entry, $date);
$stmt->execute();
// insert new key
$stmt = mysqli_prepare($link, "INSERT INTO key VALUES (?,?,?)");
$stmt->bind_param('isi',$id,$key,$numtimes);
$stmt->execute();
$stmt->close();
} else {
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss',$id,$poster,$key,$entry,$date);
$stmt->execute();
// update key count
$stmt = mysqli_prepare($link, "UPDATE key SET numtimes=key+1 WHERE key=$key");
$stmt->bind_param('s',$key);
$stmt->execute();
$stmt->close();
}
}
?>
This should do the trick for you, you can't use fetch_row() directly on $stmt, that was your mistake.
There are two issues
first
while ($row = $stmt->fetch_row()){
$count = $row[0];
}
should be replaced by simply
$count = $stmt-rowCount()
You actually don't need the 'keys' table. Consider your DB schema again. The keys table is superfluous. The 'entry' table will suffice just update the entry table and you are good. All information can be obtained by querying the entry table rightly

How to get select query working sqli

I want to perform a select query on my users table with sqli in php.
For security reasons (sql injection) i want to do it using parameter(s).
Also i want to store the result in a php variable.
This is my code:
the $conn variable is filled in correctly.
$login = $_POST['username'];
//Check if username is available
/*Line44*/ $stmt = $conn->prepare("SELECT login FROM users WHERE login = ?");
/*Line45*/ $stmt->bind_param('s', $login);
$result = $stmt->execute();
if ($result->num_rows > 0)
{
echo "This username is in use.";
}
else
{
//Add account to database
$stmt = $conn->prepare("INSERT INTO users (login, password, email, gender) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $login, $md5pass, $email, $gender);
$stmt->execute();
$stmt->close();
echo "<font color=\"#254117;\">Your account is succesfully geregistered! <br />U can now login!</font>";
}
I get this error:
Warning: mysqli::prepare() [mysqli.prepare]: Couldn't fetch mysqli in
C:\xampp\htdocs\cammerta\registreer.php on line 44
Fatal error: Call to a member function bind_param() on a non-object in
C:\xampp\htdocs\cammerta\registreer.php on line 45
I hope someone can provide an solution and explain to me what i did wrong.
Thanks in advance!
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
$stmt->execute();
Plus
1.Please run query in phpmyadmin or any program
2.Maybe you not set variables. $login, $md5pass, $email, $gender
$stmt = $conn->prepare statement may be return false.Please use given code for getting error in query.
if ($stmt = $conn->prepare('your query')) {
$stmt->bind_param(...);
}
else {
printf("Error=: %s\n", $conn->error);
}

Categories