I used to write some php a few years ago and used adodb to connect to a mysql database.
After reading a bit on stackoverflow I wondered if adodb is still maintained ?
the latest changelog is from 3rd of September 2012.
I started reading the documentation of mysqli. I can get a database connection but can not seem to figure out a way to run a query and get the results of the query back.
Could someone tell me how to run a simple query like "SELECT * FROM Text WHERE TextId=10;" ?
I tried this
$dbconn = new mysqli($Host, $DbAdminUser, $DbAdminUserPassword, $Database);
if ($dbconn->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $dbconn->host_info . "\n";
$stmt = mysqli_prepare($dbconn, "SELECT * FROM Text WHERE TextId=10;")
$result = mysqli_query($dbconn,$stmt);
print_r($result);
anybody could help me out or point me what I am doing wrong ?
or should I just stick with adodb ?
Please note that mysqli is a low-level api that isn't intended to be used in the application code. So - it's incomparable to ADODB. So, instead of raw mysqli I'd suggest you to use PDO or a library built on top of mysqli, such as my safeMysql
Related
everything functions on the side of data validation and error gathering and such, I get a problem specifically where $r is being executed. I always get the echo error. I've used this same bit of code before, but for some reason isn't working. Just need a second look of eyes at it perhaps.
if (empty($errors)){
$q = "INSERT INTO testTable (test1, test2) VALUES ('Test', 'Test')";
$r = #mysqli_query($dbc, $q);
if($r){
echo 'Complete!';
}
else{
echo 'error';
}
mysqli_close($dbc);
include('footer.html');
exit();
I can enter the statement manually in MySQL and it will add it to the table, so I don't think its a syntax error there, I am just a little tired at this point.
"I'm getting a lot of warnings saying that parameter 1 of mysqli_xxx must be mysqli. So does that mean that my $dbc variable isn't working properly?"
The reason for that may very well be because your DB connection method is probably based on mysql_connect() or PDO to connect with.
Something you haven't posted in your question.
Those different MySQL APIs do not intermix with each other.
mysql_ + mysqli_ or PDO = no love. mysqli_ + PDO, same thing.
Refer to both manuals:
MySQLi: http://php.net/manual/en/function.mysqli-connect.php
PDO: http://php.net/manual/en/pdo.connections.php
and use only "one" MySQL API, from beginning to end and not a "mix of".
You should also remove the # symbol(s) from your code. Those are error suppressors and won't help you when debugging code.
So your connection for MySQLi_ would look something like this:
$dbc = mysqli_connect("myhost","myuser","mypassw","mybd")
or die("Error " . mysqli_error($dbc));
Unlike mysql_:
$dbc = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$dbc) {
die('Could not connect: ' . mysql_error());
}
I am querying a mysql database with php but cannot get it to work on my iMac. In particular, php is unable to connect to the mysql DB. It connects to mysql and selects the DB but then fails. See code below:
if (!mysql_connect($db_host, $db_user, $db_pwd)){
die("I cannot connect to database");
}
if (!mysql_select_db($database)){
die("I cannot select database");
}
$sql = "SELECT FROM ${table} ORDER BY $sql_orderBy";
$result = mysql_query($sql);
if (!$result) {
die("I cannot execute query to show fields from Table: {$table}. Query failed.");
}
For reference, I installed apache/mysql/php with macports. The same php code works on my laptop (same installations), and the query works when I invoke it from within mysql on both computers. All variables are declared. Something with the system config is my best guess, but I even went through a uninstall/install.
Any help would be appreciated!
Your issue is ${table} . This should be {$table} or better still, ".$table."
You also need to say what you are SELECTING:
So:
$sql = "SELECT * FROM ".$table." ORDER BY ".$sql_orderBy;
You can discover issues by using Mysql_error() at the end of the query, for example:
mysql_query($sqlString) or die("line: ".__LINE__.":".mysql_error());
this will output a clear error message regarding your SQL statement. This is not for production and public situations but for development.
Also:
MySQL is deprecated and is no longer supported by PHP or the wider community, it is VERY strongly recommended you take up MySQLi or PDO and use these methods as they are much stronger, less flawed and more efficient delivery of results. They will also be supported in future updates and developments whereas MySQL will not.
This question already has an answer here:
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead [duplicate]
(1 answer)
Closed 8 years ago.
My host recently upgrade the PHP version and a certain part of my website now shows the following error:
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in url/structure/here on line 49
That is referencing the below code:
function DBConnect() {
$this->connectCount ++;
//echo "$this->connectCount<br>";
if ($this->dbType == 'mysql') {
$dbConnect = mysql_connect($this->dbHost, $this->dbUser, $this->dbPasswd) or die ("MySql Connection Failed: " . mysql_error());
mysql_select_db($this->dbName, $dbConnect);
}
if ($this->dbType == 'postgresql') {
$dbConnect = pg_connect("host=$this->dbHost port=$this->dbPort dbname=$this->dbName user=$this->dbUser password=$this->dbPasswd") or die ("PostgreSQL Connection Failed: " . pg_errormessage($dbConnect));
//$dbConnect = pg_pconnect("host=$this->dbHost port=$this->dbPort dbname=$this->dbName user=$this->dbUser password=$this->dbPasswd") or die ("PostgreSQL Connection Failed: " . pg_errormessage($dbConnect));
}
return $dbConnect;
}
I'm aware the fact that this is because the current way my site connects to MYSQL is now outdated in the new version of PHP but does anyone know how I would update the above code to make this work?
The easier way is to use mysqli_connect(). The syntax is very similar to what you would had with mysql_connect(),which means the changes in your code will be minor and easy to make.
Pdo would be the safest, but if you are trying to get you site back on quickly, the mysqli_* commands will achieve that.
Google (or check on stackoverflow) mysql vs mysqli. You ll find plenty of examples.
Hope this helps.
Good luck
--
Sorry after re-reading i see you asked what needs to be change on your source code. Afraid i cannot help right now as i am responding from a mobile phone :(
I have been working for days now and I am at a dead end. After talking with GoDaddy support I am positive that I have the correct hostname, username/password when I run the script but it still cannot get past die().
Ultimately I am attempting to pull a single question from a database. I have combed this website but nothing i found seems to answer my question. Please help.
<?php
$hostname='localhost';
$username='username';
$password='password';
$dbname='qod';
$usertable='Questions';
$userfield='question';
mysql_connect($hostname,$username, $password) or die ("<html><script language='JavaScript'>alert('Unable to access the Question of the Day! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname);
# Check If Record Exists
$query = 'SELECT $.userfield FROM $.usertable ORDER BY RAND() LIMIT 1';
$result = mysql_query($query);
if($result){
while($row = mysql_fetch_array($result)){
$name = $row[$yourfield];
echo "Name: ".$name;}
}
?>
You are using dots for your SELECT variables where there shouldn't be any.
SELECT $.userfield FROM $.usertable, then calling them with:
$usertable='Questions';
$userfield='question';
Remove them from your SELECT and use proper error reporting techniques such as :
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of code
and
or die('Could not connect: ' . mysql_error());
also a dollar sign in [$yourfield] for your column name; remove it also.
You should be using quotes: I.e.: ['yourfield'] - yourfield being the column name in your table that you wish to show.
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/.
Use mysqli_* with prepared statements, or PDO with prepared statements.
I'm trying to get my head around prepared statements.
Basically, I would do a insert like so normally:
$sql = '
INSERT INTO customers
(customer_first, customer_last, customer_address, customer_email)
VALUES
(' . mysql_real_escape_string($_POST['customer_first']) . ',
' . mysql_real_escape_string($_POST['customer_last']) . ',
' . mysql_real_escape_string($_POST['customer_address']) . ',
' . mysql_real_escape_string($_POST['customer_email']) . ' )
';
mysql_query($sql);
From what I've been told however there is a more secure way to do this using Prepared Statements.
So far I think it is done like so:
$stmt = $dbh->prepare("INSERT INTO customers (customer_first, customer_last, customer_address, customer_email) VALUES (:customer_first, :customer_last, :customer_address, :customer_email)");
$stmt->bindParam(':customer_first', $_POST['customer_first']);
$stmt->bindParam(':customer_last', $_POST['customer_last']);
$stmt->bindParam(':customer_address', $_POST['customer_address']);
$stmt->bindParam(':customer_email', $_POST['customer_email']);
$stmt->execute();
Is this correct? Or is there a better way to do what I'm trying to achieve? If I try the above I get an error "Call to a member function prepare() on a non-object" - what does that mean?
I'm using the examples # http://php.net/manual/en/pdo.prepared-statements.php. It refers to a $dbh - where does it get that from? Is $dbh supposed to be referenced elsewhere - I'm assuming it is something to do with the database connection?
In addition to those questions, can I still use things like mysql_insert_id() or mysql_error() using prepared statements like above?
If you are new to OOP, you could start with mysqli for more immediately familiar functionality and syntax and support for functional programming, but it's worth reviewing the PDO class if you're ready to tackle OOP.
Worth reviewing to help decide where to start: mysqli or PDO - what are the pros and cons?
It refers to a $dbh - where does it
get that from? Is $dbh supposed to be
referenced elsewhere - I'm assuming it
is something to do with the database
connection?
$dbh = database handle (as defined in the PDO > Connections and Connection Management doc)
Can I still use things like
mysql_insert_id() or mysql_error()
using prepared statements like above?
PDO::lastInsertId, PDO::errorInfo
The error message indicates your problem is with the $dbh object -- how is it initialized?