I've searched the site and was unable to find an answer.
What I get in my script is an empty pulldown menu instead of the contents from the MySQL table. I'm developing/testing code in NetBeans 8.0.2 and running in Firefox 34.0.5. Here is my code (name of file is 'domains.php') and it is exactly as shown; I didn't leave anything out.
<body>
<form method="post" action="">
<select id="domain" name="domain">
<?php
// define connection variables
$DBServer = "localhost"; // server name or IP address
$DBUser = "xxxxxxxxx";
$DBPass = "xxxxxxxxx";
$DBName = "country";
$DBPort = "3306";
// create a connection to mysql
$conn = mysqli_connect ($DBServer, $DBUser, $DBPass, $DBName, $DBPort);
// check to see if a connection was made and, if yes, proceed
if (mysqli_connect_errno()) { // connection failed
echo "Database connection failed: " . mysqli_connect_error();
}
// the domain query to get all domain names
$domainQuery = "select domains from domains_subdomains_cop";
// run the query -- this works elsewhere to display the contents of a table
$resultD = mysqli_query($conn, $domainQuery) or die ("Query to get data from domain failed: "
. mysql_error());
// w/the exception of pulldown menu, the while loop works well to display records
// I've seen examples with MYSQLI_ASSOC and without it and I've tried both without success for
// pulldown menus. I use it because I haven't had any issues elsewhere in my program.
while ($row=mysql_fetch_array($resultD, MYSQLI_ASSOC)) {
$domainName=$row[DOMAINS]; // DOMAINS is the table attribute I'm trying to pull from
echo "<option>
$domainName // I accidentely put a ';' here once and that did show up in the pulldown
// menu.
</option>";
}
?>
</select>
</form>
</body>
Below is an object-oriented, mysqli prepared statements version
<form method="post" action="">
<select id="domain" name="domain">
<?php
$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName, $DBPort);
$stmt = $db->prepare("select `domains` from `domains_subdomains_cop`");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_object()){
echo "<option>".$row->domains."</option>";
}
?>
</select>
</form>
Related
Sorry for the newbie question, but I have this task which kind of got me stuck.
So, I made a database in PhpMyAdmin, created a table with data : Products(id, name, city) and created a stored procedure that will actually do a query on the table to find out the product with a certain name (which will be input-ed by the user on the web page). My stored procedure is: proc_test and takes one VARCHAR paramter.
So, how can I do this in a php script? How can i ask the user for some data, (on the site he should have like a box to type it) then click a search button, and get redirected to the page with the query results. This is my code so far:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CALL proc_test('pencil');";
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['numec'] . "<br/>";
}
}
$conn->close();
?>
Here, of course, I manually give the parameter in the script. But I don't know how to change this and ask for a user input instead. Any help is welcome!
You can use ajax to send the data from your website to the php file where you can search for it in the database and send that data back to the user. In my example, the data is being displayed on the same webpage. You could echo the link to the website and redirect the user on the webpage using JavaScript if you really wanted to but my example is just a proof of concept.
index.html
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input required type="text" id="user_input">
<button onclick="sendData()">Search</button>
<p id="result"></p>
<script>
function sendData() {
var var_params = $('#user_input').val();
$.post('test.php', {params: var_params}, function(data) {
document.getElementById('result').innerHTML = "Your search result: " + data;
});
}
</script>
</body>
</html>
test.php
<?php
if(isset($_POST['params'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname); // Create connection
if ($conn->connect_error) { // Check connection
die("Connection failed: " . $conn->connect_error);
}
$param = mysqli_real_escape_string($conn, $_POST['params']);
$sql = "CALL proc_test('$param');";
if($result = mysqli_query($conn, $sql)) {
while($row=mysqli_fetch_assoc($result)) {
echo $row['numec']. "<br/>";
}
}
$conn->close();
}
?>
I am trying trying to receive data by making a html form and then adding receiving data by $_GET method.Whenever I try to submit my data I get an error saying 'Your file was not found' in my chrome browser,so I tried opening my php page in chrome by typing "localhost/...." in my address bar and there it was displaying 'Database NOT Found'
here is my php code:-
<html>
<?php
$user_name = "root";
$password = "";
$database = "mysql"; //mysql is name of my database
$server = "localhost";
$db_handle = mysql_connect($server , $user_name, $password,"addresbook"); //adressbook is where all the tabels are
$db_found = mysql_select_db($database, $db_handle);
if (!$db_found) {
print "Database Found ";
$x=$_GET['fname'];
$y=$_GET['sname'];
$z=$_GET['address'];
$sql="INSERT INTO addresbook(First_Name,Surname,Address) VALUES('".$x."','".$y."','".$z."')";
mysql_query($sql,$db_handle);
}
else {
print "Database NOT Found ";
}
?>
</html>
here is mt html code:-
<form action="practic.php"method="get">
Firstname:<input type="text" name="fname"><br>
Lastname:<input type="text" name="sname"><br>
Address:<input type="text" name="address"><br>
<input type="submit">
</form>
btw i am using wamp server.Thanks in advance.
$db_found will be true on success, so your condition should be
if ($db_found) { // make DB changes etc.
and switch to MySQLi or PDO and use prepared statements as already mentioned, refer to the manual:
http://php.net/manual/en/mysqli.prepare.php
use mysqli_connect because mysql_connect is now deprecated.
$db_handle = mysqli_connect($server , $user_name, $password,$database);
refer here for connection
http://www.w3schools.com/php/func_mysqli_connect.asp
Hi change your code to use MysqLi or use PDO
<?php
$user_name = "root";
$password = "";
$database = "mysql"; //mysql is name of my database
$server = "localhost";
$con = mysqli_connect($server,$user_name,$password,'adresbook');//adresbook is where all the tabels are
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
// Change database to "adresbook"
$db_found = mysqli_select_db($con,'adresbook');
if ($db_found) {
print "Database Found ";
$x=$_GET['fname'];
$y=$_GET['sname'];
$z=$_GET['address'];
$sql="INSERT INTO addresbook(First_Name,Surname,Address) VALUES('".$x."','".$y."','".$z."')";
mysqli_query($con, $sql);
}
else {
print "Database NOT Found ";
}
?>
Your phpMyadmin should look like this with the database addresbook with a single s.
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) ){
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();
?>
ok so I have the following code that I am running in the python shell:
import MySQLdb
db = MySQLdb.connect(host = "xxxx",user="xxxx"password="xxxx",db="xxxx")
cur = db.cursor()
cur.execute(CREATE TABLE qqqq (asdf VARCHAR(20),fdsa VARCHAR(20))
Fairly sure the connection part is working, I'll get an error if I enter in the wrong value, or if I deny access to the database for my computer's IP address.
on the webhosting server, I have the following basic index.php file, which I have tested on a server on my computer, and I know works. when I go to the website domain, I get the following error: "Database query failed."
Any ideas why the MySQL query isn't working? My webhosting is Cpanel with godaddy.com, should I look for something else?
<?php
$dbhost = "xxxx";
$dbuser = "xxxx";
$dbpass = "xxxx";
$dbname = "xxxx";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); /*1*/
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
$query ="SELECT * FROM qqqq"; /*2*/
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed.");
}
?>
<!DOCTYPE html PUBLIC >
<html lang="en">
<head>
<title></title>
</head>
<body>
<ul>
<?php /*3*/
while($subject = mysqli_fetch_assoc($result)){
?><li><?php echo $subject['asdf'];?></li>
<?php
}
?>
</ul>
<?php
mysqli_free_result($result); /*4*/
?>
</body>
</html>
<?php
mysqli_close($connection); /*5*/
?>
You should call db.commit() to have it complete. By default, autocommit is turned off.
You also have an error in your code. The SQL should be a string.
Shouldn't the cursor execute be calling a string? You don't have quotes around your sql statement.
This line without quotas is incorrect:
cur.execute(CREATE TABLE qqqq (asdf VARCHAR(20),fdsa VARCHAR(20))
It should be
cur.execute("CREATE TABLE qqqq (asdf VARCHAR(20),fdsa VARCHAR(20))")
So test in your database whether you really have table qqqq.
You could install SQL Buddy or phpMyAdmin.