Problems printing a session in php - php

I have a problem while passing information with $_SESSION in php. Every time that I try it, it sends me a message saying "Array to string conversion".Here is the code:
<?php
session_start();
ob_start();
include("conexion3.php");
$con = mysql_connect($host,$user,$pw) or die("Error");
mysql_select_db($db,$con) or die("Error DB");
$sel2 = mysql_query("SELECT usuario_n,correo FROM usuarios WHERE usuario_n='machan'",$con);
$sesion = mysql_fetch_array($sel2);
$_SESSION['resultado'] = $sesion;
echo $_SESSION['resultado'];
?>

The answer lies in your last comment. The problem is, $_SESSION['resultado'] is an array and with echo $_SESSION['resultado']; you're trying to convert array to string, hence the message.
You can do something like this to get the values:
echo $_SESSION['resultado'][0]; // machan
echo $_SESSION['resultado']['usuario_n']; // machan
echo $_SESSION['resultado'][1]; // elver#gmail.com
echo $_SESSION['resultado']['correo']; // elver#gmail.com
Sidenote: Please don't use the mysql_ database extensions, they were deprecated in PHP 5.5.0 and were removed in PHP 7.0.0. Use mysqli or PDO extensions instead. And this is why you shouldn't use mysql_ functions.

You're trying to echo out an array. $session stores the array you fetched from your mysql db. Try the following instead of that echo statement:
print_r($_SESSION['resultado']);
http://php.net/manual/en/function.print-r.php

Related

I get this error when I want to connect my database

I am doing a course on the internet and everything was going well until I had to connect a database. It has not worked for me and I have looked for many solutions but I have 2 days and I do not get anything
Here the database code
<?php
function conectar_bd()
{
$servidor = "127.0.0.1";
$usuario = "jhon28";
$contraseña = "Elmenor28519";
$nombrebd = "empresa";
$conexion = mysqli_connect("127.0.0.1", "jhon28", "Elmenor28519");
mysqli_select_db($conexion, $nombrebd);
return $conexion;
}
?>
Here the connection code
<?php
include("basededatos.php");
$conexionbd=conectar_bd();
echo $conexionbd;
mysqli_close ($conexionbd);
?>
Here the error that come to me
Recoverable fatal error: Object of class mysqli could not be converted to string in C:\xampp\htdocs\prueba.php on line 4
Remove echo $conexionbd; or change it to print_r($conexionbd);
<?php
include("basededatos.php");
$conexionbd=conectar_bd();
print_r($conexionbd); //here you are getting object so you can't use echo use print_r instead
mysqli_close ($conexionbd);
?>
based on the docs you wont need select_db, you may insert it on the same function like below.
$link = mysqli_connect($servidor, $usuario, $contraseña, $nombrebd);
Therefore, you save one line. Just helping to optimize your code. Refer docs for more information.

Generate simple JSON file based on database

Hey I am iOS developer I am trying to create simple JSON output from my website. I found good start link and here is some explanation how to do it.
So I've created accounts.php file and put it to my public_html folder
<?php
include_once("JSON.php");
$json = new Services_JSON();
$link = mysql_pconnect("localhost", "user", "pass") or die("Could not connect");
mysql_select_db("iglobe") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM users");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
Echo $json->encode($arr);
?>
Of course I use my user and password and I pointed my just created database ob my end.
so when I try to request my file so http//mywebsite.com/accounts.php there is no data.
I tried to use google chrome and Postman so it says No response received when I switch to JSON. For HTML there is no info in Postman.
My question how can I test it? even if I use Echo(123) before include_once("JSON.php"); line there is no 123 on html page.
I tried to test PHP with only this code:
<?php
phpinfo();
?>
and it works. I have PHP Version 5.4.32
First of all, simply use PHP's function json_encode($arr). It does exactly what you are asking for and is pretty much included in every version of PHP that I can think of.
Documentation
Also, I am not sure if this is the issue, but you may want to change Echo ==> echo. This is generally convention at the very least.
SUPER IMPORTANT
Finally, DO NOT USE mysql extension. Its is dangerous, may not work correctly, and has security vulnerabilities. Use mysqli or PDO.
Matrosov -
You are very close. Use the json_encode function to output your code via the PHP manual. Also consider using mysqli instead of mysql for your database connection as it has been better support for modern MySQL servers.
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/book.mysqli.php
<?php
include_once("JSON.php");
$link = mysqli_connect("localhost", "user", "pass") or die("Could not connect");
$link->mysql_select_db("iglobe") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM users");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo json_encode($arr);
?>

MySQL connect function runs even if the username is wrong

