mysqli_query(): Empty query in line - php

I'm confused by xcode and php due to the fact that the exact same code, which works within the iOS simulator, doesn't work for the iPhone itself.
The php file looks like the following:
<?php
$con=mysqli_connect("localhost","BLACKEDOUT","BLACKEDOUT","BLACKEDOUT" );
$array = json_decode($_POST["identifier"]);
for($i=0; $i < count($array); $i++)
{
$name = $array[$i][1];
for($j=0; $j < count($array[$i][0]); $j++)
{
$nummer = $array[$i][0][$j];
$query = "SELECT x FROM Z WHERE uniqueID = $nummer";
$dbConn = new PDO('mysql:host=localhost;dbname=BLACKEDOUT', "BLACKOUT", "BLACKEDOUT");
$smt = $dbConn->prepare($query);
$smt->bindParam(1, $phone_num );
$smt->execute();
if($smt->rowCount())
{
$ergebnisArray[] = [$name,$nummer];
}
else
{
}
}
}
echo json_encode($ergebnisArray);
mysqli_query($con, $query) or die ("Could not connect to server");
mysqli_close($con);
?>
When running the code in the iOS simulator it's all fine, but when I run it on my device it says: as the response string in Xcode: "mysqli_query(): Empty query in on line 30". When I work around that error, I don't get the result I expect either.
Every help is greatly appreciated!

Note, that you use BLACKOUT and BLACKEDOUT mixed, and you never use $con. Also, be aware that you define $query inside a loop, so when it iterates zero times, $query never gets defined, thus cannot by used in mysqli_query.
Try this and come back with the result:
<?php
$array = json_decode($_POST["identifier"]);
for($i=0; $i < count($array); $i++)
{
$name = $array[$i][1];
for($j=0; $j < count($array[$i][0]); $j++)
{
$nummer = $array[$i][0][$j];
$query = "SELECT x FROM Z WHERE uniqueID = '".$nummer."'";
$dbConn = new PDO('mysql:host=localhost;dbname=BLACKEDOUT', "BLACKOUT", "BLACKEDOUT");
$smt = $dbConn->prepare($query);
$smt->bindParam(1, $phone_num );
$smt->execute();
if($smt->rowCount())
{
$ergebnisArray[] = [$name,$nummer];
}
else
{
}
}
}
echo json_encode($ergebnisArray);
?>

Related

PHP: populate MySQL table with result of anagram creation

