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);
?>
Related
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.
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.
I'm trying to put through a basic search through my Database based on a user entry, and I could not get it to work, so I'm doing a hard coded search just so I can get it to work... and I can't. My code is as follows:
<?php
$db_connection = mysqli_connect("HOST", "USERNAME", "PASSWORD", "DATABASE");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$data = mysql_query($db_connection, "SELECT * FROM card_collection WHERE ID='1207409700'");
while( $card = mysql_fetch_array( $data ) ) {
echo $card['Name'], '<br />';
}
mysql_close();
?>
I've double checked spelling for everything linked to the database. The ID I'm basing my search from is the first item in my database.
You are using the mysqli_connect to database and then you are using the mysql_query to execute the query it should be mysqli_query
You code should be:
$data = mysqli_query($db_connection, "SELECT * FROM card_collection WHERE ID='1207409700'");
while( $card = mysqli_fetch_array( $data ) ) {
echo $card['Name'], '<br />';
}
mysqli_close();
Replace the mysql with the mysqli. This may be your problem.
I personally use PDO and not mysqli, but is the problem perhaps that you use mysql_query and mysql_fetch_array, instead of mysqli_query and mysqli_fetch_array? Note the missing i
Edit: dangit, beat to the punch :)
<?php
$db_connect = mysqli_connect("host", "user", "pass", "db");
if($db_connect){
$data = mysqli_query($db_connection, "SELECT * FROM card_collection WHERE ID='1207409700'");}
else {"Not Connected to db";}
while( $card = mysqli_fetch_array( $data ) ) {
echo $card['Name'], '<br />';
}
mysqli_close();
?>
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>
I created a script on a windows platform which connects to the mysql database and returns the results of a table. A very basic script which I wrote to simply test my connection worked. The script works fine on my windows machine but not on my new mac. On the mac it simply does not display any records at all.
I know that the database connection has been established because there is no error but I can not see why the result set is not being displayed on screen, as I said it worked fine on my windows machine.
The Mac has mysql (with data) and apache running for php.
Please could someone help as I have no idea what to do now?
Script below:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'test';
mysql_select_db($dbname);
mysql_select_db("test", $conn);
$result = mysql_query("SELECT * FROM new_table");
while($row = mysql_fetch_array($result))
{
echo $row['test1'] . " " . $row['test2'] . " " . $row['test3'];
echo "<br />";
}
mysql_close($con);
There are various things you could do to debug this.
Show all PHP errors.
ini_set('display_errors','On');
ini_set('error_reporting',E_ALL);
Catch all possible MySQL errors, not only the ones concerning whether you connected successfully.
mysql_select_db("test", $conn) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("SELECT * FROM new_table") or die(mysql_error());
Side note: There's no reason to select which database you wish to use twice.
Its very difficult to see what is wrong ... so add some basic error checking, like changing this
$result = mysql_query("SELECT * FROM new_table");
to
$result = mysql_query("SELECT * FROM new_table") or die(mysql_error());
This will show you the error you are getting from your query (if there is one) .. you ill see in the documentation for mysql_query that it returns a boolean if there was an error
Also note that you have a mistake in the variable name for closing the MySQL Connection :
mysql_close($con);
should be
mysql_close($conn);
Check to see if the SELECT query was successful or not before fetching the rows.
<?php
$result = mysql_query("SELECT * FROM new_table");
if(!$result)
die('SQL query failed: ' . mysql_error());
The only thing i can think of is that Mac file system is case sensitive while windows isn't so it might be that you mispelled the name of the table. In any cas you should do
$result = mysql_query("SELECT * FROM new_table") or die("error:".mysql_error());
to view the error
I think you should use the improved PHP mysql driver
try
{
$db = new mysqli("localhost","root","root","test");
if ($db->connect_errno) {
throw new Exception($db->connect_error);
}
if ($result = $db->query("SELECT * FROM new_table")) {
printf("Select returned %d rows.\n", $result->num_rows);
while($row = $result->fetchAssoc())
{
echo $row['test1'] . " " . $row['test2'] . " " . $row['test3'];
echo "<br />";
}
/* free result set */
$result->close();
}
$db->close();
}
catch(Exception $e)
{
printf("Database Error: %s\n", $e->getMessage());
exit();
}