how to validate multiple inputs from database? [duplicate] - php

This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 7 years ago.
I wan't to create a validation, check the database if the DATE, TIME and COTTAGE is already reserved/available. If any in one of the 3 is unavailable, it will save to the database.
Here is the code I made:
<?php
require_once("config.php");
require_once("includes/inputs.php");
//fetching the data of the cottage
$sql = "SELECT * FROM cottage WHERE id='$cottage'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
$name_cottage = $row["name"];
//fetching the data of the time
$sql = "SELECT * FROM rate WHERE id='$daytime'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
$daytime_name = $row["name"];
//validating whether the date, time and cottage is already available in the cottage
$validate = "SELECT * FROM reserve WHERE date = '$date' AND daytime = '$daytime' AND cottage = '$cottage'";
$qry = mysqli_query($link, $validate);
$getrow = mysqli_num_rows($qry);
if( $getrow > 0 ){
echo " $date, $daytime_name and $name_cottage has already been taken!";
return false;
}
else{
$sql = "INSERT into reserve (name, address, contact, email, date, time, ahc, chc, cottage, promo, total) values ('$name','$address','$contact', '$email', '$date', '$daytime', '$ahc', '$chc', '$cottage', '$promo', '$calc')";
$result = mysqli_query($link,$sql);
echo " $date, $daytime_name and $name_cottage is successfully reserved!";
return true;
}
?>
But i am having an error of:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\reservation\formup.php on line 22
and line 22 is
$getrow = mysqli_num_rows($qry);
but when i use this multiple select query:
$validate = "SELECT * FROM reserve WHERE date = '$date'";
$validate = "SELECT * FROM reserve WHERE daytime = '$daytime'";
$validate = "SELECT * FROM reserve WHERE cottage = '$cottage'";
it will save to the database but when the cottage have the same cottage on the database it won't save...
please help me to fix this....

By the documentation of msyql query:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
Link
So as i understand it the query is successful or not succesful true / false is returned else a mysqli_result object. So i think your query have no return value. Tried running the sql query on the db and have you check that the expected values are returned?

mysqli_num_rows() returns true on success and false on failure; for select, show etc. mysqli_query return result object.
I may need to see the full codes to get better idea whats wrong there but try this:
$qry = mysqli_query($link, "SELECT * FROM reserve WHERE date = '$date' AND daytime = '$daytime' AND cottage = '$cottage'");
$getrow = mysqli_num_rows($qry);
if( !$getrow == 0 ){
echo ".....taken";
}
else{
$sql = mysqli_query($link, "insert.....");
echo "...reserved";
}

Related

How to access the integer returned from SQL Count [duplicate]

This question already has answers here:
number of rows in a table
(3 answers)
Closed 6 years ago.
Going to make this quick.
So I am doing something that should be relatively simple but none of the answers I have found online (Yes, I have read through and implemented them ALL) have yielded the right result.
Basically, all I am trying to do is count how many times a specific field shows up in a column in one of my databases. Sounds easy, right?
Well, this is where it gets a bit sketchy for me. The query I am trying to use to attain this information is this:
$sql2 = "SELECT user_id COUNT(*) FROM ch_documents_list WHERE user_id = $users_id ";
From here, I want to take the result as an int and echo it into a specific part of the site (not important as to where exactly).
The only way I can get information out of the result is to run a print_r($result) Where $result is set to the response of the query.
NOTE The information printed looks like this:
mysqli_result Object ( [current_field] => 0 [field_count] => 5 [lengths] => [num_rows] => 1 [type] => 0 )
Which, as many of you can figure out, is useless. What changes do I need to make in order to get this right?
Thanks everyone!
Pasting more of my code below
Query As Of Now
$dbname_classes = "classes";
$conn2 = new mysqli($servername, $username, $password, $dbname_classes);
$sql2 = "SELECT user_id, COUNT(*) AS total FROM ch_documents_list WHERE user_id = $users_id";
$result2 = $conn->query($sql);
$row = mysqli_fetch_assoc($result2);
Then below in the html
<div class='overview-stat'><?php echo $row['total']; ?></div>
Which leads to this:
Notice: Undefined index: total
May this be helpful.
$sql2 = "SELECT COUNT(*) as total FROM ch_documents_list WHERE user_id = $users_id";
$result = mysqli_query($con,$sql2); // $con is Boolean returned from mysqli_connect()
$row = mysqli_fetch_array($result);
echo $row["total"];
Try this code
$query = "SELECT * FROM ch_documents_list WHERE user_id = $users_id ";
$result = mysqli_query($con,$query );
$rows = mysqli_num_rows($result);
print_r($rows);
May not the propper way, but works fine for me since years:
$sql2 = "SELECT user_id COUNT(*) AS total FROM ch_documents_list WHERE user_id = $users_id";
$result = mysqli_fetch_assoc($sql2)
You can then access it with
$result['total']
Using the SQL AS Keyword
Rewrite your query like this below query:
$sql2 = "SELECT user_id, COUNT(*) AS total FROM ch_documents_list WHERE user_id = $users_id";
After that just index your result array using the total key and boom you got your int counts
Like: $result['total']
return int two query example:
1. $sql2 = "SELECT COUNT(user_id) as id FROM ch_documents_list WHERE user_id = $users_id";
**You should return count
mysql_num_rows
**
$conn = mysqli_connect("localhost", "username", "password", "databasename");
$result = mysqli_query($conn, "SELECT user_id FROM ch_documents_list WHERE user_id = $users_id");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
this is mysqli function support

