Connecting MYSQL using PHP - php

I can't run my codes.
It says:
syntax error, unexpected '$query' (T_VARIABLE).
Code
<?php
$hostname="localhost";
$username="";
$password="";
$dbname="thesis";
$usertable="product";
$yourfield="product_id";
msql_connect($hostname,$username,$password) or die ("<html><script>
language='Javascript'>alert('Unable to connect to database!.'),history.go(-1)</script></html>")
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if($result)
{
while ($row = mysql_fetch_array($result))
{
$name = $row["$yourfield"];
echo "Name: ".$name."</br>";
}
}
?>

msql_connect($hostname,$username,$password) or die ("<html><script>
language='Javascript'>alert('Unable to connect to database!.'),history.go(-1)</script></html>")
should have a semicolon.
Replace it with this:
msql_connect($hostname,$username,$password) or die ("<html><script>
language='Javascript'>alert('Unable to connect to database!.'),history.go(-1)</script></html>");

<?php
$hostname = "localhost";
$username = "";
$password = "";
$dbname = "thesis";
$usertable = "product";
$yourfield = "product_id";
$mysqli = new mysqli($hostname, $username, $password, $dbname);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT * FROM $usertable")) {
while ($row = mysql_fetch_array($result))
{
$name = $row["$yourfield"];
echo "Name: ".$name."</br>";
}
/* free result set */
$result->close();
}
$mysqli->close();
http://php.net/manual/en/mysqli.query.php

Related

PHP and mysql connection not working

I have written following code to connect mysql in php but I am not getting output.
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$mysql_conn = new mysqli($servername, $username, $password);
if ($mysql_conn->connect_error) {
die("Connection failed: ". $mysql_conn->connect_error);
}
echo "Connected successfully";
$name = $_POST["microorganism"];
echo $name;
$db_selected = mysql_select_db('yieldofvanillin', $mysql_conn);
if (!$db_selected){
die ('Can\'t use : ' . mysql_error());
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
$result = $mysql_query($query);
while ($line = myql_fetch_array($result, MYSQL_ASSOC)) {
echo $line["Substrate"];
echo $line["products"];
echo $line["Microorganism"];
echo $line["yield"];
echo $line["Reference"];
}
mysql_close($mysql_conn);
?>
The database name is "yieldofvanillin" and it has five column. I an getting output Connected successfully. After that no output. Please let me know the bug in code.
i have remove errors. which i mention in comments. Code Reference PHP Manual. you should read this manual (strongly recommended)
<?php
$mysqli = new mysqli("localhost", "root", "pravin", "yieldofvanillin");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["Substrate"];
echo $row["products"];
echo $row["Microorganism"];
echo $row["yield"];
echo $row["Reference"];
}
/* free result set */
$result->free();
}
you're mixing mysqli and mysql libraries.
the code should be:
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$mysql_conn = new mysqli($servername, $username, $password);
if (mysqli_connect_errno()) {
die("Connection failed: ". mysqli_connect_error());
}
echo "Connected successfully";
$name = $_POST["microorganism"];
echo $name;
$db_selected = mysqli_select_db($mysql_conn,'yieldofvanillin');
if (!$db_selected){
die ('Can\'t use : ' . mysqli_error($mysql_conn));
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
$result = mysqli_query( $mysql_conn,$query);
while ($line = mysqli_fetch_assoc($result)) {
echo $line["Substrate"];
echo $line["products"];
echo $line["Microorganism"];
echo $line["yield"];
echo $line["Reference"];
}
mysqli_close($mysql_conn);
?>
Remove error in your code.Read carefully php manual.
<?php
$servername = "localhost";
$username = "root";
$password = "pravin";
$db = "yieldofvanillin";
// Create connection
$mysqli = new mysqli($servername, $username, $password, $db);
/* connection string*/
if ($mysqli->connect_errno) {
die("Connection failed: " . $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM vanillin WHERE Microorganism = '$name' ";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row["Substrate"];
}
$result->free();
}
$mysqli->close();
?>
Your output not showing because mysql_fetch_array is not correct.Because you are mixing mysql_ and mysqli_ functions and you called myql_fetch_array that doesn't exist in mysqli. MySQL and MySQLi are two different PHP extensions and they cannot be mixed. Because the former is deprecated in mysqli

Need help to display data from mysql database

I would need some help with showing data that I have on my database but I can't seen to be able to.`
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
$connect = mysqli_connect($servername, $username, $password, $dbname) or die ("connection failed");
//Query
$query = "SELECT * FROM 'Students'";
mysqli_master_query($dbname, $query) or die ("Error while Query");
$result = mysqli_master_query($dbname, $query);
$row = mysql_fetch_array($result);
while ($row = mysql_fetch_array($result)) {
echo "<p>".$row['Name']."</p>";
};
mysql_close($connect);
?>`
I am pretty new to this so I could have missed something simple. Any help appreciated.
Below is a sample code of the normal procedure to connect to a database and to select data from it. Please follow this type of coding since MySQL is now deprecated and MySQLi is used.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
For further reference check out http://php.net/manual/en/book.mysqli.php and also https://www.w3schools.com/php/php_mysql_insert.asp

Drop-down PHP-MySqli error

I want to make a dropdown list and i use this codes:
<div class="selector">
<?php
include ("connect.php");
$db = new mysqli('localhost', $dbuser, $dbpass, $dbnam);
?>
<div class="label">Select Name:</div>
<select name="names">
<option value = "">---Select---</option>
$stmt = $db->prepare("SELECT `name` FROM `monitoare`");
$stmt->execute();
$stmt->bind_result($name);
while ($stmt->fetch()){
echo "<option value='$name'></option>";
}
$stmt->close();
?>
</select>
as index.php
and this:
<?php
$dbname = 'mydabase';
$dbuser = 'myuser';
$dbpass = 'mypass';
?>
as connect.php and after i launch this the drop stays just with ---select--- as an option
I reckon that you should do all of this using either MySQLi procedural or object oriented rather trying to do with prepared statements.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
You can save this in a 'connect.php' file and include it in the relevant file.
The solution to getting dropdown instead of --select-- without any errors is shown below
echo "<select name='names'>"
$sql = "SELECT `name` FROM monitoare";
$result =mysqli_query($db, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<option value=".$row['name'].">".$row['name']."</option>";
}
} else {
echo "No results found";
}
?>
For further reference check out http://php.net/manual/en/book.mysqli.php and also https://www.w3schools.com/php/php_mysql_insert.asp
Here's a (corrected) example, adapt to your code :
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$host = ""; /* your credentials here */
$user = ""; /* your credentials here */
$pwd = ""; /* your credentials here */
$db = ""; /* your credentials here */
/* connect to DBd */
$mysqli = mysqli_connect("$host", "$user", "$pwd", "$db");
if (mysqli_connect_errno()) { echo "Error connecting to DB : " . mysqli_connect_error($mysqli); }
$query = " SELECT `name` FROM `monitoare` ";
$stmt = $mysqli->prepare($query);
$stmt->execute();
$stmt->bind_result($name);
$stmt->store_result();
if ($stmt->num_rows > 0) { /* we have results */
echo"<select name=\"names\"><option value=\"\">---Select---</option>";
while($stmt->fetch()){
echo "<option value=\"$name\">$name</option>";
}
echo"</select>";
}
else
{ echo"[ no data ]"; }
?>

is it possible select Database 2 simultaneously in the same conection

I have problem with 2 select Databases from the same connection simultaneously, the code is:
#$dbmssSQLGestasa_conn = mssql_connect($servidor, $usuario, $contra);
if(!$dbmssSQLGestasa_conn){
header("Location:nobase.php");
exit();
}
mssql_select_db('GESTASA', $dbmssSQLGestasa_conn);
the code of the other connection:
#$dbmssSQLTasa_conn = mssql_connect($servidor, $usuario, $contra);
if(!$dbmssSQLTasa_conn){
header("Location:nobase.php");
exit();
}
//Apertura de la base de datos
mssql_select_db('TASA', $dbmssSQLTasa_conn);
it dont work and give me error "(severity 16)".
is It possible do 2 or more selections databases en la same connection mssql?
Dont use mysql_select_db();
In Mysqli :
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM test123.posts"; // databse.tablename
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$mack[] = $row;
}
}
$sql1 = "SELECT * FROM portal.abouts"; // databse.tablename
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
// output data of each row
while($row1 = $result1->fetch_assoc()) {
$mack1[] = $row1;
}
}
echo "<pre>";
print_r($mack);
print_r($mack1);
echo "</pre>";
$conn->close();
You can easily use 2 databases in same time with Below Codes
I'm Using variables as Capital word But you can use your own variable words.
<?php
define('HOST', "YOURHOSTNAME");
define('USER', "YOURHOSTNAME");
define('PASS', "YOURHOSTNAME");
define('DATABASE1', "NAMEOFDATABASE1");
define('DATABASE2', "NAMEOFDATABASE2");
$DATABASE1 = mysqli_connect(HOST, USER, PASS, DATABASE1);
$DATABASE2 = mysqli_connect(HOST, USER, PASS, DATABASE2);
if(!$DATABASE1){
die("DATABASE1 CONNECTION ERROR: ".mysqli_connect_error());
}
if(!$DATABASE2){
die("DATABASE2 CONNECTION ERROR: ".mysqli_connect_error());
}
$sql = "SELECT * FROM TABLE"; /* You can use your own query */
$DATABASE1_QUERY = mysqli_query($DATABASE1, $sql);
$DATABASE2_QUERY = mysqli_query($DATABASE2, $sql);
$DATABASE1_RESULT = mysqli_fetch_assoc($DATABASE1_QUERY);
$DATABASE2_RESULT = mysqli_fetch_assoc($DATABASE2_QUERY);
/* SHOW YOUR RESULT HERE WHICH DATABASE YOU WANT FROM */
echo $DATABASE1_RESULT['id'];
echo $DATABASE2_RESULT['id'];
/*After complete your all work don't forgot about close database connections*/
mysqli_close($DATABASE1);
mysqli_close($DATABASE2);
?>

MySQLI LOOP DATA

I want to get all the records from the while loop. I'm unable to get all the rows from the query. It shows only the first row.
Is there anything I was going wrong in my code.
function Connect($DB_HOST = 'localhost', $DB_USER = 'root', $DB_PASS = '', $DB_NAME = 'bodhilms')
{
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
return $mysqli;
}
function GetCoeficient($coeficient = false, $con)
{
if(!$con)
return 0;
$result = array();
$sql[] = "SELECT * FROM users ";
if($coeficient != false)
$sql[] = "WHERE username = '".$coeficient."' ORDER BY u.id";
//print_r($coeficient);
$query = $con->query(implode(" ",$sql));
//print_r($query);
while($row = $query->fetch_assoc())
{
$result[] = $row;
}
return (!empty($result))? $result : 0;
}
$con = Connect();
$result = GetCoeficient($coeficient,$con);
$username = $result[0]['username'];
$firstname = $result[0]['firstname'];
$lastname = $result[0]['lastname'];
$email = $result[0]['email'];
First of all,to make sure the infomation of mysql is right,like port.
and I wonder the code of you $result = Getcourse($coeficient,$con);, how the var coeficient come from.Then
You can try the code below:
$mysqli=new mysqli("localhost","root","root","123");
$query="select * from test";
$result=$mysqli->query($query);
if ($result) {
if($result->num_rows>0){
while($row =$result->fetch_array() ){
echo ($row[0])."<br>";
echo ($row[1])."<br>";
echo ($row[2])."<br>";
echo ($row[3])."<br>";
echo "<hr>";
}
}
}else {
echo 'failure';
}
$result->free();
$mysqli->close();

Categories