I am having trouble creating a general MySQLi query box, where the results, regardless of the type of query, are output in another textarea - similar to the textarea from the SQL tab in PHPMyAdmin.
For example:
I would like to display a textarea on my page.
User enters ANY MySQL code, whether it be SELECT, UPDATE, DELETE, etc.
Results are displayed in a results textarea, for example, if they enter a SELECT query, they get the results, if they enter a DELETE, they will get a # of deletions.
Functions just like the SQL tab of PHPMyAdmin.
Is there a simplified way to do this? Or do I need to detect their query, and return results depending on an algorithm that I have to write (which I can do, I'm just trying to avoid all that coding).
This is what I've tried last:
$mysqli = new mysqli($host, $username, $pw, $dbname);
if ($mysqli->connect_errno) {
echo "BAD CONNECTION!";
} else {
$result = $mysqli->query($query);
print_r($result);
mysqli_free_result($result);
}
$mysqli->close();
I also tried:
echo $result
Thanks!
There is no simple way to do what you need. Try to use some PHP open source DB libraries like DiBi (http://dibiphp.com/cs/). But you will still need to write some code. This just makes it easier.
Related
I was wondering if some one could direct me on the right path to take because every way I have tried has failed or really broken my code. To keep it simple I have page with a dynamically created select box populated with peoples names from a mySQL database its element id is 'insert'. This page also holds the php query
my query on the database works if I hard code a name in but I want to pass it as a variable from the select box. I can't seem to get it to post my variable and return me an id.
heres my query
<?php
function getElementById($id) {
$xpath = new DOMXPath(NEW domDocument);
return $xpath - > query("//*[#id='$id']") - > item(0);
}
$insertName = getElementById('insert');
printf($insertName);
$con = mysqli_connect("localhost", "root", "", "karaoke");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$sql = "Select id FROM queue where singer = '$insertName'";
$result = mysqli_query($con, $sql) or die("Bad SQL: $sql");
while ($row = mysqli_fetch_assoc($result)) {
$insertAt = ("{$row['id']}");
printf($insertName);
printf($insertAt);
};
?>
whats the best way to get my variable sent to the script and then return me the answer.
thanks
You can use either the POST or GET form methods to send data from your HTML form to your PHP script. In the form element, you will want to set the action to your PHP script like so: <form action = 'your_php_file.php' method = 'GET or POST'>. This means that when the form is submitted, you can get the data from this PHP file. Then, in your PHP, you will want to use the global variable for either POST or GET (depending on which you have used for the form method) to get the value from the select box. Using this method means you can replace your GetById function and assign the value from the form to the $insertName variable using the superglobals.
Another problem in your code is that you use your PHP variables in your SQL query. This means that your code is open to an SQL injection which could lead to problems such as people getting all of the database info (which is bad for a database storing poorly encrypted/hashed passwords, or even storing them in plain text)or could even lead to your database being deleted. To avoid this, you should use prepared statements and parameters whereby the statement is sent first without the variable and the variable is bound after.
Also, take a look at the links above about POST and GET and also about the PHP global variables which will allow you to get the data from your HTML form. Also, here are some links which explain prepared statements and parameters so that you can write more secure PHP code:
Mysqli prepare statement used to prepare the statement. The use of question marks are as placeholders as you later bind your variables to the query.
Mysqli Bind Param used to add in the variable to the SQL statement after the statement has been prepared which prevents SQL injection.
That's all for now, but be sure to ask any questions you may have and I will try my best to answer them all.
EDIT
ADDED CODE - hopefully will demonstrate what you were after, there are some small changes that may need to be made. There may be some extra code needed to fit in with any other code you have, but this should demonstrate the principle of POST and prepared statements with parameters. Written in OOP as opposed to your procedural as I find it cleaner and easier (personal opinion). If there are any problems integrating this be sure to tell me about any errors or issues/further questions. I too am fairly new to PHP.
<?php
$insertName = $_POST['insert']; // Get the value of the select box which will need to have the attribute 'name = "insert"' by POST
printf($insertName);
$con = new mysqli("localhost", "root", "", "karaoke");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$sql = "Select id FROM queue where singer = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param("s", $insertName); //Binds the string insertName to the question mark in the query
$stmt->execute();
while ($row = $stmt->fetch_assoc()) { // Left as was because syntax is different from PDO which I use. Therefore, I am assuming this part is correct.
$insertAt = ("{$row['id']}");
printf($insertName);
printf($insertAt);
};
?>
I have a simple form that needs a list of stops in the textarea and returns an id for each on the right hand side. This is my screenshot on localhost...I have the same table names, column names, number of records on both localhost and live server.
Here's the screenshot of the same page with same query on live server...
Here's the code I am using on both pages
$conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
if(isset($_POST["busnumber"], $_POST["busroute"])){
$stops = explode(PHP_EOL, $_POST["busroute"]);
$sql = 'SELECT * FROM stops WHERE stop_name LIKE :stop';
$statement = $conn->prepare($sql);
$statement->setFetchMode(PDO::FETCH_ASSOC);
foreach($stops as $stop){
$statement->bindValue(':stop', $stop);
$statement->execute();
$results = $statement->fetchAll();
foreach($results as $result){
echo $result['stop_id'].' '.$result['stop_name']."</br>";
}
}
}
As you can see, it returns the ID of the last row only on the live server. Can someone please tell me how this is possible and what I am missing?
EDIT 1
Notice what happens when I reverse the data entered in the text area
The localhost shows both the ids now
Guess what the server shows after reversing? Only the LAST ROW!
You don't need setFetchMode(). In the time I've used PDO I always had the best results with just using bindParam() and fetch() with the most default setup of PDO, which means just setting the errormode to exception and charset to utf8 like this:
try
{
$con = new PDO("mysql:host=".$host.";dbname=".$db_name, $user, $password);
}
catch(PDOException $e){
die("ERROR ". $e->getMessage());
}
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->exec("SET NAMES utf8");
Fetching any results like this
while($r = $statement->fetch())
{
echo $r['id'];
}
Any time when someone has used a different set up, I've noticed they've faced problems.
Try this, perhaps.
This is very simple. Please check your live db via phpmyadmin if you have access and from phpmyadmin run your queries like you are running it from php code. May be you have some restrictions of mysql or php on live. And also check your db versions on localhost and live with php versions too. Let me know the results of phpmyadmin queries thanks!
Just guessing the problem. I don't really think if this answer is correct. So please pardon me in advance.
PDOStatement::fetchAll() returns an array that consists of all the rows returned by the query. From this fact we can make two conclusions:
This function should not be used, if many rows has been selected. In
such a case conventional while loop ave to be used, fetching rows
one by one instead of getting them all into array at once. "Many"
means more than it is suitable to be shown on the average web page.
This function is mostly useful in a modern web application that
never outputs data right away during fetching, but rather passes it
to template.
Source: PDO Tutorial
I FIXED the error. I have answered it in detail on a different post and I am linking to that post from HERE Thank you all for your time and answers
I'm currently doing a school project and I'm using dreamweaver along with a backend database using phpMyAdmin.
Now, what i need to do is, when I click the button, it will reduce the stock column value in the "products" table by 1.
However there are different products in the table. Shown below:
http://i.stack.imgur.com/vLZXQ.png
So lets say, A user is on the game page for "Destiny" and clicks on the Buy now button, how can i make it reduce the stock level by one, but only for the Destiny record and not for the Fifa 15 column. So Destiny stock becomes 49, but Fifa stays 50. Will i just need to make each button have a different script or?
Currently, I made a button in the page, which links to an action script, but im not sure what sort of code i will be using.
Thank you
xNeyte is giving you some good advice, but it comes across to me that you - Xrin - are completely new to programming database contents with PHP or similar?
So some step by steps:
MYSQL databases should be connected with one of two types of connection - PDO and MySQLi_ . MySQL databases will also always work using the native MySQL but as xNeyte already mentioned - this is deprecated and highly discouraged .
So what you have is you pass your information to the PHP page, so your list of games is on index.php and your working page that will update the number of games ordered would be update.php, in this example.
The Index.php file passes via anchor link and $_GET values (although I highly recommend using a php FORM and $_POST as a better alternative), to the update.php page, which needs to do the following things (in roughly this order) to work:
Update.php
Load a valid database login connection so that the page can communicate with the database
Take the values passed from the original page and check that they are valid.
establish a connection with the database and adjust the values as required.
establish the update above worked and then give the user some feedback
So, step by step we'll go through these parts:
I am going to be a pain and use MySQLi rather than PDO - xNeyte used PDO syntax in his answer to you and that is fully correct and various better than MySQLi, for the sake of clarity and your knowledge of MySQL native, it may be easier to see/understand what's going on with MySQLi.
Part 1:
Connection to the database.
This should be done with Object Orientated - Classes,
class database {
private $dbUser = "";
private $dbPass = ""; //populate these with your values
private $dbName = "";
public $dbLink;
public function __construct() {
$this->dbLink = new mysqli("localhost", $this->dbUser, $this->dbPass, $this->dbName);
}
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
if ( ! $this->dbLink )
{
die("Connection Error (" . mysqli_connect_errno() . ") "
. mysqli_connect_error());
mysqli_close($this->dbLink);
}
else
{
$this->dbLink->set_charset("UTF-8");
}
return true;
} //end __construct
} //end class
The whole of the above code block should be in the database.php referenced by xNeyte - this is the class that you call to interact with the database.
So using the above code in the database.php object, you need to call the database object at the top of your code, and then you need to generate an instance of your class:
include "database.php"; ////include file
$dataBase = new database(); ///create new instance of class.
Now When you write $dataBase->dbLink this is a connection to the database. If you do not know your database connection use the details PHPMyAdmin uses, it carries out its tasks in exactly the same way.
Sooo
Part 2:
That is that your database connection is established - now you need to run the update: First off you need to check that the value given is valid:
if (is_numeric($_GET['id']) && $_GET['id'] >0 ){
$id = (int)$_GET['id'];
}
This is simple code to check the value passed from the link is a integer number. Never trust user input.
It is also a good idea never to directly plug in GET and POST values into your SQL statements. Hence I've copied the value across to $id
Part 3:
$sql = "UPDATE <TABLE> SET STOCK = STOCK-1 WHERE Product_ID = ? LIMIT 1";
The table name is your table name, the LIMIT 1 simply ensures this only works on one row, so it will not effect too many stocked games.
That above is the SQL but how to make that work in PHP:
first off, the statement needs to be prepared, then once prepared, the value(s) are plugged into the ? parts (this is MySQLi syntax, PDO has the more useful :name syntax).
So:
include "database.php"; ////include file
$dataBase = new database(); ///create new instance of class.
if (is_numeric($_GET['id']) && $_GET['id'] >0 ){
$id = (int)$_GET['id'];
$sql = "UPDATE <TABLE> SET STOCK = STOCK-1 WHERE Product_id = ? LIMIT 1";
$update = $dataBase->dbLink->prepare($sql);
$update->bind_param("i",$id);
$update->execute();
$counter = $update->affected_rows;
$update->close();
//////gap for later work, see below:
}
else
{
print "Sorry nothing to update";
}
There's probably quite a lot going on here, first off the bind_param method sets the values to plug into the SQL query, replacing the ? with the value of $id. The i indicates it is meant to be an Integer value. Please see http://php.net/manual/en/mysqli-stmt.bind-param.php
The $counter value simply gets a return of the number of affected rows and then something like this can be inserted:
if ($counter > 0 ){
print "Thank you for your order. Stock has been reduced accordingly.";
}
else {
print "Sorry we could not stock your order.";
}
Part 4
And finally if you wish you can then just output the print messages or I tend to put the messages into a SESSION, and then redirect the PHP page back.
I hope this has helped a bit. I would highly recommend if you're not used to the database interactions in this way then either use PDO or MySQLi but do not combine the two, that will cause all sorts of syntax faults. Using MySQLi means that everything you know MySQL can do, is done better with the addition of the letter "i" in the function call. It is also very good for referencing the PHP.net Manual which has an excellent clear detailed examples of how to use each PHP function.
The best is to set a link on each button with the ID of your game (1 for destiny, 2 for Fifa15).
Then your script which the user will launch by clicking will be :
<?php
include('database.php'); // your database connection
if($_GET['id']) {
$id=$_GET['id'];
} else throw new Exception('Invalid parameter');
$statement = myPDO::getInstance->prepare(<<<SQL
UPDATE TABLE
SET STOCK = STOCK-1
WHERE Product_id = :id
SQL
);
$statement->execute(array(":id" => $id));
This script will do the job
I am using the external authentication system. Therefore, there are a lot of user data, which is not available in Phorum.
I am using the last post module, although I want to get the information from the last post user, from my own user table (I have some data, like avatar, birth info etc). I want to show in my Phorum. How can I achieve this?
I've tried to simply connect via a: mysql_query(); but then I just get No database selected error.
I've searched for hours - I cannot find any documentation regarding getting custom data from your own user table.
I would recommend using mysqli, as mysql is deprecated. First make sure that your connection is correct. No database selected means you probably do not have your connection included at the top.
$con = mysqli_connect("localhost","username","password","database");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error());
}
Make sure that your sql statement looks like so (Notice the $con in the mysqli_query()):
$sql = "select * from TableName";
if ($que = mysqli_query($con, $sql)) {
// Query has ran
}
I know this is probably something simple, but I have searched for hours the past few days and I'm ready to jump out of my one-story building.
Have a basic site for testing, literally nothing on it but opening/closing html tags.
A very basic table in a data base, using phpmyadmin to access it.
Trying to get table contents to display on the basic website.
Was using mysqli_ or mysql_ style in the php to access the data for a while with no luck.. Have since been reading about PDO and found numerous tutorials on how to use it. I feel like what I'm trying to do should be so simple but I've tried copying what I've found on this site and other tutorials to the T and the site still does not display the data.
try {
$conn = new PDO("mysql:host=$hostname; dbname=$userdb", $username, $password);
$conn->exec("SET CHARACTER SET utf8");
$sql = "SELECT * FROM Monday";
$result = $conn->query($sql);
while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {
echo $row['Name'] . '<br />';
}
$conn = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
Basically the website will display everything after the first -> in this case after the $conn-> but none of the actual table data.
I've tried about 50 different ways at least from numerous sites and I'm just lost now I guess..
Side note: I do have php forms on the same site that when submitted successfully insert data into the table, so I know I am able to connect to the db and table and INSERT, its just the issue of SELECT I can't get.
Thanks for any help
EDITED: to add fetchAll
You are using the method fetch() in your loop, which only fetches the next single row of your results. Replace it with fetchAll() and it should work.
More information about the fetchAll() method:
http://php.net/manual/en/pdostatement.fetchall.php
And for testing purposes you could set the PDO error mode to PDO::ERRMODE_EXCEPTION. See: http://php.net/manual/en/pdo.error-handling.php
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
Should be;
while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {