PHP: populate MySQL table with result of anagram creation - php

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.

Related

mysqli_query(): Empty query in line

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);
?>

Running MySQL queries inside a loop

I want to run multiple mysql queries in a loop. Maybe this the wrong approach but thats why I'm asking.
Example:
A user submits a array of userinput and i want loop through it an perform multiple mysql queries. If I hardcode the ID it works but if I set the ID as a VAR it dosen't. When using a VAR it alway shows a result with the last entry.
Best, Tim
if(isset($_POST['list'])){
$list=$_POST['list'];
$list_arr=explode(PHP_EOL, $list);
$list_arr_len=count($list_arr);
for ($i=0; $i < $list_arr_len; $i++) {
echo $list_arr[$i]."<br>";
$result = mysqli_query($con,"SELECT col FROM table where id='$list_arr[$i]'");
$row=mysqli_fetch_array($result,MYSQLI_NUM);
echo $row[0]."<br>";
}
mysqli_close($con);
}
You can do it in one query like this:
if(!empty($_POST['list'])){
$list=$_POST['list'];
$list_arr=explode(PHP_EOL, $list);
$list_id=implode("', '", array_map('mysqli_real_escape_string', $list_arr));
$result = mysqli_query($con,"SELECT col FROM table where id IN ('{$list_id}')");
while($row=mysqli_fetch_array($result,MYSQLI_NUM)) {
echo $row[0]."<br>";
}
mysqli_close($con);
}
in this example no matter which type of colum for id u use
Create PDO object and set it in exception mode
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try
{
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
You are posting a comma separated list (I'd post an array but what the hell), so we're going to simply parse the string into integers and stick it in MySQL's IN clause
if(isset($_POST['list']))
{
$list = str_replace(["\r", "\n"], "", $_POST['list']);
$numbers = strpos($list, ',') !== false ? explode(",", $list) : (int)$list;
// This can probably bet written nicer, the idea is to have each number explicitly typecast to int so it's safe to stick in a query directly
// Basically, you want "1,2,3,4,5" without the possibility of having some bad input here
if(is_array($numbers))
{
$numbers = implode(",", array_map(function($number)
{
return (int)$number;
}, $numbers));
}
// And the nice, one liner, where you query and fetch the records which are now in the array called $records
$records = $pdo->query(sprintf("SELECT * FROM your_table WHERE id IN(%s)", $numbers))->fetchAll(PDO::FETCH_ASSOC);
}
Note: I didn't test the code so don't copy paste it, it most likely contains errors. I wrote the answer to show how easy it is to use PDO and retrieve results easily, in one liner.
I think this shall work:
$result = mysqli_query($con,"SELECT col FROM table where id=".mysqli_real_escape_string($list_arr[$i])."");
First Create a string of all the ids and use IN(String of Ids) in your query and store all the data corresponding to id in an array.
$stringIds = "";
for ($i=0; $i < $list_arr_len; $i++)
{
if (is_null($stringIds))
{
$stringIds = '"' . $list_arr[$i] . '"';
}
else
{
$stringIds .= ',"' . $list_arr[$i] . '"';
}
}
$resulSet = mysqli_query($con, ""SELECT col FROM table where id='?'"");
while($row = mysqli_fetch_assoc($resulSet))
{
mainArray[$row['id']] = $row;
}
Now, your able to fetch all your data from the array using foreach loop and please use PDO to avoid SQL Injection.
Problem was:
\n \r
This c0de works for me now ( also IN('') might be the better idea ):
if(isset($_POST['list'])){
$list=$_POST['list'];
//echo $list;
$replace = array("\n", "\r");
$id = str_replace( $replace, ",", $list);
$id_arr = explode(",", $id);
$id_arr_len = count($id_arr);
for ($i=0; $i < $id_arr_len; $i++) {
# code...
$result = mysqli_query($con,"SELECT col1,col2 FROM table where id='$id_arr[$i]'");
while($row = mysqli_fetch_assoc($result)){
echo $row['col1'].': ';
echo $row['col2'].'<br/>';
}
}
}

Why my text file is filling with values of data from database in php?

Here is my PHP code:
<?php
$fh = fopen('mytest.txt', 'w');
$con = mysqli_connect("some.host.com", "username", "password", "database");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con, "database");
$result = mysqli_query($con, "SELECT * FROM Apri_score");
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$num = mysqli_num_fields($result);
$last = $num - 1;
for ($i = 0; $i < $num; $i++) {
fwrite($fh, $row[$i]);
if ($i != $last) {
fwrite($fh, ",");
}
}
fwrite($fh, "\n");
}
fclose($fh);
?>
The mytest.txt file is getting filled with commas but no data. I cannot understand why this is happening.
Your problem is you are using mysqli_fetch_array(), with a second parameter of MYSQLI_ASSOC. This will assign $row with array keys containing the column names. You are accessing them with numeric indexes from $i in your for loop.
Change it to either mysqli_fetch_row($result) or use mysqli_fetch_array() with the second parameter of MYSQLI_NUM which will return the array with numeric indexes.

