I'm trying to make a football betting system based on the WordPress CMS. I apologize if this is a redundant question, but I've been searching through Google and a few Wiki's all day, and I haven't been able to find any clue to how this question is answered.
BACKGROUND INFORMATION:
I use:
MySQL
PHP
Navicat
Every time the user inputs two integers, corresponding to the goalscorings in a football match, on the php-scripted website, the two integers get sent off to the database table "bets", through an insert.php-file.
The insert.php looks like this:
<?php $con = mysql_connect("host","username","password"); if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("database", $con);
$sql="INSERT INTO bets (homebet, awaybet) VALUES ('$_POST[homebet]','$_POST[awaybet]')";
if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "Thanks for betting!";
mysql_close($con); ?>
The php-form looks like this:
I have the following self-made tables: bets, teams, matches, and I have the WordPress table, wp-users, where each member is listed.
The bets table looks like this:
As you can see, the userid is empty - which it shouldn't be. It should contain the ID of the user, who entered the bet.
My two-part question is then..
How should I obtain the ID of the user and display it in the database table, bets? Perhaps WordPress have a code-snippet for it.
And finally, how should I attach a gameid to each match? Should I create a new form for each new match?
Thanks SO much in advance - I hope I was able to make this thread readable and easy to understand.
Frederick Andersen
You're missing quite some things here. I can't advise you how to manage the different games since I don't know what the rest of your application looks like.
Here are some pointers to get you going:
Don't create your own DB connection
Remove:
$con = mysql_connect("host","username","password"); if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("database", $con);
Add instead:
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');
WordPress current user ID
Add this to top off script:
global $wpdb, $current_user;
get_currentuserinfo();
Change $sql code to this:
$sql= $wpdb->prepare("INSERT INTO `bets` (`userid`, `homebet`, `awaybet`) VALUES (%d, %d, %d)", $current_user->ID, $_POST['homebet'], $_POST['awaybet']);
I've also used the wpdb prepare function so your post data will be escaped before getting queried.
Also change this to use WP native querying.
Remove:
if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "Thanks for betting!";
mysql_close($con);
Add instead:
$wpdb->query($sql)
Related
Thank you first of all for coming to try and help me solve an issue I am having with my current attempt to build a customer user system.
First of all, a brief explanation on the system I am trying to build might shed some light on the meaning behind my approach.
I am trying to build a system where the user can log into the website via the WordPress Login & Registration System, but then, based on their WordPress ID, they'll be given information related to that ID from another MySQL Table.
The reason for this is, we want to store specific data to users on another table, such as Weight, Height, Sex, and more.
The reason this needs to be in another table, is that an API from another service will directly put the data (and keep it up to date) in a specific table we will create.
The Code:
$servername = 'server';
$username = 'username';
$password = 'password';
$conn = mysql_connect($servername, $username, $password);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT pacientes.Id, wp_users.ID, pacientes.nombre
FROM pacientes
RIGHT JOIN wp_users
ON pacientes.Id = wp_users.ID';
mysql_select_db('database');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "Fetched data successfully";
mysql_close($conn);
Up until this point, everything seems to work as intended. I am given the all clear by all the die commands, and so I don't suspect there is any issue with finding, or locating the database, and tables I've mentioned.
The Code (Part 2)
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "WordPress ID: {$row['ID']} <br> ".
"Patient Id: {$row['ID']} <br> ".
"Patient First Name: : {$row['nombre']} <br> ".
"Patient Second Name : {$row['apellidos']} <br> ";
}
Now, this is echoing the data correctly. As you can see the Patient ID & WordPress ID are correctly associated with each other. The 4th user in the Patient Table is indeed Manuel.
You can see a quick screenshot here: https://gyazo.com/300af05da9afc8bcffa8f7efac628691
So my issue is with making this system only pull the data from the Patient Table, that is related to the ID of the current user, as chosen by the WordPress User ID.
I've looked at various sources that I will also link below, but none have so far produced what I am attempting to create.
Again; The intention here is that the user can log in using WordPress, and based off their WordPress ID co-inciding with an ID in the Patient Table, they should be shown their own specific data from the Patient Table, based on their ID's matching in both tables.
Current Research:
Integrating wordpress authentication with an existing user database
getting specific data from wordpress database table
Get the data of specific user in PHP
I greatly appreciate any help, advice or guides you can provide me with. Thank you.
So, after a little more work I found the solution
Code (Database Connection & SQL Queries)
$servername = 'YourServer';
$username = 'YourUsername';
$password = 'YourPassword';
$conn = mysql_connect($servername, $username, $password);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
// Get the current User ID of the person logged into WordPress.
$currentUser = get_current_user_id();
$sql = 'SELECT wp_users.ID, sharedID, pacientes.nombre, pacientes.peso
FROM pacientes
RIGHT JOIN wp_users
ON pacientes.Id = wp_users.ID';
mysql_select_db('Sql918293_2');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "Fetched data successfully";
mysql_close($conn);
Those code pulls all the relevant data from the databases, and joins them together so that you can use both tables, as long as they have a common ID. In this instance, the ID of the WordPress user needs to match the ID in the patient table.
Code (Echo the Data only to the relevant user)
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
if ($row['Id'] == $currentUser)
{
echo
"WordPress ID: {$row['ID']} <br> ".
"Patient Id: {$row['Id']} <br> ".
"Patient First Name: : {$row['nombre']} <br> ".
"Patient Second Name : {$row['apellidos']} <br> ".
"----------------------------------------<br>";
}
}
The fix was actually really easy, and I have no idea why it pop into my head before. All I had to do was apply the $currentUser = get_current_user_ID(); to grab the ID from WordPress, and put it into a variable.
Then I did a simple If Statement to check against, and only to echo the information if the variable was correct.
if ($row['Id'] == $currentUser)
This basically checks against the ID (Patient ID) as seen above, and if it equals the same as the current user (As you're already logged into WordPress), then print the information.
I hope this helps everyone!
My name is Anna and I'm building a website with a festival calendar! People can add festivals when they're logged in. But now is my question, how can I display what people put in my database. I found the following code on this website, but when I put it in my script, I get the error that there's no database selected. But I do have a database selected (Festivals) ?
$sql = "SELECT festival_name, festival_organisator, festival_begin FROM Festivals WHERE festival_id=3";
$result = mysql_query($sql) or die(mysql_error());
$festival_name = $festival_organisator = $festival_begin = array();
while($row = mysql_fetch_assoc($result)) {
$festival_name[] = $row['festival_name'];
$festival_organisator[] = $row['festival_organisator'];
$festival_begin[] = $row['festival_begin'];
}
I hope anybody can help me! Thanks in advance
You have not yet connected to the database itself
Query selecting from the table Festivals does not mean that you've selected the Festivals database, those are two very different things.
The database Festivals contains all the tables (table Festivals, table x, etc).
The table Festivals contains data which you can query (festival_name, festival_organisator, etc).
Now you must connect
Taking a look at the documentation is always a good choice, let's see how you can connect to and select a database:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>
You should be connected to the database, having access to the selected database through $link.
mysql_query($sql, $link)
But don't do it!
Unless you must, but cute puppies will die :(
You shouldn't be using mysql_* in the first place though since it's no longer supported. Instead you should be using PDO or mysqli to achieve your task. It may sound or appear trickier at first but it's actually rather simple:
Related answer on how to query with PDO.
The PDO documentation provide nice examples on how to query.
The mysqli_* documentation provide nice examples on how to query.
I recently began learning PHP, and I set up a MySQL Server. However, I'm not very familiar with SQL, and I would like to know, how would I get the top amount of results (amount as defined by _GET["Amount"] that all have the same EventType as defined by _GET["EventType"]?
<?php
$con=mysqli_connect(Info removed);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Amount=$_GET["Amount"];
$GetType=$_GET["Type"];
$sql= ""; //How would I do the action outlined above?
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Done";
mysqli_close($con);
?>
I've looked over this site and others, to no avail. All help is greatly appreciated.
Sorry misunderstood your question...
Try this instead: $sql = "SELECT * FROM table WHERE EventType='$GetType' ORDER BY amount_column DESC";
Run the query: $sql_run = mysql_query($sql);
The amount column in your table do have to be INT i think.
To echo out all the amounts you could then say something like:
while($sql_row = mysql_fetch_assoc($sql_run)){
echo $sql_row['amount_column'].'<br>';
}
btw in your code you don't use the mysql_select_db() method, there might be a way around it, but as far as I know you do have to specify a database.
Before writing query you need to prepare the mysql table. If you have one, try to post here your table structure.
I need to retrieve the auto increment field from my database table. I tried the following but $id is always just empty.
The insert works too.
My table is as follows:
idint(9) NOT NULL auto_increment,
and id is set as primary
What am I doing wrong?
$conn = mysql_connect($host,$username,$password);
mysql_select_db($database, $conn) or die( "Unable to select database");
include "update_activity.php";
updateActivity("logged in", "On Break");
$date = date("m/d/y"); $starttime = time();
$sesh = $_SESSION['fname']." ".$_SESSION['lname'];
$q = "INSERT INTO `breaks` (date, starttime, user) VALUES ('".$date."', '".$starttime."', '".$sesh."')";
$query = mysql_query($q, $conn);
$id = mysql_insert_id($conn);
echo var_dump($id); exit;
edited to show my more recent attempts
Have read all comments given and your replies to each.
Only one of these is possible:
Either the query works properly OR
You are not getting the generated primary key.
Both of these can never be true.
Define, how you know query is working? Do you know the max PK before and after the running query? Is the insert happening from some other place or thread or even other user? the query is working properly from code or from your mysql client?
To diagnose the problem, we have to go though the normal way.
Dump your generated query before calling mysql_query.
Wrap a error checking system around your query call so php can tell you if the query worked or not. I am sure just by these two steps you will realize the root cause of the problem.
error_reporting(E_ALL);
ini_set('display_errors','on');
echo "before calling: $q\n";
$query = mysql_query($q, $conn);
if(!$query)
{
echo "Error:" . mysql_error($conn);
return;
}
echo " generated id:" . mysql_insert_id($conn);
#adelphia as far as i get the idea there is a problem in the query that is executed.
plz check the query properly
Borrow a lead from this code extracted from here:
http://php.net/manual/en/function.mysql-insert-id.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
The problem with your insert query
$q = "INSERT INTO `breaks` (date, starttime, user)
VALUES ('".$date."',
'".$starttime."',
'".$_SESSION['fname'] $_SESSION['lname']."')";
try with this
and main thing you are using most of the deprecated "mysql" things like "mysql_insert_id()"
store the values that u want to pass into an array or variable and pass it in the insert query.
its should work fine then...
<?php
$link = mysql_connect('localhost', 'sc2broad_testing', '1BananA2');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_query("INSERT INTO Persons (re) VALUES ('Peter')");
mysql_close($link);
?>
This code isnt taking the value 'peter' and inserting it into persons row 're'?? should i attempt to tell it which database somewhere? thanks . it is saying it connects successfully even if i am not telling it which database to connect to? only the server and user? i am confused.
I think you may need to specify the database that you are querying to?
mysql_select_db('db_name', $link)
If not try changing the mysql_query to:
print("INSERT INTO Persons (re) VALUES ('Peter')");
You can then check the query is correct and test it works outside of the php.