How to extract desired row from Mysql database using PHP script - php

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();
?>

Related

Check if a MySql database has been updated in PHP

I am trying to detect whether a MySql database has been updated the second it has been updated. So far I've just found triggers but it, https://www.siteground.com/kb/mysql-triggers-use/, said I need superuser privileges and, unfortunately, the domain I use is a shared server.
So currently there is one group working on inserting all user information into the database like so.
<form method="post">
-> user post data
</form>
<?php
-> post data to varibles, $x $y as examples
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "name";
// Check connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO Test (Col1, Col2)
VALUES (". $x .",". $y .")";
mysqli_close($conn);
?>
And then my group, in a separate file, is supposed to get the data from the database when it is updated. Our file set up looks like this.
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "name";
// Check connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
->trigger on column update
$sql = "SELECT Col1, Col2, time FROM Test";
$result = mysqli_query($conn, $sql);
->etc.
mysqli_close($conn);
?>
So far I've only found triggers that are in MySql but there doesn't seem to be a way to directly do it in PHP ex.
mysql> CREATE TRIGGER agecheck BEFORE INSERT ON people FOR EACH ROW;

cant show the results of query in php from mysql

Hello I am new at php and mysql and I don't know what is wrong.
I cant show the results from query and the connection with mysql is successfully connected.
I don't use wampserver I just install php,mysql and Apache separately.
Thanks in advance.
Code
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql="select * from `books`;";
$result=mysqli_query($conn,$sql);
if (!$result){
echo "query cannot execute";
};
?>
its only show me "query cannot execute"
You need to pass fourth parameter database name in mysqli_connect()
It would be
$conn = mysqli_connect($servername, $username, $password,"YOUR_DATABASE");
Read http://php.net/manual/en/mysqli.error.php to check error in query.
Read http://php.net/manual/en/mysqli-result.fetch-array.php
To fetch data from query result

Deletion of row in MySQL using php

