The basics of what I want to do is check the user values.
If they are there return true and go back to the page otherwise return false and print null values.
$query = sprintf("SELECT * from Users where username = ? and password = ?");
$params1 = array( $username, $password);
$stmt = sqlsrv_query($conn, $query, $params1);
if ($stmt === false)
{
die(print_r(sqlsrv_errors(), true));
}
$Users = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$username1 = $row['username'];
$password1= $row['password'];
}
$Users["username"] = $username1;
$Users["password"] = $password1;
//echo json_encode($Users);
echo "you are here";
if ($username1==null)
{
return false;
echo "null values";
}
else {
return true;
if (!empty($_SERVER['HTTP_REFERER']))
header("Location: ".$_SERVER['HTTP_REFERER']);
else
echo "No referrer.";
}
echo "\n\nyou're at the end though";
sqlsrv_free_stmt($stmt);
sqlsrv_close( $conn );
}
else {
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
As you can see I am trying to debug the program and see where the program is going. It gets to the point
//echo json_encode($Users);
echo "you are here";
After that nothing else seems to work and I don't know why.
Directly after your working echo you have:
if ($username1==null)
{
return false;
...
}
else
{
return true;
...
}
...
So nothing after this will get executed because of the return statements. From the manual:
If called from within a function, the return statement immediately
ends execution of the current function, and returns its argument as
the value of the function call. return also ends the execution of an
eval() statement or script file.
If called from the global scope, then execution of the current script
file is ended.
Also note that you should check for the number of rows returned from your query, now you will get undefined variable warnings if no row was found.
before you enter thw while statment you need to check the row count in if statment if its not 0 return true else return false something like this
if(sqlsrv_num_rows($stmt)
{
// your code be here
return true;
}else{
// your code be here
return false;
}
http://php.net/manual/en/function.sqlsrv-num-rows.php
Related
i did some query to check username and password.
when i enter the right data its working ok,
if i put the right email and wrong password its working ok,
when i put a username that do not exist i get no results and white screen. now echo command jump. its looks like its stuck and there is no error.
any idears?
if (isset($email) && isset($password)) {
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE user_email = '{$email}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row["user_password"] == $password) {
echo json_encode($row);
} else {
echo ('{"user_id":"0","user_name":"","user_email":"","user_password":"","register_date":"2016-03-05","confirm":"0"}');
}
}
} else {
echo("error");
}
} else {
echo($result);
echo("Missing Vars");
}
I bet that "if ($result)" is true but it never enters the while loop since there are no rows to iterate over. This would lead to a blank screen. Try echoing out what is returned from the database and echoing out each nest to see what gets output. Like the following:
if ($result) {
echo("if $result must be true because I made it in");
while ($row = mysqli_fetch_assoc($result)) {
echo("I made it in the while loop if there are rows in my result");
if {
echo("I made it in while's if");
...
} else {
echo("I made it in while's else");
...
}
}
} else {
echo("if $result must be false because I didn't make it in");
echo("error");
}
I bet that using the above example you'll see:
if $result must be true because I made it in
And that is all you'll see
/MY CODE/
The if part is working properly but else is not working.
i even tried $variable instead of direct echo but still it is not working 'else'
Updated
<?php
$db = new mysqli('localhost', 'root' ,'', 'timeline');
if(!$db) {
echo 'Could not connect to the database.';
} else {
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
if(strlen($queryString) >0) {
$query = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10");
if(isset($query)) {
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some'; // this part is not working
}
} else {
// do nothing
}
} else {
echo 'There should be no direct access to this script!';
}
}
?>
help me out.....
even read lots of like problem on stackoverflow but no real return
If you are using mysqli::query then your if(isset($query)) statement will always be evaluated as true, as $query would be either FALSE or a mysqli_result object. isset returns TRUE for both these values, so your else code will never be called.
Documentation on isset:
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
Use if($query !== false) instead.
Update
It also seems like you are checking $query to see whether or not there was a hit in the database. You need to check the number of rows in the result for that, e.g:
if ($query !== false && $query->num_rows > 0) {
// Query was ok and at least one row was returned
}
else {
// Will be reached if query was bad or there were no hits
}
Try
if($query_run = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10")){
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some';
}
For some reason, the while loop below never fires.
All of this is inside a class.
$code = $this->get_postal_state_no('Western Cape');
private function get_postal_state_no($psn)
{
$sql = "
SELECT
no
FROM
ct_state
WHERE
name LIKE('".$psn."');";
$stmt = sqlsrv_query($this->conn1, $sql);
// This statement is not false, so the error handling does not happen, this is expected.
if($stmt === FALSE)
{
if(($errors = sqlsrv_errors()) != NULL)
{
foreach($errors as $error)
{
$sqlstate = $error['SQLSTATE'];
$code = $error['code'];
$sqlmessage = $error['message'];
}
}
$msg = 'Error in $stmt in get_postal_state_no() method.';
$this->do_error_log($error_msg, $sqlstate, $code, $sqlmessage, $msg, __LINE__, __FILE__, __FUNCTION__, __CLASS__, __METHOD__);
sqlsrv_free_stmt($stmt);
}
//This loop is never entered. This is not expected.
while($obj = sqlsrv_fetch_object($stmt))
{
echo "I am here now";
break;
if(!empty($obj->no) && $obj->no != '')
{
echo "Hello, I exist";
break;
// This break never happens
return $obj->no;
}
else
{
echo "Hello, I don't exist";
break;
// This break never happens
$code = $this->sp_aa_iud_ct_state($psn);
return $code;
}
sqlsrv_free_stmt($stmt);
}
}
Does anyone have an idea why? I am using the php_sqlserv driver. The SQL server profiler shopws the query for the first part executing.
Thanks
J
Looking at the documentation page for sqlsrv_fetch_object it says this about the return value:
Returns an object on success, NULL if there are no more rows to return, and FALSE if an error occurs or if the specified class does not exist.
I suspect the function is either returning NULL or FALSE, though the reasons are a little unclear. Try adding this above the while loop and see what the output is:
$obj = sqlsrv_fetch_object($stmt)
var_dump($obj);
die;
while($obj = sqlsrv_fetch_object($stmt))
{ // ...
Another helpful debugging trick is to dump out the query and then copy/paste it into your DBMS system and run the query you are executing in code directly against your database to see if any results are actually being returned:
$sql = "
SELECT
no
FROM
ct_state
WHERE
name LIKE('".$psn."');";
var_dump($sql);
For example:
$qrInsert = "INSERT INTO DBASE1.DBO.TABLE1 VALUES ('sampVal','sampVal','sampVal')";
odbc_exec($msCon,$qrInsert);
if( 'the query if successfully executed' ){
//then do this
//if not then
}else{
//then do this
}
Is there an easy way to know if it is successfully inserted, or in other cases, updated, and deleted succesfully?
Thanks
Try like
if(odbc_exec($msCon,$qrInsert))
{
echo 'Executed Successfully';
} else {
echo 'Error in execution';
}
odbc_exec only will return true if the query executed successfully,or else return false if it is not
if (odbc_exec($msCon,$qrInsert)){
// do this
}
else{
// do that
}
just replace your code with
$qrInsert = "INSERT INTO DBASE1.DBO.TABLE1 VALUES ('sampVal','sampVal','sampVal')";
if( odbc_exec($msCon,$qrInsert); )
{
//then do this
//if not then
}
else
{
//then do this
}
It Return 0 or 1 depends on failure or success of your query.You Can store result of "odbc_exec" in a variable & compare it in 'If','Else' condition.Benefit of storing in a variable is ,you can use it where ever you want .
i.e.
$query_result = odbc_exec($msCon,$qrInsert);
if($query_result)
echo 'Executed Successfully';
else
echo 'Execuion Error';
I have the following simple php code snippet, which will, when called, delete a relevant article from a database. The result is passed to a javascript function, which will update the page via AJAX. I would like to return the string false if the query fails, as I've below.
if($cmd=="deleterec"){
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
$delRecord->close();
echo "true";
} else {
echo "false";
}
}
I would like to know what I have missed and the correct way to check if a query was successful or not.
You're currently only checking whether the SQL statement is correctly prepared, you're not checking whether it actually deleted the record.
Try:
...
echo ($delRecord->affected_rows > 0) ? 'true' : 'false';
$delRecord->close();
That doesn't address whether you're correctly checking the result string in your Javascript code - if that's a problem we'll need more information.
You need to use mysqli->affected_rows() for checking if the query was successful (or you could use mysqli_stmt->execute()'s result value).
Taking your example, and modifying nothing but for the above:
if($cmd=="deleterec") {
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
if ($delRecord->affected_rows > 0) {
echo "true";
} else {
echo "false";
}
$delRecord->close();
}
}
Use the return value of mysqli_stmt->execute() to see if the query was executed successful.
if($cmd=="deleterec"){
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
$delRecord = $con->prepare($deleteQuery);
if ( $delRecord === false ) {
echo "false";
}
$delRecord->bind_param("s", $pk);
if ( $delRecord->execute() ) {
echo "true";
} else {
echo "false";
}
$delRecord->close();
}
Checking prepare() could be left out because the query is fixed and should be working (unless there is an error on the server side). execute() returns true, if the query was executed successful. Using affected_rows() can be misleading because perhaps there was no item to delete and therefore affected_rows() whould return 0. Nontheless the query was successfully executed.
function run_query($query,$conn,$dbname){
$conn->select_db($dbname);
if($result = $conn->query($query)){
return $result;
}
else{
echo 'error ';
exit();
}
}
run_query() accepts three parameters, the query, connection, and DB. will through an error if the query was unsuccessful, else result object will be returned.