I want to do a really simple task: check if an inserted id matches one found in a mysql database. If no match, an alert box will appear displaying an invalid id message. The problem that I have is my script ALWAYS returns found, even if the id does not exist in the database. Here is my script, any idea what is wrong?
PHP SCRIPT:
<?php
//connect to server....
$id = $_GET["id"];
$query = 'SELECT * from users where id = $id';
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if (empty($result))
{
$response = "notfound";
echo $response;
}
else
{
$response = "found";
echo $response;
}
// Close connection to the database
mysql_close($con);
?>
You're using single quotes instead of double quotes on your query assignment. You must use double quotes or string concatenating.
$query = "SELECT * from users where id = $id";
OR
$query = 'SELECT * from users where id = ' . $id;
And you're also probably doing this in the insert, which is why it's always being 'found'.
Try:
$query = 'SELECT * from users where id = '.(int) $id;
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$num_rows = mysql_num_rows($result);
if($num_rows > 0) {
echo "found";
}
else {
echo "not found";
}
I am no t familiar with php syntax but can you replace the if condition to be something like this
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if($result)
{
$response = "found";
echo $response;
}
else
{
$response = "notfound";
echo $response;
}
Related
$stmt is execute and give Result in Print_r($stmt). Result is this "Resource id #4" but when Print_r($stmt) is put in if (odbc_num_rows($stmt) > 0) {Print_r($stmt);}. it's not give Result. and gone else conditon give message else condition.so How to Put odbc function instead of odbc_num_rows($stmt).if right Parameter pass query execute and gone if condition.
which Odbc function used in if condtion.
<?php
include 'Connection.php';
if(isset($_REQUEST["insert"]))
{
$user = $_GET['user'];
$pwd = $_GET['pass'];
$yid = $_GET['yid'];
$sql = "select RegNo, UserName, Pasword from Std_Reg where UserName= '$user' and Pasword = '$pwd' and YearID = $yid and IsActive = True";
$stmt = odbc_exec($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (odbc_num_rows($stmt) > 0)
{
print_r($stmt);
$stmt1 = odbc_fetch_array($stmt);
$product = array();
$product['RegNo'] = $stmt1['RegNo'];
$product['UserName'] = $stmt1['UserName'];
$product['Pasword'] = $stmt1['Pasword'];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
array_push($result["product"], $product);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["succes"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
odbc_close($conn); //Close the connnection first
}
}
?>
For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. The manual says-
Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.
one way around this behaviour is to do a COUNT(*) in SQL instead. See here for an example.
I have a php script which retrieves data from mysql db.
Everything works fine, but my problem is that this $result = $dao->joinedEvents($userId); returns an array of numbers and what I would like to do is to run this $secondResult = $dao->joinedEventsInfo($receivedIds); for every ID and this script I'm using right now returns data only for one ID.
This is part of my php script:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId); //This is getting the IDs array
if(!empty($result)) {
$receivedIds = $result["event_id"];
$ids = explode(",", $receivedIds);
foreach($ids as $id){
$secondResult = $dao->joinedEventsInfo($id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id" . $id;
}
}
} else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
And this is joinedEvents script:
public function joinedEvents($userId){
$returnValue = array();
$sql = "SELECT event_id from MyTable WHERE userId= '$userId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
This is joinedEventsInfo script:
public function joinedEventsInfo($eventId){
$returnValue = array();
$sql = "SELECT * FROM Events WHERE eventId = '$eventId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
Edit: Tha reason I need this is that I have two tables. In the first one I have just IDs and in the second one I have info. So first I need to get the IDs and then I need to get data for every ID I have just received.
Thank you very much , I'm totally stuck.
Based on the updated code snippets and the discussion below, it is found that $result is indeed an array, and the solution is:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId);
if(count($result)){
foreach($result as $array){
$event_id = $array['event_id'];
$secondResult = $dao->joinedEventsInfo($event_id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id: " . $event_id;
}
}
}else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
Have you tried array_map()?
That would allow you to call a php function on each member of an array easily.
Another way would be to use the common while ($row = mysql_fetch_array($result)) which would execute the code in the while loop for each row of your returned results. Note, you will likely have to change the mysql_fetch_array to something specific for your SQL connection.
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if (!$sql) {
while ($row1 = mysqli_fetch_array($sql, MYSQL_NUM)); {
echo $row1;
}
} else {
echo "Funker ikke";
}
I cant get it to work, all I get is the: else "Funker ikke".
1) Using wrong if condition. If query return true then insert into if condition
2) Wrong echo data using MYSQL_NUM. It return numeric array
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql) {// if true
while ($row1 = mysqli_fetch_array($sql, MYSQL_NUM)) {
echo $row1['0'];//numeric array
}
} else {
echo "Funker ikke";
}
UPDATED as per below comments
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql) {
$row1 = mysqli_fetch_array($sql, MYSQL_NUM);
echo $row1['0']; //numeric array
} else {
echo "Funker ikke";
}
Read http://php.net/manual/en/mysqli-result.fetch-array.php
Your code is correct except the not sign before sql in if condition.According to you if your sql query is wrong then the $row1 is displayed else if it is correct then "funker ikke" gets printed.Just the opposite. This code works:
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql) {
// as the query can only return 1 row the while look is unnecessary
//while ($row1 = mysqli_fetch_array($sql, MYSQL_NUM)) {
$row = mysqli_fetch_array($sql, MYSQL_NUM)
echo $row[0];
} else {
echo "Funker ikke";
}
Your code are having two error there.
First, it should be true condition only can get into the display loop. But you put the condition as !$sql means false only can get into the loop. So, you should change !$sql to $sql. Besides, after the While loop should not direct put the semicolon. You try see the following code
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql) {
while ($row1 = mysqli_fetch_array($sql, MYSQL_NUM))
{
echo $row1[0];
}
}
else {
echo "Funker ikke";
}
There are a few errors in your code
First you do not need a while loop to process a single result, SELECT COUNT() can only return one row.
Second as mysqli_query() for a SELECT query will return either FALSE or a mysqli_result object it would be better to flip your if condition as below and test specifically for FALSE rather than TRUE.
Third, a mysqli_fetch_array($sql, MYSQL_NUM) returns an array, you have to use array notation to get the only returned value i.e. $row[0]
Also when any mysqli_ function fails it leaves some error information that is very useful, so show that info or send it to an application error file if you dont want users to see them when the code goes live.
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql === FALSE) {
echo "Funker ikke";
echo mysqli_error($db);
exit;
} else {
$row = mysqli_fetch_array($sql, MYSQL_NUM);
echo $row[0];
}
if ($result = $db->query("SELECT * FROM tab WHERE ID = $id")) {
while($row = $result->fetch_assoc() ){
echo "ID:". $row['ID'];
echo "Product:" .$row['Product'];
... }
$result->close();
} else {
echo "could not retrieve data from db"; }
I only get one result, but it should be a lot more.
How do I get all the results?
btw I cannot use fetch_all.
You are using an ID in your query, that means that you are asking for a specific item. In order to select all you have to remove this condition.
Your code would look like:
if ($result = $db->query("SELECT * FROM tab")) {
while($row = $result->fetch_assoc() ){
echo "ID:". $row['ID'];
echo "Product:" .$row['Product'];
}
$result->close();
} else {
echo "There is no data in the database";
}
Replace
$result = $db->query("SELECT * FROM tab WHERE ID = $id"
with
$result = $db->query("SELECT * FROM tab WHERE ID = $id LIMIT 1"
You must select both id and product from tab and also add a where statement.
Your code would look like:
if ($result = $db->query("SELECT ID, Product, user FROM tab WHERE user='".$username."' ")) { //$username = john;
while($row = $result->fetch_assoc() ){
echo "ID:". $row['ID'];
echo "Product:" .$row['Product'];
}
} else {
echo "There is no data in the database";
} result->close();
Let me hope your equate value is the name john it may be anything. so you will get all result rows from the database where the word john is listed.
put $username = 'john'; before the if statement.
The process of fetching data from a MYSQL result goes like this:
Connect to the host
Select the DB
Run the query
if ($result) //Check if the return is true
while($row = mysqli_fetch_array($result)) {
// do something with the $row
//like print it
}
}
In order to make fully sure print the query using
echo $your_query
Then run that query through phpMyAdmin and see what results or error you get.
I am trying to see if the logged in user is verified. But there is an error:
Warning: mysql_fetch_array(): supplied
argument is not a valid MySQL result
resource in
/home/psmcouk/public_html/colemansystems/verify.php
on line 332
Here is the PHP code:
$user1 = $_SESSION['usr'];
$result = mysql_query("SELECT * FROM phpbb_members WHERE memberName=$user1");
while($row = mysql_fetch_array($result)) //LINE 332
{
$valid = $row['valid'];
}
if($valid == "1"){
echo "$user1, you're account is currently verified.";
}
I just can not see what is wrong with this code.
Thanks!
All the answers above are lame.
$user1 = mysql_real_escape_string($_SESSION['usr']);
$query = "SELECT valid FROM phpbb_members WHERE memberName='$user1' and valid=1";
$result = mysql_query($query) or trigger_error(mysql_error()." in ".$query);
$valid = mysql_num_rows($result);
if($valid){
echo "$user1, your account is currently verified.";
}
You probably have an SQL error. Try
if (!$result) {
echo 'Invalid query: ' . mysql_error() . "\n";
}
I guess $user should be quoted:
$result = mysql_query("SELECT * FROM phpbb_members WHERE memberName='$user1'");
You can always see whats wrong my placing echo mysql_error(); after the query
As already posted, you just have to put the user name in single quotations marks:
$query = "SELECT * FROM phpbb_members WHERE memberName = '".$user1."'";
Assuming, that the user name column is varchar. The code you used is only valid if you compare numbers, e.g. integers.
A general remark: Depending on the size of the columns of your database, it might be resonable to select specific rows rather than all using *. For instance:
$query = "SELCT memberName, valid FROM phpbb_members";
Try to use:
$result = mysql_query("SELECT * FROM phpbb_members WHERE memberName='$user1'")
or die(mysql_error()); // to get if any error exists
$user1 = $_SESSION['usr'];
$result = mysql_query("SELECT * FROM phpbb_members WHERE memberName=$user1");
while($row = mysql_fetch_field($result)) //LINE 332
{
$valid = $row['valid'];
}
if($valid == "1"){
echo "$user1, you're account is currently verified.";
}
try this.
You should test the result of mysql_query before using it, if you follow the examples from php.net :
$result = mysql_query("SELECT * FROM phpbb_members WHERE memberName=$user1");
if (!$result) {
die('Request problem : ' . msql_error());
}
while($row = mysql_fetch_array($result)) //LINE 332
...