This mysql_connect Attribute seems to old how can I replace them? - php

I cannot connect to my Data Base using this way:
mysql_connect("localhost","root","") or die("1");
mysql_select_db("database") or die("2");
After the connection to the data base I would like to create a while loop with the elements of the data base, this is my code:
$carlistreq = mysql_query("SELECT * FROM cars WHERE brand="'.$_GET['marq'].'"") or die("3");
$count = mysql_num_rows($carlistreq);
if($count==0)
{
echo "No elements";
}
else
{
while($row= mysql_fetch_array($query))
{
//my code
}
}
The issue comes from my SQL attributes like:
mysql_connect
mysql_fetch_array
mysql_select_db
For example.
Here is the error:
Deprecated: mysql_connect(): The mysql extension is deprecated and
will be removed in the future: use mysqli or PDO instead in C:[....]
on line 2

use the mysqli-extension like this:
$mysqli = new mysqli("localhost","user","password","database") or die("1");
$sql = "SELECT * FROM cars WHERE brand='".$_GET['marq']."'";
$result = $mysqli->query($sql);
if($result){
while($row = $result->fetch_assoc()){
//do something with your $row here
}
}
http://php.net/manual/en/book.mysqli.php

Use PDO
$db = new PDO('mysql:host=localhost;dbname=databaseName', 'User' , 'password');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

Yes now servers are going to handel mysqli and PDO. Try implementing this code:
<?php
$con = mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
// Change database to "test"
mysqli_select_db($con,"test");
// ...some PHP code for database "test"...
mysqli_close($con);
?>
You can user http://php.net/manual/en/book.mysqli.php as reference to understand better how mysqli works.

Related

php change type connection from odbc to PDO

