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 an trying to query a mySQL database using a PHP function. Intermittantly, the function that I am using does not seem to return a result. As far as I can detect, it's not a null response, and based on the function, it doesn't seem to be returning an invalid result ( the return string Nuthin in this case ).
function GeneratePiece2 ($sqlstr){
$conn = new mysqli(gHOST, gUSER, gPASSWORD, gDATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sqlstr);
$returnable = "";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row;
$returnable = $row;
}
} else {
return "nuthin";
}
$conn->close();
return $returnable;
}
I've been using the same SQL Query of
SELECT Name FROM Char_Name_full WHERE Male=1 AND DivisionID=12 ORDER BY RAND() LIMIT 1
Around 80% of the time I will receive a result of something like {"Name":"Christoph"} but 1 out of 10 returns nothing.
If someone is having problems with fetch_assoc() returning "Undefined index":
Check the indexes names (database Column name) - they are case sensitive.
Example:
For "SELECT Name FROM..." Your code must be $row["Name"]. Not NAME or name.
In your query, you are checking if the number of rows is greater than zero, but you are not doing anything to check if the value that is returned is Null. The behaviour that you are describing matches the scenario of at least 1 row in 'Name' that has a NULL value.
Note that I am not going to comment on your code structure or syntax here, but I have changed your response values to help identify / prove that a null value is the issue here.
Also, if your query is limited to a single row, then the while loop will only iterate once.
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// Echo out the values for Name in the result set
if(is_null($row["Name"], ))
echo '[NULL]';
else
echo $row["Name"];
// your application logic ;)
$returnable = $row;
}
} else {
return "no rows";
}
Please consider using a SQL IDE like Toad for MySQL along side your development, then you can visually inspect your data for these issues without writing code hacks :)
Related
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 1 year ago.
The question is simple, I have a small database and what I would like to compare is a specific column.
Scenario:
Using PHP to get the result from a querie and getting the value:
$sql = "SELECT verified FROM user WHERE id = ?";
$stmt->bind_param("i", $id);
$stmt->execute();
verified is a tinyint, either 0 or 1.
So how using PHP could make an if statement which compares either the result of $stmt->execute(); is 0 or 1.
<? php if(mysqli_fetch_row($stmt) == 0) {
echo "Not verified"
} else {
echo "Verified"
}
PD: What I would like to know is how to compare and operate on a SQL query.
You are almost there, jus grab result, and then compare it:
$result = $stmt->get_result();
$row = $result->fetch_array(MYSQLI_ASSOC);
if($row['verified'] == 1){
echo 'verified';
}else{
echo 'not verified';
}
This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\xxx\dash.php on line 20
I am quite fairly new, and being a old-school coder, simply using mysql_result to grab such data, I am unaware of how to go about this. I have a class->function setup.
Line 20 of dash.php contains:
echo $user->GetVar('rank', 'Liam', $mysqli);
While, the function is:
function GetVar($var, $username, $mysqli)
{
$result = $mysqli->query("SELECT " . $var . " FROM users WHERE username = '" . $username . "' LIMIT 1");
return $result;
$result->close();
}
Now, to my understanding, I am meant to convert $result into a string, but I am not fully aware of how to do so. I've tried using a few methods, but to no avail. So I've come to the community to hopefully get a answer, I've also looked around but noticed that all other threads are asking for num_rows, while I just want to grab the string from the query select.
You have to fetch it first before echoing the results. Rough Example:
function GetVar($var, $username, $mysqli) {
// make the query
$query = $mysqli->query("SELECT ".$var." FROM users WHERE username = '".$username."' LIMIT 1");
$result = $query->fetch_assoc(); // fetch it first
return $result[$var];
}
Then use your function:
echo $user->GetVar('rank', 'Liam', $mysqli);
Important Note: Since you're starting out, kindly check about prepared statements. Don't directly append user input on your query.
if ($result = $mysqli->query($query)) {
while($row = $result->fetch_object()) {
echo row['column_name'];
}
}
$result->close();
where you see 'column_name put the name of the column you want to get the string from.
This question already has answers here:
php warning: mysqli_close() expects parameter 1 to be mysqli
(2 answers)
Closed 2 years ago.
I am having a slight problem when I try to connect to a db remotely and I would be really grateful for any tips. Here is the code:
$con=mysqli_connect($port, $username, $password, $database);
$sql = "SELECT name, date FROM `view_tickets`;";
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
mysqli_close($result);
mysqli_close($con);
I want to result in json to be able to run this from a mobile app. At the moment nothing is displaying on the browser (I am running Xampp). I added some prints and can confirm that the connection is successful and the array is being filled properly. I managed to print it out using print_r(array_values($resultArray));
Is something wrong with my json?
I don't know if this helps but noticed that I am getting the following warning;
Warning: mysqli_close() expects parameter 1 to be mysqli, object given in /Applications/XAMPP/xamppfiles/htdocs/www/service.php on line 39
This corresponds to mysqli_close($result);
Any ideas?
Here is optimised version of your code.
Note that tempArray is remove (there is no need of it)..
mysqli_close($result) is replaced with unset($result) because $result is not a connection object. How ever unsetting is not required if this is the end of your code because after the end of the script php will unset all variables by it self..
$con=mysqli_connect($port, $username, $password, $database);
$sql = "SELECT name, date FROM `view_tickets`;";
$resultArray = array();
if ($result = mysqli_query($con, $sql)) {
// Loop through each row in the result set
while($row = $result->fetch_object()){
$resultArray[] = $row;
}
}
unset($result);
mysqli_close($con);
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
The mysqli_close needs to connection given to close, but you're give the function your result from your Query!
Change it to
mysqli_close($con);
Then it should be working, if not just comment
I had an issue with the encoding of the character set. Databases can have different encoding, make sure it is utf8
This question already has answers here:
How to check if mysql database exists
(23 answers)
Closed 8 years ago.
$pdo_mysql = new PDO("mysql:host=localhost", "ales", "alespass");
$result = $pdo_mysql->query("SHOW DATABASES LIKE `dbname`");
if ($result) { //not work.
print "no";
} else {
print "yes";
}
You can not use CREATE DATABASE IF NOT EXISTS or new PDO("mysql:host=localhost;db=dbname" ...
You have a typo error in your comment on #robin s answer, I think the condition should be if (!empty($result)) with that exclamation mark. It is printing not exists because $result is not empty when database exists. Therefore using this $result = $pdo_mysql->query("SHOW DATABASES LIKE '" . DB_NAME . "'"); if (!empty($result)) { print "exists"; } else { print "no exists"; } should work. I hope that helps
Manual:
PDO::query() returns a PDOStatement object, or FALSE on failure.
Your query is valid and should never fail (ignoring possible lower level issues).
$result will always evaluate to TRUE-ish, so the flow will always enter the if ($result) block.
(if (empty($result)) makes little to no sense)
You need to check whether the query returns zero row (zero result is not an error).
On second thought:
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
It is safer to do something like this:
if ($result->fetch() === FALSE) {
// result set is empty
}
CREATE DATABASE IF NOT EXISTS
should do the trick. If it doesn't, check for the existence first via
SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'dbname'
it will return you the database name itself, so you can check if the count of the query is > 0, the result is != 0...and so on. However you like.
The problem with your queries is the wrong use of backticks, you need to use single quotes, not backticks.
' instead of `
I'm trying to check if a row exist in my db like this:
$uid = $_GET['queryString'];
if(isset($_GET['queryString'])) {
echo "New: ".$uid."<BR>";
$query = "SELECT * FROM stuff WHERE $uid";
// Escape Query
$queryE = $db->real_escape_string($query);
$results = $db->query($queryE);
if(($results->num_rows) > 0) {
echo "NO!";
}
else
{
echo "Make new row";
}
}
else
{
echo 'Error!';
}
But I keep getting the error: Trying to get property of non-object in ....
So if it exist I do one thing, if it doesn't I do the other, i've been searching for about an hour to find the cause, maybe I'm mixing up old PHP4 with my PHP5 stuff?
I've tried a lot, tried some examples but tend to get the error: mysql_fetch_array() expects parameter 1 to be resource, string given
Or should I check it in the query itself?
What line is the error on?!
If it is on the real_escape_string line, you haven't instantiated $db properly.
If it is on the $results->num_rows line, try changing
$results = $db->query($queryE); to:
if(!($results = $db->query($queryE))) {
echo 'Make new row';
} else {
// user likely exists, check $results
}
Also, you need to clean up the way you check the query string -- just process the query variable you want, rather than the whole string. Suggest also to use a different name for the query variable and the table column.