I have been developing a CRUD application using PHP & MySQL database.
I was succeeded by creating, displaying, updation parts. But I stuck at the deletion part of a row from a database table.
I tried my best solving all the PHP shown errors but now in final it is now showing a message which I wrote to echo in case of failure.
I request someone to please help me with this problem.
Thankyou in advance.
Code I wrote for deletion:
//include database connection
include 'db_connect.php';
//$mysqli->real_escape_string() function helps us prevent attacks such as SQL injection
$query = "DELETE
FROM `grocery`
WHERE `GrocerID` ='".$mysqli->real_escape_string($_GET['id'])."'
limit 0,1";
//execute query
if( $mysqli->query($query) ){
//if successful deletion
echo "User was deleted.";
}else{
//if there's a database problem
echo "Database Error: Unable to delete record.";
}
$mysqli->close();
?>
Code I wrote for delete link in display table:
//just preparing the delete link to delete the record
echo "<a href='delete.php?id={$GrocerID}'>Delete</a>";
Code I wrote for db config:
<?php
//set connection variables
$host = "localhost";
$username = "root";
$password = "secret";
$db_name = "crud"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
die("Connection failed: " . $conn->connect_error);
exit;
}
?>
I tried this and got working, can you update the code and see if this works?
$host = "localhost";
$username = "root";
$password = "secret";
$db_name = "crud"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
die("Connection failed: " . $conn->connect_error);
exit;
}
// Delete row
if ($mysqli->query (sprintf( "DELETE FROM grocery WHERE email = '".$mysqli->real_escape_string($_GET['id'])."' LIMIT 1") )) {
printf ( "Affected Rows %d rows.\n", $mysqli->affected_rows );
}
I hope this helps.
Provide a connection :
if( $mysqli->query($con, $query) ){

My data is not being stored in my database

I can't seem to figure out what is wrong with my code. I am trying to get it to take the input from
<form id="contact-form" action="emails.php" method="post">
<input placeholder="Please enter your email address" name="emailz" type="email" tabindex="2" required>
<input type="submit" name="submit" id="contact-submit" value="Subscribe">
</form>
and have it saved into my database.
Here is my PHP file:
$servername = "localhost";
$username = "poweilup";
$password = "bloop";
$dbname = "poweilup_emails";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$insert = "INSERT INTO emails(addressEmail) VALUES($_POST '$emailz')";
$conn->close();
To use MySQLi in a safe way, it's best to use Prepared Statements. This will prevent your users from inserting SQL injection or, possibly by mistake, inserting characters that can cause problems to your MySQL server.
As you can see in the script below, I'm first preparing the SQL query, using a placeholder "?" for the item variable. After I'm binding the parameter(variable) to this placeholder.
Now the query is setup correctly, it's time to execute it. It's always a good habit to close anything left open once done, as it will free up memory that's no longer in use.
<?php
/* DB Info */
$servername = "localhost";
$username = "poweilup";
$password = "bloop";
$dbname = "poweilup_emails";
/* MySQLi Object */
$conn = new mysqli($servername, $username, $password, $dbname);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Prepare query */
if ($stmt = $conn->prepare("INSERT INTO emails (addressEmail) VALUES (?)")){
/* Bind POST data */
$stmt->bind_param("s", $_POST['emailz']);
/* Run query */
$stmt->execute();
/* Close statement */
$stmt->close();
}
/* Close connection */
$conn->close();
?>
Here is how you do the insert -
$servername = "localhost";
$username = "poweilup";
$password = "bloop";
$dbname = "poweilup_emails";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO `emails`(`addressEmail`) VALUES(?)");
$stmt->bind_param('s', $email);
$email = $_POST('emailz');
$stmt->execute();
First you prepare the query and leave placeholders for the item variables. The you bind each parameter(variable) and then declare them. Finally you execute the query.
First check if the user hasn't missed anything:
if (isset($_POST['emailz']) { //code here.. };
In the code here... section, store the value of emailz in a variable like this:
$emailz = $_POST['emailz'];
Of course this may be insecure for more important data like passwords. You should use the hash() function then.
For inserting the variable in DB, try this:
$query = "INSERT INTO `user` (emailz) VALUES ('$emailz')"; $result = mysql_query($query); //inserts the variable in the DB.

php access error using credentials that work in another script

I'm an iOS developer trying to update a bit 'o php to work with the mysqli_* stuff instead of the deprecated mysql_* stuff.
I know next to nothing about php/mysql, and I'm stuck. I'm using a script found at http://www.w3schools.com/php/php_mysql_select.asp, with changes to reflect my field names etc
When I call the following from a browser I get an access error (Connection failed: Access denied for user 'whoisit7'#'localhost' (using password: YES)). The server name, password and username etc I'm using all work with an existing script in a browser but not with this new one.
Can anyone point me at what I'm getting wrong?
<?php
$servername = "localhost";
$userName = "whoisit7_ios";
$password = "blahblahblah";
$dbName = "whoisit7_scathing";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT name, latitude, longitude FROM location where status = 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "name: " . $row["name"]. " - latlong: " . $row["latitude"]. " " . $row["longitude"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
In PHP, variable names are case-sensitive. So, Change your connection variable names to:
$servername = "localhost";
$username = "whoisit7_ios";
$password = "blahblahblah";
$dbname = "whoisit7_scathing";
Read it if you are new to PHP: http://php.net/manual/en/language.variables.basics.php
Php is case sensitive, so change the below line from:
$conn = mysqli_connect($servername, $username, $password, $dbname);
to
$conn = mysqli_connect($servername, $userName, $password, $dbName);
You have made error in $username which is $userName and $dbname which should be $dbName as you declared above.
Just change -->
localhost to 127.0.0.1 //you need to change params in mysql config if u want to use it as localhost
And
$username to $userName //As u need to keep these variables similar :)
this Problem seems to be coming from database privileges as i have also have encountered this before. Give this fix a try.
GRANT ALL PRIVILEGES ON database_name TO usernamehere#host IDENTIFIED BY 'yourpassword';
FLUSH PRIVILEGES;
Just change the lower case letters to your own credentials.

Categories