Removing unwanted codes from mysgli query result - php

please help.
I was trying to query a mysqli database to display part of my blog articles on my main page using php. It output a messy character as shown on the link. www.myimcm.com (unwanted commas and stuffs like that. The simple code for this was:
$q ="SELECT SUBSTRING_INDEX(post_content,' ',130) AS post,(post_title) AS title,ID AS id FROM wp_posts WHERE post_type='post' ORDER BY post_date DESC LIMIT 1";
$r = #mysqli_query ($dbc, $q); // Run the query.
if ($r) { // If it ran OK, display the records.
echo '<h2>LATEST FROM OUR GUIDES</h2>';
// Fetch and print all the records:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo"<p class='title'>". ($row['title'])."</p>";
echo nl2br($row['post']);
echo ' Continue reading';
}
mysqli_free_result ($r); // Free up the resources.
} else { // If it did not run OK.
// Public message:
echo '<p class="error">The are no latest from our blog. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbc); // Close the database connection.

use utf-8 encoding in your webpages.
Use this code in your head section.
header("Content-Type: text/html; charset=utf-8");

Your page claims to be encoded in UTF-8, but that is not true. It contains the following octets: 85, 91, 92, a0 which (on their own) are not valid UTF-8.
They are probably from one of the Windows-125x character encodings, such as Windows-1252.
You need to set up your database to use the correct character encoding for the Database, Table, and connection. See the MySQL manual and PHP manual for details.

Related

PHP->JSON Encoding not working

I know this has been asked like a million times now.
I tried several solutions I found here but still it doesn't work for me.
What i want to do is SELECT Values out of a simple MySQL Table.
The Values are inserted every five minutes by a program I have written.
I catches all mp3 files in a selected folder and inserts its ID3 Tags into the Table tb_song.
These files should then be SELECTED with the PHP Script and an Android App should Play these files with their URL.
The Database and PHP Code works.
If I just echo all selected values it works fine.
But converting and printing out the encoded array just throws an blank screen.
Could it be that JSON Objects are limited to size?
I've got about 500 entries in tb_song.
Here's my code.
<?php
require_once('config.php');
$connection=new mysqli($server,$user,$password,$database);
$songs=array();
$sql=("SELECT Title,Artist,Album FROM tb_song");
$result=$connection->query($sql);
while($row=$result->fetch_assoc())
{
$temp=array();
$temp['Title']=$row['Title'];
$temp['Artist']=$row['Artist'];
$temp['Album']=$row['Album'];
array_push($songs,$temp);
}
json_encode($songs);
echo(json_encode($songs));//just for testing purposes
$connection->close();
?>
You can distil your code down to this. Plus adding some error checking!
<?php
/* add next 2 lines while testing,
especially if you are using a live hosting site
where error reportinf will be turned off
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'config.php';
$connection = new mysqli($server,$user,$password,$database);
// Check connection is good
if ($connection->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $connection->connect_error);
}
$songs=array();
$sql = 'SELECT Title,Artist,Album FROM tb_song';
$result = $connection->query($sql);
if ( ! $result ) {
echo $connection->error;
exit;
}
while($row=$result->fetch_assoc()) {
$songs[] = $row;
}
$jstring = json_encode($songs);
if ( json_last_error() > 0 ) {
file_put_contents('json-output.txt', json_last_error_msg());
}
echo $jstring;
//add this line for testing
file_put_contents('json-output.txt', $jstring);
exit;
?>
I finally figured it out.
I guess this is not the standard which's happening to all people but anyway.
Before I'll post my code I want to say a few things for people who are running into the same problem:
Make sure you're only passing strings without 'ä','ü' or whatever letter that is not in the english alphabet.
You need to give your JSON Object a Name, otherwise it could cause problems.
<?php
require_once 'config.php';
$connection = new mysqli($server,$user,$password,$database);
if ($connection->connect_error) {
die('Connect Error (' . $connection->connect_errno . ') '
. $connection->connect_error);
}
$songs=array();//Create Array
$sql = 'SELECT * FROM tb_song';
$result = $connection->query($sql);
while($row=$result->fetch_assoc()){
array_push($songs,$row);//Insert $row in $songs
}
echo json_encode(array('Songs'=>$songs));//Giving JSON Object a proper Name and //encode
$connection->close();
?>

Assistance with PHP and MYSQL

I have code here that is supposed to print a html table from my mysql database. When I open the page in my web browser, it is a blank page.
<html>
<body>
<?php
$connection = mysql_connect('localhost', 'admin', 'may122000');
mysql_select_db('contacts');
$query = "SELECT * FROM users";
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
echo "</table>";
mysql_close();
?>
</body>
</html>
Remove password
Enable error output
When you use mysql_fetch_array you will get the resulting array with numeric indices.
mysql_fetch_assoc will give you an associative array, like you want.
Note: mysql_* is deprecated.
while($row = mysql_fetch_assoc($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
If you still want to use mysql_fetch_array you'll have to pass a second parameter:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
First of all user mysqli or PDO and mysqli_fetch_assoc() so you have only associative array. Blank page is probably result of a hidden error, that's stored in your error.log on your server - take a look at it and get back to us.
I prefer using PDO or mysqli but anyway , Are u sure Your connection is established ? to check this and check other connections and query :
if (!connection)
die(mysql_error());
try this and feedback me
Improvements - some of which already mentioned in other post but all put together in one form:
<?php
$connection = mysqli_connect('localhost', 'admin', '****', 'contacts');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT first_name, last_name, phone FROM users";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
echo "<table>"; // start a table tag in the HTML
while($row = mysqli_fetch_array($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
echo "</table>";
mysqli_close($connection);
?>
So, first off the MySQL_* has been upgraded to Mysqli, with some minor reformatting,
The select * has been replaced with selecting only the needed columns.
The closing statement has been correctly set.
Firstly if your connection fails an error catch will output this to the screen. Remove this upon product launch or public launch of the page.
A (Rather rudimentary) error catch has been put in that if the SQL Query is bad that an error is outputted. Again, this should be removed in production but will help you with finding SQL errors.
If No SQL errors return the you have either an empty table in your database, or some sort of PHP error but from the code sample given the most likely error is that your PHP doesn't run MySQL and would only run PDO or MySQLi.
You also said "when I open the page in my browser it is a blank page", if the Source of the page is blank - as in it DOES NOT show
<html>
etc, then this is a sign the PHP execution failed and you have bad PHP, as detailed in your error log file.
The most likely cause of this from the code sample given is, as stated already, your PHP version does not support MySQL.
If your
<table>
Tag appears in your HTML source code then this is a sign that the While clause is not running which means your Datbase table is empty and there is no data to output.
Hope this helps. But first point of call is to upgrade to MySQLi :)

mysql_fetch problems... I'm getting crazy

I'm sorry, probably somewhere there will be the answer to my question, but it's hours I'm looking for trying to resolve this problem:
Here is the code:
<?php
$con = mysql_connect("****","****","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("******", $con);
$query = "SELECT id FROM fq_questions";
$rowcnt = mysql_num_rows(mysql_query($query));
echo "Tot scenes: ".$rowcnt;
$id = rand (1,$rowcnt);
echo "<br>Id rand: ".$id."<br>";
flush();
$newquery = "SELECT question FROM fq_questions WHERE id=".$id;
$result = mysql_query($newquery);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $newquery;
die($message);
}
$row = mysql_fetch_assoc($result);
echo $row['question'];
mysql_close($con);
?>
The problem is that there is no output. I've tried everything, seems to be a problem into the query, but there is a result, it's not false, but even if it exists, nothing is outputted.
The code works till
echo "<br>Id rand: ".$id."<br>";
then it shows nothing.
It's a dummy problem, i'm getting crazy just because of it.
Uh, was forgetting... The website where I've got the problem: http://www.freelabs.it/filmquiz/game.php
Be careful, desc is a SQL keyword ! Your query may not compile because of that.
"desc" is a MySQL reserved word, you should just change that column name in your DB. Anyway, your method is not random at all, and it will fail as soon as you have a "hole" in your ids (when you delete one member).
Take a look at MySQL "ORDER BY RAND()"
$data = mysql_query("SELECT description FROM fq_questions ORDER BY RAND() LIMIT 1");
You used mysql_fetch_row() which returns a numerical array. You then try to access the array slot named 'desc'.
It doesn't exist. (My guess is that that produces a supressed error, preventing any output from showing up, or a supressed warning, preventing any output after that line from showing up.)
Try changing mysql_fetch_row() to mysql_fetch_assoc() (still DEPRECATED!) and that should be solved.
Sources: http://php.net/manual/en/function.mysql-fetch-row.php
And: http://php.net/manual/en/function.mysql-fetch-assoc.php

Having trouble displaying last update time of mySQL table

So I have a website and I am trying to display the last update time of the mySQL server, I've looked around but still having problems. Here is my code
$sql = 'SHOW TABLE STATUS FROM alumni LIKE "alumni_data"';
$tableStatus = mysqli_query($link, $sql);
if (!$tableStatus) {
$error = 'Error getting update status: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
while ($array = mysqli_fetch_array($tableStatus)) {
$updatetime = $array['Update_time'];
}
echo '<center>Last Updated: ' . $updatetime . '</center>';
What happens is nothing prints out, its like it never found the update time. I have manually typed that query so I am pretty sure it works.
Thanks

using a PHP script to return values from SQL table

I am attempting to search a SQL table from a PHP script. the SQL table is a word list and in the PHP I call a Python script to do the permutations of a given word. Everything is working until I actually go to execute the mysql_query. I need some formatting advice on how to pass so many values to a Select statement. From what I've seen it needs to be in the form ('a','b','c',...) and this is how it is formatted but I'm not getting a return on the actual execution.
<?php
ini_set('display_errors','On');
error_reporting(E_ALL);
$con= mysql_connect("127.0.0.1","app","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wordlookup");
//Retrieve the data.
$word = $_POST['data'];
$perm = exec("python comb.py $word");
$query="SELECT * FROM words WHERE IN (" .$perm. ")";
print $query;
$sql=mysql_query($query);
print $sql;
mysql_close($con);
?>
This is all of the PHP file, the output from the python call would be in the 'a','b','c'... format and the random prints are just debugging. The print $sql doesn't actually put out anything at the moment.
Thanks,
Kyle
SELECT * FROM words WHERE IN (...)
Your query is missing a condition. WHERE what IN ...? You need to fill in a column name there.
Further, if a query is not working, ask the database why it didn't work:
$result = mysql_query($query);
if (!$result) {
echo mysql_error();
}
Though solution is strange (use external script executed via exec to calculate permutations?), I'd answer your exact question.
$perm_arr = explode(' ', $perm);
function quote($str) { return "'$str'"; }
$perm_arr = array_map('quote', $perm_arr);
$sql = "select * from words where word in (" . join(', ', $perm_arr) . ")";

Categories