I already know that if you want to connect to a database using MySQL you have to provide the correct URL, username, password that is the normal thing here is my code:
<?php
$mysql_id = mysql_connect('localhost', 'root', '');
mysql_select_db('Booklet', $mysql_id);
if(!$mysql_id)
{
echo"cannot connect to database ";
}
?>
This code runs well, however if I messed with the username which is root it still connects here is the code:
<?php
$mysql_id = mysql_connect('localhost', 'rot', '');
mysql_select_db('Booklet', $mysql_id);
if(!$mysql_id)
{
echo"cannot connect to database ";
}
?>
Can anyone explain to me why is this happening?
As of PHP 5.5.0 mysql_* functions are deprecated and you should not code with thoses. Think of thoses function as a crawling zombie, you don't go and kiss it, do you ?
You should use MySQLi or PDO for doing operations on database. Please don't bother with mysql_* anymore, you dont want that. It's like asking to code on Windows Milenium, hell, even booting this thing is a nightmare.
Anyway, to answer the question you should write :
$mysql_id = mysql_connect('localhost', 'rot', '') or die(mysql_error());
Or better, you should look at the doc of MySqli and be free of thoses shackles. Think about that, please.
You never bothered checking for failure. Your code simply assumes success and blunders onwards.
$mysql_id = mysql_connect('localhost', 'rot', '') or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
mysql_select_db('Booklet', $mysql_id) or die(mysql_error());
All of the mysql_*() function return boolean false on failure. You need to check for that false. Never ever assume a DB operation succeeded. Always assume failure, check for that failure, and treat success as a pleasant surprise.
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
try to debug your code by adding mysql_error() like this
$mysql_id = mysql_connect('localhost', 'rot', '');
mysql_select_db('Booklet', $mysql_id);
echo " debug return: " . mysql_error();
or simply update your code if you have a newest version of php > 5.5.0
$mysql_id = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
Using the new MySQLi functions, you would get a false back on trying to connect, also you can pass you database as fourth parameter. So your code could look like this:
<?php
if($mysql_id = mysqli_connect('localhost', 'root', '', 'Booklet'))
{
/* do something like mysqli_query($mysql_id, ... */
}
else
{
echo"cannot connect to database ";
}
?>

Mysql & PHP won't echo the results of the query

<?php
mysql_connect("localhost", "root", "usbw");
mysql_select_db("europese unie");
$id = $_GET['Land'];
$query = "SELECT `Land`, `Oppervlakte`, `Inwoners`, `Klimaat`, `Motto`, `UTC` FROM `algemene informatie` WHERE `Land` = '$id'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
$land = $row[0];
echo "$land";
print("<h2>$id</h2>");
print("<br />");
die(mysql_error())
?>
when i tried to run this code i expected to echo the first land that came up with this query instead i got nothing. i am not a very experienced PHP or Mysql user nor is english my first language so pleas do not hold annything against me.
Solved
Taken from comments:
"well the adress is localhost:8080/details.php?Land=%20Belgie and $id = $_GET['Land']; is the id so Belgie should be $id but as var_dump($result) it keeps giving bool(false)"
Basically what you're asking SQL, is to find (space)Belgie and since your column doesn't contain the word Belgie with a space, it will not find it; least that's what I think is happening
That %20 is a space btw. That could be the problem. You could make use of the trim() function.
Use:
$id = trim($_GET['Land']);
OP:
thank you print_r($row); now gives Array ( [0] => Belgie [1] => 31 [2] => 11 [3] => gematigd zeeklimaat [4] => Eendracht maakt macht [5] => 1 ) i can finaly proceed
Sidenote: Your present code is open to SQL injection. Use mysqli_* functions. (which I recommend you use and with prepared statements, or PDO)
mysql_* functions are deprecated and will be removed from future PHP releases.
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Do not use mysql_connect() this is going to become outdated, use mysqli_connect().
I.e.:
$connection = new mysqli('host', 'username', 'password', 'db table', 'portnumber');
if (mysqli_connect_errno()){
printf("<b>Connection failed:</b> %s\n", mysqli_connect_error());
exit;
}
run you query through mysqli object and remember to use injection prevention or you will get people hacking you site.
e.g.
http://www.phphaven.com/article.php?id=65
Hope that helps
Quote out the variables.
echo $land;
print("<h2>" . $id . "</h2>");

Include no database selected

I have a project (exisiting) and I am ordered to continue it
but there's something strange
in my connection
<?php
include "adodb5/adodb.inc.php";
$config['mysqlhost'] = 'localhost';
$config['mysqluser'] = 'xxx';
$config['mysqlpass'] = 'yyy';
$config['mysqldb'] = 'zzz';
$DB = ADONewConnection('mysql');
$DB->Connect($config['mysqlhost'],$config['mysqluser'],$config['mysqlpass'],$config['mysqldb'],true);
?>
and if I try to call query (same queries as below) from this page, it works (and when I echo, it shows the value)
So I go to other page
<?
include ("inc/con.php");
?>
<?php
$sql = ("SELECT * FROM table");
$query = mysql_query($sql)or die($myQuery."<br/><br/>".mysql_error());
$result = mysql_fetch_array($query);
echo $result ['table id'];
?>
and the result is
Notice: Undefined variable: myQuery in C:\xampp\htdocs\d88\www\mypage.php on line 9
No database selected
is there anything wrong with it?
since i try on con page, it works and when i include it to other page, it not working
You are not defining any $myQuery either in inc/con.php nor in the same file itself. Also you are not selecting any database with mysql_select_db:
mysql_select_db($config['mysqldb']);
You are suggest, also, not to use mysql_* functions as they are going to be deleted and are yet deprecated (and you can use PDO or mysqli).
Notice: I think $sql = ("SELECT * FROM table") gets evaluated as $sql = true.
You can not connect with ADODB connection and establish a query with mysql_query.
the syntax is something like this mysql_query ($query ,$con). $con is optional but if you do not specify it, the last link opened by mysql_connect() is assumed; but you have not any mysql_connect() statement before
because of my version of php, i must use <?php ?> instead of <? ?>
thanks for helping

Categories