I am trying to populate a MySQL table with the result of a function to create anagrams from a given word. There is simply no result at all. I even do not get an error message.
<?php
//connect to your database
$conn = mysqli_connect("localhost","dbuser","3423423sfdfsdf","mydb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$input = $trimmed;
function string_getpermutations($prefix, $characters, &$permutations)
{
if (count($characters) == 1)
$permutations[] = $prefix . array_pop($characters);
else
{
for ($i = 0; $i < count($characters); $i++)
{
$tmp = $characters;
unset($tmp[$i]);
string_getpermutations($prefix . $characters[$i], array_values($tmp), $permutations);
}
}
}
$characters = array();
for ($i = 0; $i < strlen($input); $i++)
$characters[] = $input[$i];
$permutations = array();
string_getpermutations("", $characters, $permutations);
foreach($permutations as $result) {echo $result,'<br>';}
foreach($permutations as $result) {mysqli_query($conn,"INSERT INTO tempanagram (anagram) VALUES ('$result')");}
?>
You can also use mysqli, but best solution is using some query builders.
Add to your code error reporting for PHP and MYSQL
<?php
error_reporting(E_ALL);
ini_set('display_errors', true)
mysql_query($sql, $conn) or die('ERROR: '.mysqli_error($conn));
More info in http://php.net/manual/en/mysqli.error.php
You can optimize your code to make 1 insert query by using bulk insert, something like this:
<?php
$sql = 'INSERT INTO tempanagram (anagram) VALUES ("'.join('"),("', $permutations).'")';
I got the solution:
Instead of foreach($permutations as $result) {mysqli_query("INSERT INTO tempanagram (anagram) VALUES ('$result')");}
I had to write:
foreach($permutations as $result) {mysqli_query($conn,"INSERT INTO tempanagram (anagram) VALUES ('$result')");}
Otherwise it is apparently not clear that I am referring to that connection.
All the other hints are very valuable. Thanks very much to everybody.

How do I display content with PDO based on num_rows?

Apparently, the num_rows property does not work in PDO as it would with mysqli.
Normally, with mysqli, my code would look like this:
<?php
$conn = new mysqli('127.0.0.1','root','mypassword','mydbname');
if($conn->connect_errno){
die("Sorry, could not connect.");
}
$id = 1;
$qry = "SELECT * FROM customers WHERE id = ?";
$getCustomers = $conn->prepare($qry);
$getCustomers->bind_param("i",$id);
$getCustomers->execute();
$result = $getCustomers->get_result();
$count = $result->num_rows;
if($count == 0){
echo "Sorry, there are no results";
}else{
while($row = $result->fetch_object()){
echo $row->id;
echo $row->fname;
echo $row->lname;
echo $row->entry_date;
}
}
?>
How do I create the equivalent with PDO? Here is what I have tried so far:
<?php
try{
$conn = new PDO('mysql:host=127.0.0.1;dbname=mydbname','root','mypassword');
}catch(PDOException $e){
echo $e;
}
$id = 1;
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$rows = $qry->fetchAll(PDO::FETCH_OBJ);
$count = count($rows);
if($count == 0){
echo "Sorry, there are no results for your criteria";
}else{
for($i = 0; $i < $count; $i++){
echo $rows->fname;
}
}
?>
Yeah isn't PDO great ;p no need to count rows when you have already got them.
To loop over your result as you have an array.
Change:
for ($i = 0; $i < $count; $i++){
echo $rows->fname;
}
To:
for ($i = 0; $i < $count; $i++){
echo $rows[$i]->fname;
}
Or better just use a foreach.
foreach ($rows as $row) {
echo $row->fname;
}
The statement
fetchAll(PDO::FETCH_OBJ) returns an array containing all of the result set rows as described here. To get the size of the array use sizeof($count). That should give you the size of the array.
To answer your question specifically. You can use rowCount() to retrieve the number of rows in a result:
$qry = $conn->prepare("SELECT * FROM customers WHERE id = :id");
$qry->execute([':id'=>$id]);
$count = $qry->rowCount();
$rows = $qry->fetchAll(PDO::FETCH_ASSOC); //my personal preference
for($i=0; $i < $count; $i++) {
echo $rows[$i]['fname'];
}
To more closely replicate your mysqli code:
while($row = $qry->fetch(PDO::FETCH_OBJ) {
echo $row->fname;
}
Of course, you should always check $conn->errorCode() after each database execution to ensure something go sideways on you.
UPDATE:
As Lawrence points out, rowCount() does not work with MS SQL Server. An alternative in that case is to use fetchAll() and count().

PHP MySQL generating unique random number

I don't understand why my code isn't working. The connection works and everything else however when I try to generate a unique random number and check from the MySQL if the number is there it still prints out a random number but it's not UNIQUE. Could anyone help me thx?
Here's my code:
$num = rand(1,5);
$sel_query = "SELECT * FROM test";
$result2 = $con->query($sel_query);
$i = 1;
for (;$i<2; $i++)
{
while($row = mysqli_fetch_array($result2))
{
if ($row['id'] == $num)
{
$num = rand(1,5);
$i = 0;
}
}
}
This should work:
$is_unique = false;
$num = false;
while (!$is_unique){
$num = rand(1,5);
$sel_query = "SELECT id from test where id = " . $num;
$result2 = $con->query($sel_query) or die($conn->error);
if (!mysqli_fetch_array($result2)){
$is_unique = true;
}
}
echo "Unique number is " . $num;
But if there aren't any more possible unique numbers, it will loop forever.
I know this is a bit old, but I found this question after needing a similar answer. I've taken Jodes's answer and updated it slightly, so that it won't run forever, is a function that returns the number, and accepts a mysqli connection as $mysqli:
function getUniqueNumber($mysqli)
{
$is_unique = false;
$num = false;
$times_run = 0;
while (!$is_unique)
{
if($times_run > 10)
{
echo "Run too many times, dying.";
die();
}
$num = rand(1,5);
$sel_query = "SELECT id from test where id = " . $num;
$result2 = $mysqli->query($sel_query) or die($mysqli->error);
if (!mysqli_fetch_array($result2))
{
$is_unique = true;
}
$times_run++;
}
return $num;
}

MySQLi not returning rows in order

This is probably not a very difficult question to answer. I'm having trouble with this PHP function I wrote... it returns the rows line by line, but it's returning them incremented by 4 each time. So the the 1st row will output, then the 5th, then the 9th...
function showDatabases() {
# $_GET variables from the URL.
$database = mysql_real_escape_string($_GET['database']);
$table = mysql_real_escape_string($_GET['table']);
$mysqli = new mysqli('127.0.0.1', 'root', '', $database);
$query_one = $mysqli->query("SELECT * from $table");
$num_rows = mysqli_num_rows($query_one);
$num_fields = mysqli_num_fields($query_one);
for ($x = 0; $x < $num_rows; $x++) {
for ($c = 0; $c < $num_fields; $c++) {
$row = mysqli_fetch_row($query_one);
echo($row[$c]." ");
}
echo("<br/>");
}
}
Thanks!
mysqli_fetch_row fetched an entire row and moves the pointer to the following row. You should call it only once per each row; now you are calling it once per column.
That is,
for ($x = 0; $x < $num_rows; $x++) {
$row = mysqli_fetch_row($query_one);
for ($c = 0; $c < $num_fields; $c++) {
echo($row[$c]." ");
}
echo("<br/>");
}
you are complicating things
you can do it with just one loop
$query = "SELECT * from $table";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row['fieldname']." ";
}
}
I advice you to add order by some time the default order is not the id order.

Reading only one row from mysql when there are two

I need the script to output both rows. However, I can only get it to output the first one. Help please!
Here is my code:
<?php
$server = ""; // assume server name
$connect = mysqli_connect($server,,,) //assume password etc.
or die ("Couldn't connect to server"); //connect to admin database
$query = "SELECT mt FROM Content";
$result = mysqli_query($connect, $query)
or die ('Could not execute query.');
$nrows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$i = 0;
while ($i <= 30)
{
echo $row[$i];
$i++;
}
?>
You need to fetch into a row in a loop:
while ($row = mysqli_fetch_array($result)) { ...
Try to type:
while( $row = mysqli_fetch_array($result) )
{
echo $row[$i];
$i++;
}
You only fetch the first row.
You should do a while loop on your mysqli_fetch_array() to get both rows.
while ($row = mysqli_fetch_array($result)) {
for ($i = 0; $i < 30; $i++) {
echo $row[$i];
}
}
That should do it (like some of the other posted while I was writing but they forgot parts of the answer :-)
But I think that you should use the OO way of using mysqli.
You could use mysqli_fetch_all() to fetch all of the records.

Categories