Error: mysqli_fetch_object() expects parameter 1 to be mysqli_result [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 8 months ago.
I don't know what the problem is with this line or how to fix it, before was okay and now I'm getting this error:
mysqli_fetch_object() expects parameter 1 to be mysqli_result
Here is my PHP code:
<?php
}
if($_GET['action']=="user_info")
{
$userid = $_GET['user_id'];
$query = "SELECT * FROM user WHERE user_id ='{$userid}'";
$result = mysqli_query($link, $query);
$user = mysqli_fetch_object($result);
$queryt = "SELECT * FROM user_title WHERE id='".$user->title."'";
$resultt = mysqli_query($link, $queryt);
$rowt = mysqli_fetch_object($resultt);
$title = $rowt->name;
$sorgu = "select * from pub_author where user_id='$userid'";
$publications = mysqli_query($link, $sorgu);
while($a = mysqli_fetch_object($publications))
{
$ids .= $a->pub_id . ',';
}
$ids = rtrim($ids,",");
$sorgu2 = "select count(id) as total , year from publication where id IN ($ids)
GROUP BY YEAR(`year`) order by `year` ";
$publications2 = mysqli_query($link, $sorgu2);
while($a2 = mysqli_fetch_object($publications2))
{
$mount = explode('-', $a2->year);
$accyaz[$mount[0]] = $a2->total;
}
}
?>
As far as your exact error is concerned one of your query is failing, the following steps might help. Ofcourse you question looks duplicate but here are some of the things that addresses your question
Your first query should be like this, with no curly braces, ofcourse untill you have explicitly ids wrapped in curly braces in your table.
SELECT * FROM user WHERE user_id ='$userid'
Secondly you are executing multiple queries so you might wanna consider error checking if your query executes properly or not(because of syntax error columns mismatch table name mismatch many more possibilities): do error checking like this as for while($a...) part
if ($result=mysqli_query($link, $sorgu);)
{
while($a=mysqli_fetch_object($result))
{
$ids .= $a->pub_id . ',';
}
$sorgu2 = "select count(id) as total , year from publication where id IN ($ids) GROUP BY YEAR(`year`) order by `year` ";
//... Your further code
}
else
{
echo "Something went wrong while executing query :: $sorgu";
}
Third i see your are getting pub_id make a comma seperated list of it so that you can give it as a parameter in your last query which is a long shot, why not use sub query for you IN clause like this:
SELECT
COUNT(id) as total, year
FROM publication
where id
IN (
SELECT pub_id FROM pub_author WHERE user_id='$userid'
)
GROUP BY `year`
order by `year`;
The error you are stating translates to this: The query fails somehow, instead of running the mysqli_query($link, $sorgu); line echo $sorgu, go to phpmyadmin and test your query, if it is bad, fix it in phpmyadmin until it works and set it up in the code correctly

