Returning just data from mysqli query - php

I am trying to receive data back from a mysql db but in my results I receive escape characters. How can I get rid of these and just return raw data (I'm a noob in this realm of coding so please keep that in mind)?
Here is a sample of my result (it's a json signature):
{"signature":"\n\t\t\t[{\"lx\":16,\"ly\":16,\"mx\":16,\"my\":15},{\"lx\":16,\"ly\":17,\"mx\":16,\"my\":16},{\"lx\":16,\"ly\":18,\"mx\":16,\"my\":17},{\"lx\":16,\"ly\":20,\"mx\":16,\"my\":18},{\"lx\":16,\"ly\":21,\"mx\":16,\"my\":20},{\"lx\":16,\"ly\":22,\"mx\":16,\"my\":21},{\"lx\":16,\"ly\":25,\"mx\":16,\"my\":22},{\"lx\":16,\"ly\":26,\"mx\":16,\"my\":25},.....]\n\t\t\t"}
I would like to remove the: {"signature":"\n\t\t\t on the beginning and \n\t\t\t"} on the end automatically.
Any help is greatly appreciated!
<?php
{
// Connect to MySQL
$mysqli = new mysqli( 'localhost', 'root', 'rootpassword', 'crs' );
//Check our connection_aborted
if ($mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_error );
}
//Read the signature
$sql = "SELECT signature FROM rescue_forms WHERE id=53";
$idresult = $mysqli->query($sql);
while($row = mysqli_fetch_assoc($idresults))
$id = $row;
//Just printing this so I can see the results.
print json_encode($id);
//sending this to a statement below.
$json = json_encode($id);
//Close connection
$mysqli->close();
}
?>

You are storing json in a database, which you shouldn't,
and for some reason you are encoding your json again, which is pointless.

In a round about way of down voting my question and basically telling me I'm an idiot, it helped! (which is the point of the forum) In hopes that this might help someone else that might just be starting out coding this kind of thing. I was able to change my array around to get the raw data as I was expecting, here's my example:
<?php
{
// Connect to MySQL
$mysqli = new mysqli( 'localhost', 'root', 'rootpassword', 'crs' );
//Check our connection_aborted
if ($mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_error );
}
//Read the signature
$sql = "SELECT signature FROM rescue_forms WHERE id=53";
$idresult = $mysqli->query($sql);
while($sig=mysqli_fetch_assoc($idresult)){
echo "<tr>";
echo "<td>".$sig['signature']."</td>";
echo "</tr>";
}
//Close connection
$mysqli->close();
}
?>
Thank you to all that responded it was greatly appreciated! Also thank you #YourCommonSense for showing me the proper way to format my code in this window with your edit.

Related

Trying to insert data into a database using PHP / Mysqli

