Mysql Values not Working - mysql

I have a rank to determine the user level, (e.g. rank 1 = registered, rank3 = admin), and everything works fine in my script below.
<?php
session_start();
require('../../config.php');
$qry=("SELECT `rank`, `uname` FROM users");
$result=mysql_query($qry);
$row = mysql_fetch_assoc($result);
$rank = $row['rank'];
$user = $_SESSION['user'];
$logged = $_SESSION['loggedin'];
if ($logged == true) {
if ($rank >= 3) {
echo "Succesful, $user.<br />
<form method='POST' action='delete.php'>
<select><option>Please select</option>";
while ($row = mysql_fetch_assoc($result)) {
$users = $row['uname'];
$lol = ucwords($users);
}
echo "<option>$lol</option>";
echo "</select>
</form>";
} else {
echo "Your not an admin.";
}
} else {
echo "Please login.";
}
?>
But, once I add a new user to the database, (2 rows in database), it says "Your not an admin".
Please help. Thank you.

Shouldn't add the where condition to specify which user? Like use the userid?
$qry=("SELECT `rank`, `uname` FROM users WHERE uid = $uid");

Related

WordPress and PHP | Check if row exists in database if yes don't insert data

I'm fairly new to WordPress and SQL. I have a contact form that I want to have the data be submitted to my WordPress database but only if the data that has been entered has not been entered before.
This is what i have so far, which sends data to my database when form is submitted.
if(isset($_POST['contact_us'])) {
$invalidContact = "<h5 class='invalidBooking'> Nope try again</h5>";
$successContact = "<h5 class='invalidBooking'> Message Sent!</h5>";
$table_name='contact_table';
global $wpdb;
$contact_name = esc_attr($_POST['contact_name']);
$contact_email = sanitize_email($_POST['contact_email']);
$subject = esc_attr($_POST['subject']);
$message = esc_attr($_POST['message']);
$error= array();
if (empty($contact_name)) {
$error['name_invalid']= "Name required";
}
if (empty($contact_email)){
$error['email_invaild']= "Email required";
}
// Im guessing some code here to check if row exists in database
if (count($error) >= 1) {
echo $invalid;
}
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
echo $successContact;
}
}
You may try this code
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$query = "SELECT * FROM $table_name WHERE 'Contact_Name'= '$contact_name' AND 'Contact_Email' = '$contact_email' AND 'Contact_Subject' = '$subject' AND 'Contact_Message' = '$message'";
$query_results = $wpdb->get_results($query);
if(count($query_results) == 0) {
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
}
}
Hope this works for you.
fetch data using this code
$query = "SELECT * FROM {$wpdb->prefix}table WHERE column = 1";
echo $query;
$results = $wpdb->get_results($query);
and then you know what to do...

Display all usernames in the "users" table

I'm trying to show all usernames in the users table onto my index page.
Here is the PHP code:
$result = $db->prepare("SELECT username FROM users");
$result->execute();
while ($row = $db->fetchAll(PDO::FETCH_ASSOC))
{
$user = $row['users'];
$username = $row['username'];
}
echo $user;
echo $username;
I think you are printing username outside of the while loop, so that you're getting the last username every time.
$result = $db->prepare("SELECT username FROM users");
$result->execute();
while ($row = $db->fetchAll(PDO::FETCH_ASSOC))
{
echo $username = $row['username'];
}

Display ratio as decimal between two PHP variables

