mysqli_num_rows not returning accurate results - php

I have a script that is supposed to take a form email value and query the database for duplicates. However, regardless of if I use an existing email (in the database) or a new one, I get "success".
My script looks like this:
if(!empty($_POST['email'])) {
$email = $_POST['email'];
// query the database for duplicates
$query = 'SELECT email FROM user_info WHERE email = "$email"';
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result)){
echo "Email already taken";
} else {
echo "Success";
}
Obviously mysqli_num_rows is returning some kind of data - or none at all.
Does anyone understand why I would not get a returned row if I'm selecting an email that already exists in the database?
EDIT
$('#email').blur( function() {
if(!this.value){
$('#jquery_msg').html("Email can't be empty");
} else if (!filter.test(this.value)){
$('#jquery_msg').html("Not a valid email");
} else {
var emailVal = $('#email').val();
// make an ajax call
$.ajax({
url: 'validation.php',
type: 'post',
data: {'email': 'emailVal'},
success: function(data, status) {
$('#jquery_msg').html(data);
// console.log(data);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
}
});
The problem is in the data that's being passed to the PHP script via Ajax. What I thought was the value of $('#email').val(); was literally emailVal. Huh..
Now I need to solve how to pass the value into the Ajax call properly.
Thank you all for you help.

This is wrong:
$query = 'SELECT email FROM user_info WHERE email = "$email"';
Apart from the potential sql injection problem, variables do not get parsed when you use single quotes.
You should use a prepared statement instead:
$query = 'SELECT email FROM user_info WHERE email = ?';
Then you can prepare the statement, bind the placeholder and get the results. Check the manual for more information.
A quick solution would also be:
$query = 'SELECT email FROM user_info WHERE email = "'
. mysqli_real_escape_string($db, $email) . '"';
Edit: To trouble-shoot further problems, you should add error handling to your database calls. You can have mysqli throw exceptions telling you exactly what is wrong - if anything - by adding this to the top of your script:
ini_set('display_errors',1);
error_reporting(E_ALL | E_STRICT);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

Related

mysqli_num_rows() returning incorrect number of rows

Context:
I've created a page where users can vote on debates. The debates all have two potential options. When the user clicks on the option on the left side, it returns a value of "0". When the user clicks on the option on the right side, it returns a value of "1". After the user clicks the side they want to vote on, an AJAX call is executed, which checks the database to see if the user has already voted by checking the user ID and poll ID. The AJAX works fine. This is the jQuery/AJAX code:
$(".display-polls-container").on("click", "input:radio", function(e) { //when user votes on debate
var thisElement = $(this);
var vote_value = $(this).val();
var pollId = $(this).parent().parent().parent().siblings().children(".poll-id").val();
<?php if (isset($_SESSION['id'])) { ?>
setVote(vote_value, pollId, thisElement); //insert vote into database
<?php } else { ?>
alert("You must sign in to vote on a debate");
<?php } ?>
});
function setVote(vote_value, pollId, thisElement) { //insert vote into database
$.ajax({
url: 'includes/poll_votes.php',
type: 'POST',
data: {vote_value: vote_value, pollId: pollId, idUsers: idUsers},
success: function(data) {
getVote(pollId, thisElement); //if vote inserts correctly, get the vote count and apply it to the debate (this function is not relevant enough to include its code)
},
error: function(requestObject, error, errorThrown) {
//console.log(error);
//console.log(errorThrown);
}
});
}
Problem:
The problem is that the PHP code isn't working at the moment. Everything seems to be working about it except the mysqli_num_rows() function. Here's the PHP code:
<?php
include 'dbh.inc.php'; //include database connection
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$query = "SELECT idUsers FROM poll_votes WHERE idUsers = ? AND poll_id = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'ii', $idUsers, $poll_id);
$idUsers = $_POST['idUsers'];
$pollId = $_POST['pollId'];
$vote_value = $_POST['vote_value'];
$seen = "false";
if ($vote_value == 0) { //change value inserted into database based on which side you voted for
$yes = "true";
$no = "false";
} elseif ($vote_value == 1) {
$yes = "false";
$no = "true";
}
mysqli_stmt_execute($stmt);
$r = mysqli_stmt_get_result($stmt);
if ($r) {
if (mysqli_num_rows($r) == 0) { //check if user has already voted on debate; this seems to be where the problem lies - it always returns 0
$q = "INSERT INTO poll_votes (yes, no, poll_id, idUsers, seen) VALUES (?, ?, ?, ?, ?)"; //insert vote into database
$stmt2 = mysqli_prepare($conn, $q);
mysqli_stmt_bind_param($stmt2, 'ssiis', $yes, $no, $pollId, $idUsers, $seen);
$execute = mysqli_stmt_execute($stmt2);
if ($execute) {
echo "Vote submitted successfully!";
}
} else {
echo "You can't vote twice!";
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
What happens is, even when the user has already voted on a specific debate, the query doesn't disallow them from continuing to vote on the same debate. Once the user votes once, they shouldn't be able to do it again. I try checking if they have already voted using the mysqli_num_rows() function, but it ALWAYS returns 0, regardless of how many rows there actually are.
Things I have tried:
I checked the original query by submitting my own values into the "SQL" part of the mysqli database, and it worked just fine, so I don't think that the problem is with the query. I have also formed the query using non-prepared statements, which worked fine and returned the correct number of results from the database. This means that the fact that I'm using prepared statements might mean that I left something out. Any ideas? Thanks.
I don't know why this worked, but I just re-wrote the code to go through the motions again and see if I could notice any prior mistakes. Ultimately, I don't THINK anything was changed, but it works now.

Jquery ajax not call not working

I have 2 files in my directory: one is js/form-validation-reg.js and one is HTML/registeruser.php. The javascript file validates a form from another html file which I have already checked; all values are passed all the way till the ajax but the values does not seem to be send to registeruser.php to be send in my database.
form-validation-reg.js:
//data string creation
var dataString = 'name='+ name
+ '&pass=' + pass
+ '&nationality=' + nationality
+ '&contactno=' + contactno
+ '&dateofbirth=' + dateofbirth
+ '&eaddress=' + eaddress
+ '&address=' + address
+ '&gender=' + gender
+ '&monthlysub=' + monthlysub;
//ajax
$.ajax({
type:"POST",
url: "HTML/registeruser.php",
data: dataString,
success: success(),
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
});
no errors is displayed and i have also tried setting the url as "../HTML/registeruser.php" but it still doesn't work.
PHP file(NOTE:i have also made sure my database details are correct.):
$name = stripslashes(strip_tags($_POST['name']));
$pass = stripslashes(strip_tags($_POST['pass']));
$nationality = stripslashes(strip_tags($_POST['nationality']));
$contactno = stripslashes(strip_tags($_POST['contactno']));
$dateofbirth = stripslashes(strip_tags($_POST['dateofbirth']));
$eaddress = stripslashes(strip_tags($_POST['eaddress']));
$address = stripslashes(strip_tags($_POST['address']));
$gender = stripslashes(strip_tags($_POST['gender']));
$monthlysub = stripslashes(strip_tags($_POST['monthlysub']));
$mysqli = new mysqli("localhost", "root", "","testdb")or exit("Error connecting to the database.");
$stmt = $mysqli->prepare("INSERT INTO user
(name, password, nationality, contactno, dateofbirth, email, address, gender, monthlysub)
VALUES (?,?,?,?,?,?,?,?,?)");
$stmt->execute();
$stmt->bind_param("sssssssss", $name, $pass, $nationality, $contactno, $dateofbirth, $eaddress, $address, $gender, $monthlysub);
$stmt->fetch();
$stmt->close();
$mysqli->close();
try:
success: success,
instead of :
success: success(),
Not sure if this might help, but your dataString variable looks like you're building it to go into a URL which would use get instead of post. It could be that your php script doesn't know how to parse what's getting passed to it because it's looking in the post variables instead. Since you're passing a password you wouldn't want to use get for security reasons though.
You need to be calling the $stmt->bind_param before the $stmt->execute();
If there is still an issue then you need to break it down to see what is given you the issue:
1) Ensure that the Javascript is getting called. Put an alert() in your Javascript and reload the page. If the alert pops up then your are fine there and you can rule out any include URL issues.
2) If you are using Firefox, install firebug and then hit F12 and view the console. You will see the HTML/registeruser.php getting called and you will also be able to see the parameters that are getting sent and other info. You can also do this in Chrome. If the URL is getting called and you are receiving a 200 response then there are no problems there and that is one more thing you can rule out.
3) At this point we have ruled out the Javascript and the Ajax call. So now we focus on the Database connection and then the SQL query. After your connection on the registeruser.php do a select statement of a table that you know has records, echo them out to ensure you definitely have a connection and that you are connected to the correct database.
4) Echo your SQL statement to ensure that it has all the parameters.
By the way, you should also check your error handling, instead of using exit you should be checking for the mysqli error so after the new mysqli call then add this:
if (mysqli_connect_errno()) {
printf("Error connecting to the database: %s\n", mysqli_connect_error());
exit();
}
You may use a library that does that automatically, like http://phery-php-ajax.net already do the bridge between jQuery and PHP automatically
phery.remote('registeruser', {
'name': name,
'pass': pass,
'nationality': nationality,
'contactno': contactno,
'dateofbirth': dateofbirth,
'eaddress': eaddress,
'address': address,
'gender': gender,
'monthlysub': monthlysub,
});
Phery::instance()->set(array(
'registeruser' => function($data){
$data = array_map('strip_tags', $data);
/* rest of mysql code */
return PheryResponse::factory(); // do any DOM manipulation, redirect, etc
}
))->process();

Ajax + PHP Collaboration Error

NOTE: UPDATE - Please Read
Please Read, updated code, much better:
Also, I added an ajax error function and it doesn't call an error, the first time I do it, but the next time it happens, an error occurs, and the third and fourth times, and so on.
I have some code that doesn't seem to be working, and the problem is probably located in the Ajax request or the PHP receiving function, and I don't know what the problem could be.
Here is the important code, ask for any other code that could also be of help to you.
Jquery Ajax request
$(document).ready(function()
{
$("#secretcoin").mouseover(function()
{
$.ajax(
{
type: "POST",
url: "achievements.php",
data: { Home_Coin_Locator: "Yes" },
error: errorAlert
});
});
});
Receiving side, PHP, which takes this info and stores it in a database:
$achieve4 = $_POST["Home_Coin_Locator"];
$astrSQL = "SELECT * FROM Awards_Inv WHERE Username = '$username'";
$rs3 = mysql_query($astrSQL, $connection);
if ($achieve4 == "Yes")
{
while($row3 = mysql_fetch_array($rs3)){
$soar4 = $row3["Home_Coin_Locator"];
if ($soar4 == "Yes")
{
$soa4 = "Yes";
}
else
{
$soa4 = "No";
$awardSTRsql = "UPDATE Awards_Inv SET 'Home_Coin_Locator' = 'Yes' WHERE Username = '$username'";
mysql_query($awardSTRsql, $connection) or die(mysql_error());
$updatestatsSTRsql = "UPDATE User_Info SET `Coins` = Coins + 120, `Skill Points` = Skill Points + 10, `Awards` = Awards + 1 WHERE Username = '$username'";
mysql_query($updatestatsSTRsql, $connection) or die(mysql_error());
}
}
}
else
{
}
Ok, so my code might be weird, but just try to read it and see what the problem is.
I guess any other advice is also accepted, thanks for looking, and I hope you find something!
I added an error callback function and combined 3 mysql queries into 1, but the problem still exists.
Finally, read this code for info about the $connection and $username variables
$connection = mysql_connect("mysql1.000webhost.com", "username hidden", "password hidden") or die (mysql_error ());
mysql_select_db("a7347456_usersdb") or die(mysql_error());
session_start();
$username = $_SESSION["Username"];
Another factoid:
The error is that the info does not get updated to database, as far as I know.
first thing, make sure that you required the config file witch identify the $connection variable. and it will be easier if you describe what the problem exactly is.

how to get the current added in the table without getting all the data

guys im trying to make a simple commenting system, that when i click the submit the fields will automatically save in the database then fetch it using ajax. but im getting all the data repeatedly instead of getting the recently added data in the database here is the code:
<div id="wrap-body">
<form action="" method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
if(username != "" && msg != ""){
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:{ 'username' : username , 'msg' : msg},
success: function (data){
var ilan=data[0].counter;
var i = 0;
for(i=0;i<=ilan;i++){
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
}
}
});
}
else{
alert("some fields are required");
}
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
$inside_counter = mysql_num_rows($result);
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message'],
'counter'=>$inside_counter
);
}
echo json_encode($data);
?>
SELECT *
FROM "table_name"
ORDER BY "id" desc
LIMIT 1
This is a SQL query to get last record from table. It return last inserted according to id. id should be a auto increment field. I think this will be helpful for you.
Its because you are returning all the row in the table again to the ajax call via
$get = "SELECT * FROM info ";
if you do return all of them again you will have to test if they are not already there before appending them with the jQuery
Perhaps only return the newly inserted row.
or
The jQuery already knows the data it sent to the server, just return success true or false, and then append it if true with the jQuery, no need to return the data back again to the client side
EDIT
I'm not going to write code for you but perhaps these suggestions may help
mysql_query($insert)
link here for reference - http://php.net/manual/en/function.mysql-query.php
will return true of false depending on if the insert statement was successful
you could potentially also check that it acutally inserted a row by calling
mysql_affected_rows()
link here for reference - http://php.net/manual/en/function.mysql-affected-rows.php
then assuming that the insert was successful (i.e. true from mysql_query($insert) or mysql_affected_rows() > 0) simply return successful (i.e. something like
echo json_encode(true);
then on the client side you could do something like the following:
(jQuery Ajax success function only:)
success: function (data){
if (data) {
$('#info').append("<p> you are:"+username +"</p> <p> your message is:"+msg);
}
else
{
alert('There has been an error saving your message');
}
}
using the variables that you just used to send the request
(Please note code samples provided here are only for example, not intended to be used verbatim)
Couple of points though. Is your intention to post the data via ajax only? (i.e. no page refresh) as if that is the case, you will need to return false from you form submit event handler to stop the page full posting. Also you do not appear to have any logic, or are not worried about complete duplicates being entered (i.e. same username, same message) - not sure if you want to worry about this.
I would also potentially look at tracking all the messages via ids (although I don't know your DB structure), perhaps using
mysql_insert_id()
link here FYI - http://php.net/manual/en/function.mysql-insert-id.php
That way each message can have a unique id, may be easier to establish duplicates, even if the username and message are identical
There are numerous ways to deal with this.
Anyway hope that helps
PS - using the mysql_ - group of commands is generally discouraged these days, use the mysqli_ range of function instead

mySQL insert statement NOT working?

I've been looking around for an answer. I've been cross-referencing my code with others. And I don't seem to see any blatant errors...
My database does not update, my database does nothing. Oh and the page also does nothing too...... It's frustrating because, I'm just using notepad ++ and can't pinpoint the error. I'm using XAmpp as well, and, all the values match the ones I have made.
The .post statement (Using jQuery 1.7.1):
//Make sure DOM is loaded before running jQuery based code: [STATIC CODE]
$(document).ready(function(){
$('#uploadbtn').click(function() {
//Parse name and song.
var name = $('#songname').val();
var song = $('#songupload').val();
$.ajax(
{
type: 'POST',
data: 'db/upload.php?name=' + name + 'song=' + song,
success: function(res) {
$('#nav-playlist').html(res);
}
}
)
});
});
Now here is my php file:
<?php
/*Connection to database.
First with mysql_connect (to log in). Then selecting the master database.
*/
echo "Upload.php accessed...";
$connection = mysql_connect("localhost", "root", "root") or die ( mysql_error() );
$database = mysql_select_db("betadb") or die( mysql_error() );
//Properties (to be inserted into database).
$name = mysql_real_escape_string($_POST["name"]);
$song = mysql_real_escape_string($_POST["song"]);
//Insertion formula for mySQL
$query = "INSERT INTO songs SET name= '$name' song='$song' ";
if (mysql_query($query)){
echo "Success";
}
else {
}
?>
ADDITIONAL NOTES:
the song table consists of id, name, song (in that order).
Song is the BLOB datatype, as it is used to store .mp3s
The problem is with the following line
data : 'db/upload.php?name='+name+'song='+song,
data should be an array containing the values, such as
var data
data["name"] = name
data["song"] = song
The $.ajax call is also missing the url parameter which is needed to carry out the request
url: 'db/upload.php'
Try to specify your column.
$query = "INSERT INTO songs (youcoulmn1,youcolumn2) VALUES ('$name', '$song')";
See also:
PHP MySQL Insert Into
Regards
$name = mysql_real_escape_string($_POST["name"]); //Assign to name & song variables.
$song = mysql_real_escape_string($_POST["song"]);
//Insertion formula for mySQL
$query = "INSERT INTO songs VALUES ('$name', '$song')";
$result = mysql_query($query, $connection) or die ("Unsucessful");
had better using SET, is more easier for some conditions, and for Jquery Command use $.ajax, you can try this one
for javascript / JQuery
$(function(){
$('#uploadbtn').click(function(){
var name = $('#songname').val();
var song = $('#songupload').val();
$.ajax({
type :'POST',
data : 'db/upload.php?name='+name+'song='+song,
success :function(res){
$('#nav-playlist').html(res);
}
});
});
});
and for Insert command in the php
$name = mysql_real_escape_string($_POST["name"]);
$song = mysql_real_escape_string($_POST["song"]);
$query = "INSERT INTO songs SET name='$name' song='$song'";
if(mysql_query($query)){
// some process if success
}else{
// some proses if not
}
use mysql_real_escape_string to filtering data before insert to database
in order to debug it
1) do print_r($_POST); to check do you have anything to insert
2) then instead of
$result = mysql_query($query, $connection) or die ("Unsucessful");
do
$result = mysql_query($query, $connection) or die (mysql_error());
to get the exact error and search for the error fix
The single quotes around variables might be causing the problem.. check it..
As far as I remember, the line
$query = "INSERT INTO songs SET name= '$name' song='$song' ";
should be
$query = "INSERT INTO songs SET name= '$name', song='$song' ";
Pay attention to commas!
And also:
data: 'db/upload.php?name=' + name + 'song=' + song,
should be at least:
data: 'db/upload.php?name=' + name + '&song=' + song,
because there is no delimiter between fields right now.

Categories