I'm trying to execute an Insert query to write data into a Database. I'm using Mysqli and PHP.
The code looks OK for me. However, every time I go to the webpage to check if the form works, the query gets executed an a new row is created in the DB (empty).
I'm pretty sure there is something wrong with the last if statement. Could you advise?
BTW, the snippet is only for the PHP to execute the sql query, since the form is working just fine.
Thanks!
$servername = "localhost";
$username = "root";
$password = "mysqlpassword";
$dbname = "bowieDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$album = $_POST['album'];
$relyear = $_POST['relyear'];
$label = $_POST['label'];
$chart = $_POST['chart'];
$track1 = $_POST['track1'];
$track2 = $_POST['track2'];
$track3 = $_POST['track3'];
$track4 = $_POST['track4'];
$track5 = $_POST['track5'];
$sql = "INSERT INTO Albums (album, relyear, label, chart, track1, track2, track3, track4, track5)
VALUES ('$album', '$relyear', '$label', '$chart', '$track1', '$track2', '$track3', '$track4', '$track5')";
$result = mysqli_query($conn, $sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
You are mixing Procedural and Object Orientated SQL interactions.
This is Procedural:
$result = mysqli_query($conn, $sql);
This is Object Orientated:
$conn->query($sql)
You can not use both with the same connection details, you should do one or the other throughout your code. The best one to use is Object Orientated approach, so rework the Procedural code to:
$result = $conn->query($sql);
if ($result) {
...
So actually you can simply remove the line starting $result = ... and let the IF statement query you already have handle itself.
Other notes:
Use MySQL error feedback such as checking if(!empty($conn->error)){print $conn->error;} after SQL statements. See example code below...
Use the following PHP error feedback too, set at the very top of your PHP page:
...
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
you need to read up and be aware of SQL injection that can destory your database should someone POST data that also happens to be MySQL commands such as DROP.
Code for Comment:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
//run SQL query you already have coded and assume
// that the form has been filled in.
$result = $conn->query($sql);
if ($result) {
//all ok
}
if(!empty($conn->error)) {
print "SQL Error: ".$conn->error;
}
}
use
1. if(isset($_POST['Submit'])){//your code here }
and
2. if($result){...
if you are using procedural method

SQL Server Database Query with PHP

I need to get some data from a Microsoft SQL Server database at work. When I have the data I need, I need to make an Excel spreadsheet that can be saved locally on my computer.
I found PHPExcel which seems to do the job on the Excel part, but what about getting the data from the Database?
I can't seem to find anything that's recent. Only old tutorials.
Use this way to Fetch the Records :
<?php
$hostname = "192.168.3.50";
$username = "sa";
$password = "123456";
$dbName = "yourdb";
MSSQL_CONNECT($hostname,$username,$password) or DIE("DATABASE FAILED TO RESPOND.");
mssql_select_db($dbName) or DIE("Database unavailable");
$query = "SELECT * FROM dbo.table";
$result = mssql_query( $query );
for ($i = 0; $i < mssql_num_rows( $result ); ++$i)
{
$line = mssql_fetch_row($result);
print( "$line[0] - $line[1]\n");
}
?>
This will fetch each rows from the Data Retrieve and Print on the Page. Use your Required format into that. I mean, Use html Table to show the data in well format.
Use this code to get an data from Database.
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = '192.168.3.50';
// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'sa');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
else{
echo "connected ";
mssql_select_db('Matrix') or die("Wrong DATAbase");
//mssql_query("SELECT Seq_no from dbo.Trans_R WHERE Seq_no = 000001",$link) or die("cannot execute the query");
$query = mssql_query("SELECT Tr_Date,Tr_Time,Tr_Data from Matrix.dbo.Trans_R");
$f = mssql_fetch_array($query);
echo $f['Tr_Date'];
}
?>
Can i know why Negative Vote??
He asked me to :
" but what about getting the data from the Database?"

Querying a database with oop

I have connected to a database for the first time with oop and stright away come up with an issue, below is my code which i'm struggling with:
$q = 'SELECT * FROM test';
$sqli->query($q);
if($sqli->query($q)){
echo "worked";
}
if($sqli->error){
echo $sqli->error;
}
I have checked for errors when connecting to the db and that works fine, but when I run this query I get no output, why? I expected an error or "worked", but have got neither.
Whats happening?
I have put some comments in the source code to help:
$q = 'SELECT * FROM test';
//$sqli is the result of a
//new mysqli("localhost", "user", "password", "database");
$resource = $sqli->query($q); // this returns a resource or false
if(!$resource) {
echo $sqli->error;
die; // do not process further
}
// process the results
$rows = $resource->fetch_all();
if ($rows) { // check if there are rows
echo "worked";
}
else {
echo "query is ok, but there are no rows";
}
You could also use $resource->fetch_object() which returns an object for output. Therefore if you wanted to print specific data from the result set, you would do something like
//table test.Name and test.Country
while ($rowobj = $resource->fetch_object()){
printf ("%s (%s)\n", $rowobj->Name, $rowobj->Country);
}
Good luck,
You could use this method, I hope it's what you are looking for. You will need to define the DB first. Then you can connect in OOP and test the connection is true or exit();
Let me know if this works for you. You can also define the DB in an external file and just do an include(); towards the top of your script for any pages needing connection to the DB.
define("SERVER","IP Address");
define("USER","DB USERNAME");
define("PASSWORD","DB PASSWORD");
define("DATABASE","DB NAME");
// This is for connection
$mysqli = new mysqli(SERVER, USER, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
exit();
}

PHP database selection issue

I'm in a bit of a pickle with freshening up my PHP a bit, it's been about 3 years since I last coded in PHP. Any insights are welcomed! I'll give you as much information as I possibly can to resolve this error so here goes!
Files
config.php
database.php
news.php
BLnews.php
index.php
Includes
config.php -> news.php
database.php -> news.php
news.php -> BLnews.php
BLnews.php -> index.php
Now the problem with my current code is that the database connection is being made but my database refuses to be selected. The query I have should work but due to my database not getting selected it's kind of annoying to get any data exchange going!
config.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "test";
?>
database.php
<?php
class Database {
//-------------------------------------------
// Connects to the database
//-------------------------------------------
function connect() {
if (isset($dbhost) && isset($dbuser) && isset($dbpass) && isset($dbname)) {
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die("Could not connect: " . mysql_error());
$selected_db = mysql_select_db($dbname, $con) or die("Could not select test DB");
}
}// end function connect
} // end class Database
?>
News.php
<?php
// include the config file and database class
include 'config.php';
include 'database.php';
...
?>
BLnews.php
<?php
// include the news class
include 'news.php';
// create an instance of the Database class and call it $db
$db = new Database;
$db -> connect();
class BLnews {
function getNews() {
$sql = "SELECT * FROM news";
if (isset($sql)) {
$result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error());
}
return $result;
}
?>
index.php
<?php
...
include 'includes/BLnews.php';
$blNews = new BLnews();
$news = $blNews->getNews();
?>
...
<?php
while($row = mysql_fetch_array($news))
{
echo '<div class="post">';
echo '<h2> ' . $row["title"] .'</h2>';
echo '<p class="post-info">Posted by | <span class="date"> Posted on ' . $row["date"] . '</span></p>';
echo $row["content"];
echo '</div>';
}
?>
Well this is pretty much everything that should get the information going however due to the mysql_error in $result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error()); I can see the error and it says:
Could not execute query. Reason: No database selected
I honestly have no idea why it would not work and I've been fiddling with it for quite some time now. Help is most welcomed and I thank you in advance!
Greets
Lemon
The values you use in your functions aren't set with a value. You likely need to convert the variables used to $this->dbName etc or otherwise assign values to the variables used.
Edit for users comment about variables defined in config.php:
You really should attempt to get the data appropriate for each class inside that class. Ultimately your variables are available to your entire app, there's no telling at this point if the variable was changed by a file including config.php but before database.php is called.
I would use a debugging tool and verify the values of the variables or just var_dump() them before the call.
Your Database class methods connect and selectDb try to read from variables that are not set ($dbhost, $dbname, $con, etc). You probably want to pass those values to a constructor and set them as class properties. Better yet, look into PDO (or an ORM) and forget creating your own db class.

Insert data into MySql table strange exception

I am using this code to insert some values in MySql table:
<?php
mysql_connect("localhost","root","root");
mysql_select_db("bib");
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query);
// Display an appropriate message
if ($result)
echo "<p>Product successfully inserted!</p>";
else
echo "<p>There was a problem inserting the Book!</p>";
mysql_close();
?>
After running it into browser, the following error occurs:
"Apache HTTP Server has encountered a problem and needs to close. We are sorry for the inconvenience."
It seems that mysql_select_db("bib") statement causes it. Database is create , also table...
I am running php 5.3 and mysql 5.1 on windows xp sp 2.
Please any ideas are welcomed...
Thanks...
Any of the mysql_* functions can fail for various reasons. You have to check the return values and if a function indicates an error (usually by returning FALSE) your script has to react appropriately.
mysql_error($link) and mysql_errno($link) can give you more detailed information about the cause. But you don't want to show all the details to just any arbitrary user, see CWE-209: Information Exposure Through an Error Message.
If you don't pass the connection resource returned by mysql_connect() to subsequent mysql_* functions calls, php assumes the last successfully established connection. You shouldn't rely on that; better pass the link resource to the functions. a) If you ever have more than one connection per page you must pass it anyway. b) If there is no valid db connection the php-mysql modules tries to establish the default connection which is usually not what you want; it only takes up more time to fail ..again.
<?php
define('DEBUGOUTPUT', 1);
$mysql = mysql_connect("localhost","root","root");
if ( !$mysql ) {
foo('query failed', mysql_error());
}
$rc = mysql_select_db("bib", $mysql);
if ( !$rc) {
foo('select db', mysql_error($mysql));
}
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query, $mysql);
// Display an appropriate message
if ($result) {
echo "<p>Product successfully inserted!</p>";
}
else {
foo("There was a problem inserting the Book!", mysql_error($mysql), false);
}
mysql_close($mysql);
function foo($description, $detail, $die=false) {
echo '<pre>', htmlspecialchars($description), "</pre>\n";
if ( defined('DEBUGOUTPUT') && DEBUGOUTPUT ) {
echo '<pre>', htmlspecialchars($detail), "</pre>\n";
}
if ( $die ) {
die;
}
}
try this to connect to database:
$mysqlID = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die("Unable to connect to database");
mysql_select_db(DB_DATABASE) or die("Unable to select database ".DB_DATABASE);
also, try this as your insert query:
$query = "INSERT INTO carte (id, title) values ('".$id."', '".addslashes($titlu)."')
$result = mysql_query($query) or die(mysql_error());
By using die(), it will tell you where it has failed and why

Categories