Function in for () loop: Fatal error: Cannot redeclare

I have this code, but when I try to execute it, it gives the following error:
Fatal error: Cannot redeclare genereerLiveCodeP() (previously declared in livestream.php:33) in livestream.php on line 32.
session_start();
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//header("location: index.php");
if($_SESSION['***'] == '***'){
$fp = fopen("test.html", 'w');
fwrite($fp, "");
fwrite($fp, '<p class="green">*** is online</p>');
$result = mysql_query("select count(1) FROM ***");
$row = mysql_fetch_array($result);
$rows = $row[0]+1000;
echo "Rows: ".$rows."\n";
for ($id = 1000; $id < $rows; $id++) {
echo "ID: ".$id."\n";
function genereerLiveCodeP () {
$lengthCode = 6;
$characters = '1234567890abcdefghijklmnopqrstuvwxyz';
$liveCodeFunction = '';
for ($p = 0; $p < $lengthCode; $p++) {
$liveCodeFunction .= $characters[mt_rand(0, strlen($characters))];
}
return $liveCodeFunction;
}
$livecode = genereerLiveCodeP ();
echo "Livecode: ".$livecode."\n";
$x = mysql_query("UPDATE *** SET livecode='".$livecode."' WHERE *** = '".$***."'");
echo $x."\n";
}
}
What should I do?
You forgot to close the for loop before declaring the function. Your code should look like this:
...
for ($id = 1000; $id < $rows; $id++) {
echo "ID: ".$id."\n";
}
function genereerLiveCodeP () {
...
Firstly, you are using a deprecated extension (ext/mysql).
You need to move your function outside of the for loop. PHP doesn't work that way (redeclaring a function isn't possible, hence the error)
You can get a bigger boost in performance if you use a prepared query, and have far more future-proof code (your code will break in PHP 5.5 when those functions start throwing errors)
session_start();
$db = new mysqli($host, $username, $password, $db_name);
function generate_live_code($length = 6) {
$characters = '1234567890abcdefghijklmnopqrstuvwxyz';
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= $characters[mt_rand(0, strlen($characters))];
}
return $str;
}
//header("location: index.php");
if($_SESSION['id'] == 'debug') {
$fp = fopen("test.html", 'w');
fwrite($fp, "");
fwrite($fp, '<p class="green">*** is online</p>');
// writing html to a file? consider using a database...
$result = $db->query("select count(1) FROM x");
$row = $result->fetch_assoc($result);
$rows = $row[0]+1000;
echo "Rows: $rows\n"; // no need to concat with double quotes.
if ($query = $db->prepare("UPDATE x SET livecode = ? WHERE id = ?")) {
for ($id = 1000; $id < $rows; $id++) {
echo "ID: ".$id."\n";
$livecode = generate_live_code();
echo "Livecode: $livecode\n";
$query->bind_param("si", $livecode, $id);
$query->execute();
}
}
}
You are declaring function genereerLiveCodeP() inside a loop, try to put it at the beginning of the file.

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