I log stats for my Minecraft server and display player's in-game stats on my site. I log kills and deaths already, but now I'm trying to get a functioning kill/death ratio.
I am trying to display the kills/deaths in a decimal ratio format (Example: 3789 kills - 5711 deaths would give you a K/DR of 0.663)
elseif ($_GET['task'] == 'stats') {
$get_player = $_GET['player'];
$get_db = 'engine';
$result = mysql_query("SELECT * FROM $get_db WHERE name = '" . mysql_real_escape_string($get_player) . "'", $link);
while($data = mysql_fetch_array($result)) {
echo '{"task":"viewstats","kills":"'; echo $data['kills'];
echo '","deaths":"'; echo $data['deaths'];
echo '","joins":"'; echo $data['joins'];
echo '","quits":"'; echo $data['quits'];
echo '","kicked":"'; echo $data['kicked'];
echo '"}';
}
}
I call upon them in a table like this:
<td><?php echo empty($stats) ? "--" : substr($stats->kills, 0, 50); ?></td>
<td><?php echo empty($stats) ? "--" : substr($stats->deaths, 0, 50); ?></td>
The above PHP code is an API file and the MySQL is already enabled in it - I only posted a snippet of the API though.
You can do this:
echo json_encode(array(
'task' => 'viewstats',
'kills' => $data['kills'],
'deaths' => $data['deaths'],
'joins'=> $data['joins'],
'quits' => $data['quits'],
'kicked' => $data['kicked'],
// then ratio
'ratio' => $data['kills'] / $data['deaths'],
));
//**Make sure this Function is declared at the top of your script.**
function MySQLi_quickConnect()
{
$host = 'somewebsite.db.120327161.hostedresource.com'; //or 'http://localhost'
$username = '<YOUR USERNAME>';
$password = '<YOUR PASSWORD>';
$database = '<YOUR DATABASES NAME>';
$db = new MySQLi($host,$username,$password,$database);
$error_message = $db->connect_error;
if($error_message != NULL){die("Error:" . $error_message . "<br>" . "Occured in function
MySQLi_quickConnect");}
return $db;
}
//Replace your code with this:
elseif($_GET['task'] == 'stats') {
$get_player = $_GET['player'];
$get_db = 'engine';
$mysqli = MySQLi_quickConnect();
$query = ('SELECT kills, deaths, FROM ? WHERE name = ? ');
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("ss", $get_db, $get_player);
$stmt->execute();
$stmt->bind_result($kills, $deaths);
}
while ($stmt->fetch()) {
$kdr = $kills/$deaths;
echo "You have a K/DR of " . $kdr . "<br>";
}
$stmt->close();
}
Note: Verify your Database connection, table names, and $_Get variables.

Send an email using php with mysql data included

I'm trying to send a list of recent entries into a mysql table via email once a week using cron jobs. Typically to call the list of recent entries I use this:
$result = mysql_query("SELECT * FROM stock WHERE PurchaseDate < '$TODAY' AND PurchaseDate > '$LASTWEEK'")
or die(mysql_error());
while ($list = mysql_fetch_array($result))
But obviously I can't put this code into the $message variable in php mail.
Any ideas?
$result = mysql_query("SELECT * FROM stock WHERE PurchaseDate < '$TODAY' AND PurchaseDate > '$LASTWEEK'") or die(mysql_error());
$entries = 'Entries: ';
while ($list = mysql_fetch_array($result)) {
$entries .= $list[entry] . ', ';
}
mail('someone#test.com', 'Stock', $entries);
This is just an example. Not sure what your table looks like.
The mail functions takes a string, and you are returning an array.
So you need to implode it implode(',', $list); or build a string with the result set.
You should use PHPMailer, Zend Mail or Swift_Mailer libraries that are safer and prevent for example from header injection.
try {
$result = mysql_query("SELECT * FROM your_table WHERE blank = 'blank' AND blank2 ='blank2'");
$num_rows = mysql_num_rows($result);
if($num_rows < 1) {
throw new Exception('There is no user who qualifies...');
}
if(!$result) {
throw new Exception('An Error Occurred..');
}
//mail off whatever you need to each user that qualifies based on your query criteria..
while($row = mysql_fetch_array($result)) {
$firstname = stripslashes($row['firstname']);
$lastname = stripslashes($row['lastname']);
$email = stripslashes($row['email']);
//and any other variables you need for the email...
$subject = 'Some Subject';
$message = 'Hello '.$firstname.' blah..blah...';
mail($email, $subject, $message);
//do something else...
echo 'All users emailed.';
}
}
catch (Exception $e) {
echo $e->getMessage();
}

How to fetch single row/data from Mysql_fetch_array?

I am reading .csv file through PHP using fgetcsv(). Now I am able to fetch I mean read data from .csv file.
Then I need to check SKU column with my fetch result & accordingly have to perform either Insertion Or Updation.
Suppose SKU is already present there, then I have to update my row in table else I need to insert new record.
I have write following code...Plz check n tell me where I am doing mistake-:
<?php
$row = 1;
if (($handle = fopen("localhost/data/htdocs/magento/var/import/Price.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 8000, ",")) !== FALSE)
{
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
for ($c=0; $c < $num; $c++)
{
$temp = $data;
$string = implode(";", $temp);
}
$pieces = explode(";", $string);
$col1 = $pieces[0];
$col2 = $pieces[1];
$col3 = $pieces[2];
$col4 = $pieces[3];
$db_name = "magento";
$con = mysql_connect("localhost", "magento", "password");
If (!$con)
{
die('Could not connect: ' . mysql_error());
mysql_close($con);
}
$seldb = mysql_select_db($db_name, $con);
$query_fetch = "SELECT `sku` from `imoprt_prices`";
$result_fetch = mysql_query($query_fetch);
$num_rows = mysql_num_rows($result_fetch);
for($i = 0; $i < $num_rows; $i++)
{
$value = mysql_result($result_fetch, i, 'sku');
if(strcmp('".$value."', '".$col2."') == 0)
{
$flag = 1;
break;
}
else
{
$flag = 0;
break;
}
}
if($flag == 1)
{
$query_upadte = "(UPDATE imoprt_prices SET customer_id= '".$col1."', sku ='".$col2."', price= '".$col3."', website= '".$col4."'
)";
mysql_query($query_upadte);
$row++;
}
if($flag == 0)
{
mysql_query("INSERT INTO `imoprt_prices`(`customer_id`,`sku`,`price`,`website`) VALUES('".$col1."','".$col2."','".$col3."','".$col4."')");
$row++;
}
}
}
?>
If you have an actual UNIQUE index on your imoprt_prices table, you can use the ON DUPLICATE KEY UPDATE syntax and simplify your code a bit to something similar to; (note, can't test, so see as pseudo code)
$db_name = "magento";
$con = mysql_connect("localhost", "magento", "password") or die(mysql_error());
$seldb = mysql_select_db($db_name, $con);
if (($handle = fopen("localhost/data/htdocs/magento/var/import/Price.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 8000, ",")) !== FALSE)
{
$col1 = $pieces[0];
$col2 = $pieces[1];
$col3 = $pieces[2];
$col4 = $pieces[3];
$query_upadte = "INSERT INTO imoprt_prices (customer_id, sku, price, website) ".
"VALUES('".$col1."','".$col2."','".$col3."','".$col4."') ".
"ON DUPLICATE KEY UPDATE customer_id='".$col1."', price='".$col3.
"',website='".$col4."'";
mysql_query($query_upadte);
}
}
You may also want to either mysql_real_escape_string() or use parameterized queries to make sure there's no ' in your inserted values though. That is always a danger with building sql strings like this.
Simple demo here.
In the following snippet:
$query_upadte = "UPDATE imoprt_prices SET customer_id= '".$col1."', sku ='".$col2."', price= '".$col3."', website= '".$col4."'";
You're trying to update all the rows repeatedly, instead of just updating a single row. This is normally not allowed in MySQL. You need to specify a particular unique ID to be updated.