MYSQli select not working - php

I am not actually very good at it, but I never got this kind of error. I am trying to select GB entries and I can't get it working.
gb.php
<?php
$conn = new mysqli('localhost','ab','somepassword','gb');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
else {echo 'connected';}
$sql = "SELECT * FROM `posts`";
if ($conn->query($sql) === TRUE) {
echo 'done';
}
else{echo 'sql not working';}
?>
Table snapshot
Result:
connectedsql not working
One more thing the INSERT & UPDATE statements are working from same folder.

The return value of MySqlI->query() is defined like:
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.
So you must check for not equal to false
if ($result !== false) {

you can also check on this condition
$res=$conn->query($sql);
if($res)
{
}
else
{
}

mysqli_query/ $mysqli->query does not return True if the query executed succesfully but return false if not executed..Try with -
$result = $conn->query($sql);
if ($result !== false) {
echo 'done';
}
else{echo 'sql not working';}

Related

Confirming deletion of record in mysql php

I m trying to delete a row in php mysql. The row is deleted quiet ok but mysqli_affected_rows($conn) is not giving a response so I can confirm the deletion for the user.
$sql="DELETE FROM `users` WHERE `memberID`='$id'";
$res=mysqli_query($conn,$sql);
if(mysqli_affected_rows($conn) == 1){
echo 'success'
} else {
echo "The User could not be deleted due to some error";
echo mysqli_affected_rows($conn);
}
You don't need to check by boolean value 0 or 1. But if you want to do it that way, you will need to declare a flag before that and then change the flag value according to condition after that you can do it [as your way]
(mysqli_affected_rows($conn) == 1)
But as default a simple if() conditon will check and return true on pass and false on fail.
So, simply you can do:
if($res)
{
//your codes if query is done
} else
{
//your codes if query fails
}
By default, the mysqli_query() function will return you a true if all went well or a false if there is any error. You can check if your query did not return any error like so:
if($res) {
echo "Delete success";
} else {
echo "Delete error: " . mysqli_error();
}

Blank MySQL error on shared hosting

I am doing a little bit of learning on mysql, php and the like. I'm using a shared hosting plan so am quite limited from a settings changes point of view.
I am attempting to run a simple mysql select command through PHP, but all i get back is a blank error
<?php
$typeID = $_GET['tid'];
//variables for the database server
$server = "localhost";
$user = "codingma_rbstock";
$pwd = "M#nL%V{%RI+h";
$db = "codingma_rbstock";
//variables for the database fields
$itemNo;
$itemNm;
$itemDesc;
$buyPr;
$sellPr;
$quan;
$dept;
//database connection
//create connection
$conn = new mysqli($server, $user, $pwd, $db);
//if the connection fails throw an error.
if ($conn->connect_error){
die("Connection Failed: " . $conn->connect_error);
}
echo "Welcome to " . $typeID . "<br>";
$sql = "select ITEM_NAME from stock where ITEM_NO='00001'";
if ($conn->query($sql) === TRUE){
$res = $conn->query($sql);
if ($res->num_rows > 0){
echo "success";
}
}else{
echo "Error: " .$sql . "<br>" . $conn->error;
}
echo $res;
?>
I have checked and it seems to be connecting to the database fine (I changed a few account details to see if that threw a different error and it did).
I am sure I am missing something completely obvious here! The below is the text output from the error;
Error: select ITEM_NAME from stock where ITEM_NO='00001'
Thanks for any help.
your problem is in this line
if ($conn->query($sql) === TRUE){
you are doing a variable type check ( === ), the result of that comparision will always fail because, for as long as you have data in your table and your query doesn't fail $conn->query($sql) will not return a boolean value
mysqli::query documentation says:
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.
You are using here a SELECT, therefore a successfull result won't be boolean
Try switching to
if ($conn->query($sql) == TRUE){
Or even better remove that if completely
EDIT
The better approach for that part of the code is:
$res = $conn->query($sql);
if ($res->num_rows > 0){
echo "success";
}
if ($res === false) {
echo "Error: " .$sql . "<br>" . $conn->error;
}

Error produced from mysql select

I'm currently learning MySql, but ive hit this problem.
the following code should just query the db for everything in the users table. but it returns this error. Error: SELECT * FROM users which helps me not at all. I am able to successfully insert an item into the database, but I am unable to select from it. I've also tried $sql = "SELECT * FROM ama.users"; my DB structure is
ama
|-users
any help would be much appreciated.
$conn = new mysqli($_ENV['OPENSHIFT_MYSQL_DB_HOST'],$_ENV['OPENSHIFT_MYSQL_DB_USERNAME'], $_ENV['OPENSHIFT_MYSQL_DB_PASSWORD'], 'ama');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username = "Doe";
$password = "johnexample";
$sql = "SELECT * FROM users";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
From the PHP Manual:
mysqli::query will return object in success and return false in failure.
So you can use it without checking data type (===):
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
For more better understanding you can use var_dump() and check what are you getting like:
var_dump($conn->query($sql));
Documentation says:
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.
So, do something like
$result= $db->query($sql);
and then check the rows in $result

Displaying a message when resultset is empty

In the following code, if the resultset is empty, the code continues to process the result. What I want instead is to just display "Query failed." when there are no results.
$connInfo = array('UID'=>$user, 'PWD'=>$passwd, 'Database'=>$database);
$dbconn = sqlsrv_connect($server, $connInfo);
if($dbconn === false){
die("<br />Error connecting to the database.<br />");
}
//SQL Query
$query = "SELECT ... FROM somehwere";
//Run Query
$qresult = sqlsrv_query($dbconn, $query);
if($qresult === false) {
die('Query failed.');
}
?>
...more code...
$qresult will contain an empty result set if no rows are found, but it still won't evaluate to false.
Try this function instead:
http://www.php.net/manual/en/function.sqlsrv-num-rows.php
So:
if(!sqlsrv_num_rows($qresult)) {
die('Query failed.');
}
Instead of:
if($qresult === false) {
die('Query failed.');
}
It does not display "Query Failed" because the query has not failed. It just returns 0 rows. So, the solution will be to use:
$row_count = sqlsrv_num_rows( $qresult);
if ($row_count > 0){
// display stuff
}
else{
// throw exception
}
Thanks. I got it to work using sqlsrv_has_rows() function.
if($qresult !== NULL) {
$rows = sqlsrv_has_rows($qresult);
if($rows === true) {
//display success
} else {
//display error
}
}
For some reason I couldn't get the sqlsrv_num_rows() to work properly for me.

How to test if a MySQL query was successful in modifying database table data?

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.

Categories