Mysqli num rows and mysqli fetch array issue [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I try to google it but, i really dont understand what is the problem with this query. Here is code
include_once("includes/db_connection.php");
//Upit za prikaz pitanja!
$listaPitanja = "";
$sql = "SELECT id, username, question FROM useroptions ORDER BY DESC";
$user_query = mysqli_query($db_connection, $sql);
$pitanjaCount = mysqli_num_rows($user_query); //line 8
if ($pitanjaCount > 0) {
while ($row = mysqli_fetch_array($sql)) { //line 10
$id = $row['id'];
$question = $row['question'];
$username = $row['username'];
$listaPitanja .= '<div id="brojOdgovora">'.$id.'</div>
<div id="tekstPitanja"><h3>'.$question.'</h3></div>
<div id="userPitanja"><h6>'.$username.'</h6></div>';
}
} else {
$listaPitanja = "There is no inserted questions!";
}
This query gives me nothing. Just this error mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in something on line 8, and if i delete ORDER BY DESC there is some error on line 10?
Sorry if it repeated, but i have no idea to solve this!! Thank you!
Your SQL statement has no ORDER column:
$sql = "SELECT id, username, question FROM useroptions ORDER BY DESC";
Change it with the correct column name:
$sql = "SELECT id, username, question FROM useroptions ORDER BY column_name DESC";
Probably, mysqli_query is returning false instead of mysqli_result object.
To add segarci,
$row = mysqli_fetch_array($sql)
should be
$row = mysqli_fetch_array($user_query)

update and insert mysqli table

I'm trying to check if the leaguename name already exists if it does then check if it is higher than the existing score. if its higher then replace the quizscore else insert the leaguename and quizscore into the table league_quiz.
The code seem to insert the values in my table, but it do not seem update if the name is equal to previous and the score is higher?
I get this error:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, string given in
My code:
<?php
$name = (string)$_POST['name'];
$score = (string) $_POST['score'];
$link = mysqli_connect("mysql12.gigahost.dk","username","password","dirts_mysql");
$query = "SELECT leaguename, quizscore FROM league_quiz WHERE leaguename = '$name' AND quizscore < '$score'";
if(mysqli_num_rows($query)) {
mysqli_query($link,"UPDATE league_quiz SET quizscore = '$score'");
} else {
mysqli_query($link,"INSERT INTO league_quiz (leaguename, quizscore) VALUES ('$name', '$score')") or die(mysqli_error($link));
}
?>
mysqli_num_rows expects the result of a query and not the string of the query itself.
Firstly you must execute your query :
$result = mysqli_query($link,$query);
and then you can count the number of rows
$numRows = mysqli_num_rows($result);
Between those two:
$query = "SELECT leaguename, quizscore FROM league_quiz WHERE leaguename = '$name' AND quizscore < '$score'";
if(mysqli_num_rows($query)) {
Have you tried to write this code?
$result = mysqli_query($query);
and then use mysqli_num_rows on the result of the query?
Try the followowing:
$result = mysqli_query($query);
if (mysqli_num_rows($result)) {
...

Doesn't work "SELECT COUNT(*) FROM..." in PHP script

My function should return number of rows with email like '$email'. But whey return 0 all the time, although in database i have rows with email like I insert in variable '$email'. What could be the reason?
function checkMail($email){
$email = mysql_real_escape_string($email);
$sql = "SELECT COUNT(*) FROM users WHERE email='$email'";
return mysql_query($sql);
}
You aren't returning a result, you're returning a query resource:
function checkMail($email){
$email = mysql_real_escape_string($email);
$sql = "SELECT COUNT(*) as emailCount FROM users WHERE email='$email'";
$query = mysql_query($sql) or die(mysql_error()); // show error if one happens
return mysql_fetch_assoc($query);
}
This will return an associative array containing your results (if it succeeds), and you should be able to access your count by:
$res = checkMail('your#email.com');
$count = $res['emailCount'];
Side note:
mysql functions are deprecated, you should use mysqli or PDO syntax:
https://stackoverflow.com/a/13944958/2812842
function checkMail($email){
$email = mysql_real_escape_string($email);
$sql = "SELECT COUNT(*) FROM users WHERE email='$email'";
$resource=mysql_query($sql);
$row=mysql_fetch_array($resource);
return $row[0];
}
To fetch the count use:
mysql_query($sql)
$row = mysql_fetch_assoc($result);
return($row[0]);
The funny thing is that mysql_query return 0, which indicates query fail. Check the corresponding error message with:
echo mysql_error();

Categories