I want to improve my non-existing PHP knowledge. To do so I created a MySQL DB and a connection.php file with an SQL query (please ignore SQL injection comments for now, I am aware of it). I trying to figure out, how I can split the connection from the actual query.
<?php
header("Access-Control-Allow-Origin: *");
$username = "root";
$password = "root";
$host = "localhost";
$database="test";
$connection = mysqli_connect($host, $username, $password, $database);
$myNodesQuery = "
SELECT * FROM nodes";
$query = mysqli_query($connection, $myNodesQuery);
if ( ! $query ) {
echo mysqli_error();
die;
}
$data = array();
for ($x = 0; $x < mysqli_num_rows($query); $x++) {
$data[] = mysqli_fetch_assoc($query);
}
//echo json_encode($data, JSON_FORCE_OBJECT);
echo json_encode($data);
mysqli_close($connection);
My thoughts were to create another PHP file and add $connection = mysqli_connect (require('connection.php')) to receive the connection string. Unfortunately, I receive a path error.
Keeping your code as is then:
File connection.php:
<?php
$username = "root";
$password = "root";
$host = "localhost";
$database="test";
$connection = mysqli_connect($host, $username, $password, $database);
The main file
<?php
header("Access-Control-Allow-Origin: *");
require 'connection.php';
$myNodesQuery = "
SELECT * FROM nodes";
// whatever follows
...
Please note that - unless you use a framework - it would be much better if you build your reusable connection class or connection-returning function. And BTW consider using the far superior PDO.
Related
I can't Update my Database with PHP. I don't get any errors but it doesn't change anything!
Here is my file:
<?php
include_once 'dbh.inc.php';
?>
<?php
$id = $_GET['verId'];
$name = $_GET['verName'];
echo $id;
echo $name;
$sql = "UPDATE allusers SET ver = '1' WHERE idUsers = '$id';";
?>
The variables are defined and work.
Here's the dbh.inc.php file:
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "loginsystem";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
die("Connection failed: ".msqli_connect_error());
}
?>
Other files that use dbh.inc.php work fine.
Thanks for your help.
You need to execute your SQL, but the way you are using MySQLi is very wrong. Let me show you how to get started with a simple query.
First in your dbh.inc.php (you should name it properly too) you should have the following code:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new \mysqli("localhost", "root", "", "loginsystem");
$conn->set_charset('utf8mb4');
Do not use root for connection. Create a valid MySQL user with a proper password.
Then in your main PHP file, you can use it as follows:
<?php
include_once 'dbh.inc.php';
$id = $_GET['verId'];
$name = $_GET['verName'];
echo $id;
echo $name;
// prepare -> bind data -> execute
$stmt = $conn->prepare("UPDATE allusers SET ver='1' WHERE idUsers=?");
$stmt->bind_param('s', $id);
$stmt->execute();
I used here what is called a prepared statement. You can learn more about MySQLi here: https://phpdelusions.net/mysqli_examples/update
I am facing an issue with PHP which doesn't perform one query in my script.
The SQL query works well in my MYSQL console but nothing is happening. Year column stays NULL:
$UpdateYear='UPDATE `pat` SET `Year` = SUBSTRING(`Prepa`,7,4)';
mysqli_query($connWarehouse,$UpdateYear) or die(mysqli_error($connWarehouse));
I don't know what I am doing wrong. Here the full script:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db="datawarehouse";
// Create connection
$connWarehouse = new mysqli($servername, $username, $password, $db);
// Check connection
if ($connWarehouse->connect_error) {
die("Connection failed: " . $connWarehouse->connect_error);
}
$UpdateYear='UPDATE `pat` SET `Year` = SUBSTRING(`Prepa`,7,4)';
mysqli_query($connWarehouse,$UpdateYear) or die(mysqli_error($connWarehouse));
mysqli_close($connWarehouse));
?>
I finally managed to solve. I don't know if it is a correct way to do it. I have to open a new connection to the database in order to perform.
alter.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db="datawarehouse";
// Create connection
$connWarehouse = new mysqli($servername, $username, $password, $db);
// Check connection
if ($connWarehouse->connect_error) {
die("Connection failed: " . $connWarehouse->connect_error);
}
$AddYear='ALTER TABLE `pat` ADD COLUMN `Year` YEAR;';
mysqli_query($connWarehouse,$AddYear) or die(mysqli_error($connWarehouse));
mysqli_close($connWarehouse));
include 'uppat.php';
?>
uppat.php
<?php
require_once 'config-datawarehouse.php';
$UpdateYear='UPDATE `pat` SET `Year` = SUBSTRING(`DatePrepa`,7,4)';
mysqli_query($conn,$UpdateYear) or die(mysqli_error($conn));
mysqli_close($conn);
?>
On that way it performed the update query.
Can any of you guys help me to reorganize this code? I'll try to explain the problem below.
I have a db_connection.php wich includes the following (just my db info and don't worry, i am just using it locally):
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=webappeind;charset=utf8','root','');
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
But the problem is i have the following file that also includes my db info, but i do not know how to reorganize my code to get it working with my separate php file.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webappeind";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM zoekopdrachten ORDER BY titel DESC LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output gegevens van elke rij
while($row = $result->fetch_assoc()) {
echo "<div class='recenttoegevoegd'>"."<a href='#'>".$row["titel"]."</a>"."</div>";
}
} else {
echo "0 resultaten";
}
?>
You can put the connection information in a separate file called, say, conn.php where you mention the code related to database opening, including credentials. Then, in the calling file, say putdata.php, you use the "require" or "require_once" command to include that conn.php. Let the conn.php file return a connection. Somewhat like this :
<?php
function GetMyConn() {
$server_name = "localhost";
$db_name = "db_name_goes_here";
$db_user = "user_name_goes_here";
$db_pass = "password_goes_here_muahhhaa";
$db_full_addr = "mysql:host=" . $server_name . ";" . "dbname=" . $db_name;
$MyConn = new PDO($db_full_addr, $db_user, $db_pass);
$MyConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $MyConn;
}
?>
In the calling file, you would say, something like :
require_once "GetConn.php";
$MyConnHere = GetMyConn();
$SqlHere = "Sql Statemetn goes here...."
$SqlHere2 = $MyConnHere->prepare($SqlHere);
$SqlHere2->execute();
Also, I suggest you can download the source code of some open source PHP application, such as mantissa, and see how they have organized their code files, folders and settings.
I have created one HTML form which takes input from user ,Now I need to search user inputed name in Mysql database and print details related to that user inputed name which is stored in Mysql database.
Below script is creating HTML form to take user input, Saved as "ProcessTracking.html".
<form action="details.php" method="get"/>
<h3 align="center"><FONT color=#CCFF66>ENTER SO NUMBER</h3>
<p align="center">
<input type="text" id="SO_Number" name="SO_Number"/>
</p>
<div style="text-align:center">
<button type="submit" value="SEARCH">
<img alt="ok" src=
"http://www.blueprintcss.org/blueprint/plugins/buttons/icons/tick.png"/>
SEARCH
</button>
</form>
Below PHP script named as "details.php"
<?php
$userinput = $_GET['SO_Number'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE SO_Number = '$userinput'") or die(mysqli_error($conn));
$row = mysqli_fetch_assoc($result);
#printf ("SO_Number: %s \n",$row["SO_Number"])
#print_r($row);
printf ("SO_Number:");
printf($row["SO_Number"]);
printf ('--||--');
printf ("Name:");
printf($row["Name"]);
printf ('--||--');
$conn->close();
?>
Firstlly you are not using the $_GET['SO_Number'] parameter in a WHERE of SQL statement. Secondlly you are using both mysql and mysqli which are totaly diffrent and don't work together. For usage see mysqli_fetch_row() and mysqli_query(). Also use print_r($row);.
Here is the corrected code:
<?php
$userinput = $_GET['SO_Number'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE SO_Number = '$userinput'") or die(mysqli_error($conn));
$row = mysqli_fetch_row($result);
print_r($row);
$conn->close();
?>
EDIT: Added code example.
You have mixed mysql and mysqli api together. Try using either one.
Note: mysql api is deprectaed as of php 5.5.0
1st Error
As saty says it is because of the syntax error you have in this line
print_r"$row";
which should be as print_r($row)
2nd Error
You're mixing mysql & mysqli
I am not sure about the table that you have.
Recommendation :
I would recommend you to turn on the error_reporting if not those errors will be in your errors_log file
Also for debugging your sql, you can first construct your sql query, run in the phpmyadmin or related tools for your query, then fire the query and make this done.
Note :
If you are using these code in online then the error_log will be in the directory where you execute this page. (But it may change according to your hosting)
If you are running in local machine the error log may locate according to the server you use...
You can find by printing the php's configuration by phpinfo and find for
error_log
May this thing will fix your issue
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ProcessTrackingSystem";
$so = $_POST['SO_Number'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT * FROM ProcessDetails WHERE SO_Number=$so");
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
print_r($row[SO_Number]);
$conn->close();
?>
I'm getting the error: No database selected
Here is the code:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database_name = "Student";
mysql_connect($host, $user, $password);
mysql_select_db($database_name);
?>
This code is for php-connect.php class and for the form:
<!DOCTYPE html>
<html>
<body>
<?php
//load database connection
include("php-connect.php");
$id = "1";
$name = "Elena";
$city = "Lahore";
//Command to insert into table
$query = "INSERT INTO studentdata (id,name,city) VALUES ('$id','$name','$city')";
//run the query to insert the person.
$result = mysql_query($query) OR die(mysql_error());
//let them know the person has been added.
echo "Data successfully inserted into the database table ... ";
?>
</body>
</html>
This is the code for the form.. I've tried a lot of things to fix this error but it does not work. Is there any problem with my database?
Try this...
<?php
$host = "localhost";
$user = "root";
$password = "";
$database_name = "Student";
$mLink = mysql_connect($host, $user, $password) or die(mysql_error());
mysql_select_db($database_name , $mLink);
another file
<?php
require 'php-connect.php';
//...... etc..
but, read this first:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_select_db()
PDO::__construct() (part of dsn)
http://br.php.net/mysql_select_db