I used odbc connection to access to my DB, but I need to change it to PDO.
I access the DB with PDO without any trouble, but some sentences are refered to odbc and I don't know how to relate it to PDO.
On my code I just change the $connect to the pdo connection (it used to be the odbc
The last part of the php is the one that i need to adjust to pdo
<?php
function getArraySQL(){
$startd = "29964";
$endd = "29968";
$connect = new PDO("sqlsrv:Server=projects;Database=dummy", "pass", "pass");
$query = "THIS IS THE QUERY";
if(!$rs = odbc_exec($connect, $query)) die();
$rawdata = array();
$i=0;
while($row = odbc_fetch_array($rs))
{
$rawdata[$i] = $row;
$i++;
}
odbc_close( $connect );
return $rawdata;
};
$myarray = getArraySQL();
echo json_encode($myarray);

Connect to my database with PHP

I want to connect my HTML page to my database but I”m not getting it not sure why. What’s wrong with the code?
<?php
$con = mysqli_connect("localhost","root","","sibd02");
$query = sprintf("SELECT*FROM fornecedor ",
$result = mysql_query($query);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
There are lots of issues with your code. Here is my cleaned up version of your code which should work:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost", "root", "sibd02") or die(mysqli_connect_errno());
// Set the query.
$query = "SELECT * FROM fornecedor";
// Run the query.
$result = mysqli_query($con, $query) or die(mysqli_connect_errno());
// Print the result for initial testing.
echo '<pre>';
print_r($result);
echo '</pre>';
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
So let’s look at your original code with notes below on each issue:
$con = mysqli_connect("localhost","root","","sibd02");
$query = sprintf("SELECT*FROM fornecedor ",
$result = mysql_query($query);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
First this line $query = sprintf("SELECT*FROM fornecedor ", is incorrect syntax in PHP. And the sprintf is not needed.
Then your MySQL query would fail because it has it’s own syntax error: SELECT*FROM fornecedor That SELECT*FROM should have spaces like this SELECT * FROM.
Then you are using mysqli_connect for the connection but then using mysql_query for the query. Those are two 100% different functions in different classes. Mixing them like this will never work.
Mixing MySQL and MySQLi won't work. You can simply do this:
<?php
/* ESTABLISH CONNECTION */
$con=mysqli_connect("localhost","root","","sibd02");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$query = "SELECT * FROM fornecedor";
$result = mysqli_query($con,$query); /* EXECUTE QUERY */
/* IF YOU WANT TO PRINT THE RESULTS, HERE IS AN EXAMPLE: */
while($row=mysqli_fetch_array($result)){
echo $row['column']." ".$row['column2']." ".$row['column3']; /* JUST REPLACE THE NECESSARY COLUMN NAME */
} /* END OF WHILE LOOP */
mysqli_close($con);
?>

PHP sql query isn't returning anything

The following PHP code:
$dbc = mysql_connect ('localhost','root','abcde');
if (!$dbc) {
die('Not Connected:' . mysql_error ());
}
$db_selected = mysql_select_db ('db_test', $dbc);
if (!$db_selected) {
die ("Can't Connect :" .mysql_error());
}
$query="SELECT * FROM 140423 WHERE GAME='Clash of Clans'";
//add "result"
$result=mysql_query($query);
if (!$query) {
die ("Can't Connect :" .mysql_error());
}
echo $result;
Doesn't return anything.
Should I be using print instead of echo?
Also, if I change
echo $result;
To
echo 'whatever';
it returns "whatever" on my post.
Help?
From the manual:
Identifiers may begin with a digit but unless quoted may not consist solely of digits.
http://dev.mysql.com/doc/refman/5.1/en/identifiers.html
Which is exactly what you're doing, and should not be doing.
Solution:
Choose a different name for your table, one consisting of letters preferably.
Use backticks around the table name.
Plus, if you wish to view data, you need to use a loop.
I.e.:
$query="SELECT * FROM `140423` WHERE GAME='Clash of Clans'";
while ($row = mysql_fetch_assoc($query))
{
$var = $row["column"]; // the column of your choice
}
echo $var;
Rewrite:
$dbc = mysql_connect ('localhost','root','abcde');
if (!$dbc) {
die('Not Connected:' . mysql_error ());
}
$db_selected = mysql_select_db ('db_test', $dbc);
if (!$db_selected) {
die ("Can't Connect :" .mysql_error());
}
$query="SELECT * FROM `140423` WHERE GAME='Clash of Clans'";
//add "result"
$result=mysql_query($query);
// as pointed out already
if (!$result) {
die ("Can't Connect :" .mysql_error());
}
echo $result; // this is up to you
// if you want to see data from your table, loop through it.
while ($row = mysql_fetch_assoc($query))
{
$var = $row["column"]; // the column of your choice
}
echo $var;
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/.
mysql_query returns a resource or false. You need to manipulate the resource with one of the various fetch functions.
Instead of looking if $query is false, you should be looking if $result is false.
if (!$result) {
die ("Can't Connect :" .mysql_error());
}
After that
$result=mysql_query($query);
if (!$query) {
die ("Can't Connect :" .mysql_error());
}
Use
while($row = mysql_fetch_array($result)) {
echo $row['YourTableFieldName'];
}
OR use
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// If you want to display all results from the query at once:
print_r($row);
// If you want to display the results one by one
echo $row['YourTableFieldName1'];
echo $row['YourTableFieldName2'];
}

PHP: connected to database, but mysql_query fails

I have very strange problem with PHP which I am starting to learn .. I have created tables in MySQL database with some data, and now I want to show them in webpage.
This is my source where I have this problem:
<?php
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);
// I check the connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
// It always goes here
echo "Connected to database!";
}
// I am testing very simple SQL query.. there should be no problem
$result = mysql_query("SELECT * FROM cathegories", $con, $db);
if (!$result) {
// but it always dies
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close($con);
?>
What is wrong?
Thanks in advance!
You are mixing mysql and mysqli.
Try something like:
<?php
$con= new mysqli("localhost","user","passwd","database");
if ($con->connect_errno){
echo "could not connect";
}
$select = "SELECT * FROM tablename";
if($result = $con->query($select)){
while($row = $result->fetch_object()){
echo $row->rowname."<br>";
}
}
else { echo 'no result'; }
$con->close();
?>
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $connection);
change to
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);
mysql_query only takes two parameters - the actual SQL and then the link identifier (I assume in your case that's stored in $con; therefore remove $db from the third parameter).
You don't even need the second $con parameter really.
Where's the actual logic to connect to the database initially? Just because mysqli_connect_errno() doesn't return an error it doesn't mean the connection actually exists and that $con is available in the current scope.
I'd var_dump($con) before the mysql query to make sure it's a valid connection.

PHP-Linking forms Using ID

I have a database in which I have a main form that list all personnel using this code
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("datatest", $con);
$result = mysql_query("SELECT * FROM Personnel");
echo "<TABLE BORDER=2>";
echo"<TR><TD><B>Name</B><TD><B>Number</B><TD><B>View</B><TD></TR>";
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["Surname"]." ".$myrow["First Names"]."<TD>".$myrow["Number"];
echo "<TD>View";
}
echo "</TABLE>";
?>
</HTML>
As you can note I have a link to view details of the person but when I click on the VIEW link I get the following error
Parse error: syntax error, unexpected 'EmployeeID' (T_STRING) in C:\Program Files\EasyPHP-12.1\www\my portable files\dss4\childdetails.php on line 6
The childdetails.php has the following code
<HTML>
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("datatest",$db);
$result = mysql_query("SELECT * FROM children;
WHERE "EmployeeID="["$EmployeeID"],$db);
$myrow = mysql_fetch_array($result);
echo "Child Name: ".$myrow["ChildName"];
echo "<br>Mother: ".$myrow["Mother"];
echo "<br>Date of Birth: ".$myrow["DateOfBirth"];
?>
</HTML>
Since the first form to list the personnel works I believe the problem is in childdetails.php on line 6 as returned by the server but I simply don’t know how to fix it.
Note: a person can have more than one child as well as having more than one wife
Help please
I would say more like.
$result = mysql_query("SELECT * FROM children WHERE EmployeeID='$EmployeeID'");
// as far $EmployeeID is actualy set before running a query
//but as comment says don't use mysql better something like this
<?php
$mysqli = new mysqli('localhost', 'root', 'my_password', 'my_db');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM children WHERE EmployeeID=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $EmployeeID);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($Employee);
/* fetch value */
$stmt->fetch();
printf($Employee);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
To begin with, your query is wrong, you're telling the sql that your script is over and that it should start executing something new. I'll show you how to do it properly here below.
Also, don't use mysql specific syntax, It's outdated and can get you into real trouble later on, especially if you decide to use sqlite or postgresql.
Also, learn to use prepared statements to avoid sql injection, you want the variables to be used as strings into a prepared query, not as a possible executing script for your sql.
Use a PDO connection, you can init one like this:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
Now you should construct a query that can be used as a prepared query, that is, it accepts prepared statements so that you prepare the query and then you execute an array of variables that are to be put executed into the query, and will avoid sql injection in the meantime:
$query = "SELECT * FROM children WHERE EmployeeID = :employeeID;"; // Construct the query, making it accept a prepared variable.
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(':employeeID' => $EmployeeID)); // Here you insert the variable, by executing it 'into' the prepared query.
$statement->setFetchMode(PDO::FETCH_ASSOC); // Set the fetch mode.
while ($row = $statement->fetch())
{
$ChildName = $row['ChildName'];
$Mother = $row['Mother'];
$DateOfBirth = $row['DateOfBirth'];
echo "Child Name: $ChildName";
echo "<br />Mother: $Mother";
echo "<br />Date of Birth: $DateOfBirth";
}
You should use a similar approach to receive $EmployeeID but this should help you a lot.
By the way: remember to close your break tags with a whitespace ' ' and a forwardslash like I showed you.
You
Need
change your query something like this
<HTML>
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("datatest",$db);
$result = mysql_query("SELECT * FROM children WHERE EmployeeID=" . $EmployeeID, $db);
$myrow = mysql_fetch_array($result);
echo "Child Name: ".$myrow["ChildName"];
echo "<br>Mother: ".$myrow["Mother"];
echo "<br>Date of Birth: ".$myrow["DateOfBirth"];
?>
</HTML>

Categories