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
}
Related
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
Hello guys i have problem with inserting data in mysql database.I accepted a project that my friend worked.
I make simple php test file and try to insert in table _content_city. query is successfully executed bu no records in database column when i check in phpmyadmin.
$handler = mysql_connect($server, $user, $pass);
$database = mysql_select_db($dbname);
if(!$handler) :
die("Faild connect to MySQL :" . mysql_error());
endif;
if(!$database) :
die("DB with name ". $dbname . " no exists " . mysql_error());
endif;
mysql_query("INSERT INTO _content_grad (wishlist) VALUES('BlaBlaBla') ") or die(mysql_error());
printf ("Inserterd records: %d\n", mysql_affected_rows());
When i execute this code in browser i have message Inserterd records: 1
But when i check in phpmyadmin that data no exist in column. I dont know whay.
You guys can see image and u will see column wishlist is empty.
http://img710.imageshack.us/img710/1852/5hfw.png
I check foreign_keys and remove all foreign_keys and again dont work.
Like test i make new database with name new_test_base and make table albums and column title and like test i execute my php code and all data is successfully inserted when i check in phpmyadmin. So problem is only in that database, i have full access and privilegies i use root (ALL)
Any solution to fix this. Thanks
The MySQL_* range of functions have been depreciated and are no longer reccomened for use. Use the MySQLi_* range of functions instead.
In your code, put the following line echo mysql_errno($handler) and it should display the latest error retuned by MySQL, a MySQLi version of this function is also available.
I have researched my question but there just isn't much help out there for MySQLI functions. I'm also new here so, please bear with me.
I have a test database named "website" and it contains a table called "users" which has data for all of the members of my website. In a separate file I have the php code that connects to my localhost and selects the database "website." I'm using the newest functions of MySQL so instead of the connection string containing mysql_connect it contains mysqli_connect. The registration process works great and I can find no error in any of the other code that uses the mysqli functions.
My include file (connect.php)
<?php
$link = mysqli_connect("localhost", "useracc", "useracc1", "website");
?>
I set up a test script for the login section.
<?php
include('connect.php');
$user = $_POST['user'];
$query = "SELECT birthday FROM users";
$result = mysqli_query($link, $query) or die ("RESULT ERROR");
echo "$user";
echo "$result";
?>
There is a password box on the previous page but for the test script I left that out and so far, only the $user is shown on the page. I get no error even when I replace "RESULT ERROR" with mysqli_error($link). I've tried interchanging ' for " in every part of the code that uses quotes but that didn't work. I've tried rewording the $query line but that also had no effect. I'm really new to MySQL and php so if you guys could tell me where I'm going wrong I'd really appreciate it.
Thanks for reading my question. Have a great day.
Add the following lines to the connect.php after you connect line
if (mysqli_connect_errno()) {
printf("Can't connect Errorcode: %s\n", mysqli_connect_error());
exit;
}
this will ensure the connection is made without any errors and return them if there are ...
I'm using HostMonster as my web host and I'm trying connect to a database I created using MySQL inside of HostMonster. In order to call that database in my website do I need to use PHP? Or is there a way to create a javascript OnClick function that can call the database. I'm not using ASP.Net so it's not quite as simple as I would like it. Just curious if the best solution is PHP, if so I guess I should go learn it.
what are you planning to do with the database, other than just 'calling it'? You will need some language like PHP to connect to the DB to retrieve, insert, update or delete data in the DB.
here is a code for connection MySQL from PHP using MYSQLI extension
<?php
$dba_host='localhost';
$dba_name='root';
$dba_pass='';
$dba_db='sn';
$con=mysqli_connect($dba_host,$dba_name,$dba_pass,$dba_db) or die('Connection Refused !');
$stmt=mysqli_prepare($con,"SELECT UID FROM Main");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $value);
while(mysqli_stmt_fetch($stmt))
$result[] = $value;
mysqli_stmt_close($stmt);
mysqli_close($con);
?>
Your javascript onClick function is running on the client side (in the browser) and the database is running on the server-side. You will need a server-side language to get the information from the database and send it to the browser.
You do not HAVE to use PHP to connect to a MYSQL database. Also, you can't connect to your database using only client-side javascript (ie. an onClick() function). You need to use a server side language, PHP is one choice.
To connect to a MYSQL database on hostmonster using PHP you will need to know your credentials that use to log into phpMyAdmin from your cpanel. Once you have made the connection you can then select the MYSQL database that you created. Once the database is selected you can query it using the "mysql_query" function in PHP. The following code does all of that and stores the results of the MYSQL query in a PHP variable called $result.
<?php
$con = mysql_connect("www.yourdomain.com","phpMyAdmin_username","phpMyAdmin_password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql_database_name", $con);
$query = "SELECT * FROM TableName"
$result = mysql_query($query);
?>
Now you've got the results of the query inside the PHP variable $result and you can use it anyway you like.
If you put this in your 'public_html' folder and named it 'index.php' or 'index.html' this would automatically be run when someone went to www.yourdomain.com.
You can find a great tutorial series on PHP here http://thenewboston.org/list.php?cat=11.
I have been learning how to program websites lately and the time has come for me to add a database. I have in fact already successfully created a MySQL database and interacted with it with PHP.
My problem is I can't seem to access a SQLite database file with it. I am using MAMP to host locally for now. Here is a snippet of the code I am using to access the db and find and print out a value stored on it.
<?php
$dbhandle = sqlite_open('/Applications/MAMP/db/sqlite/Users');
if ($dbhandle == false) die ('Unable to open database');
$dbquery = "SELECT * FROM usernames WHERE username=trevor";
$dbresult = sqlite_query($dbhandle, $dbquery);
echo sqlite_fetch_single($dbresult);
sqlite_close($dbhandle);
?>
As you have access to the database (your code doesn't die), I'd say there's got to be an error later ;-)
Looking at your SQL query, I see this :
SELECT * FROM usernames WHERE username=trevor
Are you sure you don't need to put quotes arround that string ?
Like this :
SELECT * FROM usernames WHERE username='trevor'
Also, notice that sqlite_fetch_single will only fetch the first row of your data -- which means you might need to use sqlite_fetch_array or sqlite_fetch_object if you want to access all the fields of your resulset.