I'm struggling with the following problem. Some years ago, I've written a function to retrieve MYSQL results (multiple rows). Till PHP7, this code worked fine:
function MultipleRows($query)
{
global $dbhost, $dbname, $dbuser, $dbpass;
mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error! Couldn't <b>Connect</b>.");
mysql_select_db($dbname)
or die("Error! Couldn't <b>Select database</b>.");
$result = mysql_query($query)
or die("Error! Couldn't execute query.");
if(($result)&&(mysql_num_rows($result)>0))
{
return $result;
} else {
return false;
}
mysql_close();
}
Now in PHP7, this code doesn't seem to work anymore. After a lot of searching I came up with this as a replacement but unfortunately it doesn't work:
function MultipleRows($query)
{
$mysqli = new mysqli($dbhost, $dbpass, $dbuser, $dbname);
$result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC);
return $result;
$mysqli->close();
}
The function is meant to work with code like this:
$res_test = MultipleRows("SELECT id, name FROM table");
if($res_test)
{
while($res = mysql_fetch_array($res_test))
{
echo $res['id'].' '.$res['name'];
}
}
It's not a good option to rewrite the 'display code' (last fragment) because in that case I have to rewrite many lines in my website. Who can give me some help in this? Thanks in advance!
mysql extension has been dropped from PHP 7, after being deprecated in PHP 5.x.
You could rewrite function MultipleRows() using mysqli as follows:
function MultipleRows($query)
{
global $dbhost, $dbpass, $dbuser, $dbname;
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$result = $mysqli->query($query);
if ($result !== FALSE)
$result = $result->fetch_all(MYSQLI_ASSOC);
$mysqli->close();
return $result;
}
A few remarks:
it is not a good idea to use global variables ($dbhost, $dbuser, $dbpass and $dbname)
this way of handling database queries makes you vulnerable to SQL injection attacks
Related
Can anyone tell me about how to build a connection between mysql and php page.
Please help me with this.
To start a connection You Might do Following code:-
<?php
$servername = "localhost";
$username = "test";
$password = "test";
$dbname = "test";
//change test with your server details//
$conn = mysqli_connect($servername,$username,$password,$dbname);
if ($conn)
{
//echo "connection ok";
}
else
{
echo "connection Failed";
}
?>
hope this code would help you .
Make conn.php file with this code inside and use $conn variable to prepare queries using prepared statement
if(!defined("connection")){
header('Location:error.php');
exit();
}
define("host","localhost");
define("user","mysql_user");
define("pass","password");
define("dbname","database_name");
$conn=new mysqli(host,user,pass,dbname);
if($conn->connect_error){
die("Failed to connect");
exit();
}
mysqli_set_charset($conn,"utf8mb4");
Use conn.php and $conn variable like this
Page.php
require_once("conn.php");
if($stmt = $conn->prepare($query)){
echo "prepared";
}
function get_country($code){
$query = mysql_query("SELECT country FROM `list_countries` WHERE `code`='".$code."' LIMIT 1");
$country = mysql_fetch_array($query);
return $country['country'];
}
Very new to PDO and have absolutely no idea how to turn this from a mysql function to a PDO one. Any help would be appreciated :)
You need to take PDO database connection handler with you :) From your code I would suggest setting it as global, or you can add additional parameter to all the functions.
$dbconn = new PDO("mysql:host=localhost;dbname=your_db","your_user","your_password");
// this line is important - throw an exception if there is an error
$dbconn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
function get_country( $dbconn, $code ) {
$res = $dbconn->prepare('SELECT country FROM `list_countries` WHERE `code`=? limit 1');
$res->execute( array( $code) )
$country = $res->fetch();
return $country['country'];
}
Hello since yesterday i am trying to get the transaction hash on blockchain send many api and send to mysql but it dont works. i put to insert at mysql $txid but it give wrong results as per example "2147483647" i really thanks for any help. Below is my code.
<p>$guid="***********";
$firstpassword="**********";
$secondpassword="**************";
$amounta="3599";
$amountb="2000";
$amountc="2000";
$addressa="********";
$addressb="***********";
$addressc="******";
$recipients=urlencode('{
"'.$addressa.'": '.$amounta.',
"'.$addressb.'": '.$amountb.',
"'.$addressc.'": '.$amountc.'
}');
$json_url =
"https://blockchain.info/pt/merchant/$guid/sendmany?password=******&second_password=********&recipients=$recipients¬e=********";
$json_data = file_get_contents($json_url);
$json_feed = json_decode($json_data);
$message = $json_feed->message;
$txid = $json_feed->tx_hash;
$tx = "$txid";
$servername = "localhost";
$username = "******";
$password = "*******";
$dbname = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$<font color="#FF0000">sql = "INSERT INTO payments (user_id, transaction_hash,
payment, date)
VALUES ('5331', '$txid', '4', now())";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;<br>
}
$conn->close();
?>
Lol, sorry that scrypt work very well, the problem i a set the table as INT 11, so i changed it to vachar 255 and its works well.
Thanks
I have to change an old mysql to PDO, I am working with a code its made by someone else, so I have this following code to change in PDO
The original code is
function liste($a,$b,$c)
{
$queryliste= "SELECT id,nom,prenom
FROM table";
$this->list = Connection_Base($querylistactu);
}
//Connection_Base
function Connection_Base($query)
{
$link = mysql_connect(DATABASESERVER, DATABASEUSER, DATABASEPASSWORD);
$ret = mysql_select_db(DATABASEDB, $link);
if (!$ret)
{
die("Echec de connection");
} else {
$mysql_desc = DATABASEDB;
if(!$result = mysql_query( $query))
{
return 0;
} else {
return $result;
}
mysql_close($link);
}
}
This is the part with which I have problem. I want to change it using PDO.
while( list($x,$y,$z) = mysql_fetch_row($lactu->list) )
I am proceed like this but it doesn't work
while( list($x,$y,$z) = $lactu->list->fetch(PDO::FETCH_NUM)
any ideas ?
Why don't you use PDO::FETCH_ASSOC? Check the code sample for connecting to database, executing the query, fetching all rows and iterate over the rows.
//Your query
$queryliste = "SELECT id, nom, prenom FROM table";
//Initialize pdo connection use your $name, $host, $username and $password
$pdoLink = new PDO("mysql:dbname={$name};host={$host};charset=utf8", $username, $password);
//Prepare statement
$statement = $pdoLink-> prepare($queryliste);
//Execute query
$statement -> execute();
//(1) Fetch rows using PDO::FETCH_ASSOC
$rows = $statement -> fetchAll(PDO::FETCH_ASSOC);
$statement -> closeCursor();
foreach($rows as $row) {
echo $row['id'];
echo $row['nom'];
echo $row['prenom'];
}
//(2) or you can use PDO::FETCH_NUM
$rows = $statement -> fetchAll(PDO::FETCH_NUM);
$statement -> closeCursor();
foreach($rows as list($x, $y, $z)) {
echo $x;
echo $y;
echo $z;
}
//(3) or you can rewrite the last in the same form you are using as
while((list($x, $y, $z) = $statement->fetch(PDO::FETCH_NUM))) {
echo $x;
echo $y;
echo $z;
}
$statement -> closeCursor();
I am new to Perl and need some help.
In Mysql I have a table with a todo-List filled up.
At the beginning of my script, I want to add these values to "my %todo"
But I can't figure out how to do this...
Any idea?
OK, let's play martian rover though I'd rather see the code.
Do you use warnings; use strict? If not, do it. If yes, are there any warnings or errors?
If you put a print "while\n"; into your while loop, how many while's will you get on screen? How many records are there in the table?
If you use DBI, turn on exceptions: $dbh->RaiseError(1); ($dbh is you database handle here) before any operations with DB.
I don't understand why you ask for "load array" and specify a hash %todo, but if you want to read a table into memory once, you should look at the $dbh->selectall_arrayref() method.
Added: See if this get you started:
my $dsn = '...';
my $user = '...';
my $password = '...';
my $dbh = DBI->connect( $dsn, $user, $password, { RaiseError => 1, AutoCommit => 0 } );
my $sql = 'SELECT ... FROM Todo';
my %todo = ();
if (0) {
my $sth = $dbh->prepare( $sql );
$sth->execute();
while (my $aref = $sth->fetchrow_arrayref()) {
$todo{ $aref->[ 0 ] } = $aref->[ 1 ];
}
$sth->finish();
} else {
my $aref = $dbh->selectall_arrayref($sql);
for (#$aref) {
$todo{ $_->[ 0 ] } = $_->[ 1 ];
}
}
for (keys( %todo )) {
print $_, "\n", $todo{ $_ }, "\n\n";
}
my $rc = $dbh->disconnect();
use strict;
use warnings;
my $dbh = $dbh->connect;
$dbh->{RaiseError} = 1;
my $sth = $dbh->prepare(q/select id, to_do from to_do_table/);
$sth->execute;
my %todo;
while(my ($id, $to_do) = $sth->fetchrow) {
$todo{$index_column} = $to_do;
}
$dbh->disconnect;