PHP and MySQL not allowing Queries - php

I'm working on some code for a friend but my PHP code refuses to query the database even when I simplify it down to running without variables.
$sql = "SELECT message1, message2 FROM cards WHERE number = 5150671";
if ($conn->query($sql) === TRUE) {
Echo "Connection to the Database Success, Card Information Recieved.";
$Message1 = $_row["message1"];
$Message2 = $_row["message2"];
...etc
Full Code:
https://pastebin.com/jGs2xBFD
It returns a Query Failed error every time, the database, table, and rows are all named correctly and the values are in there.
cards #door_sign (localhost_3306) - Table
number message1 message2
5150671 1 2
any input would be greatly appreciated.

Missing something?
$result= $conn->query($sql);
while($row = $result->fetch_assoc()) {
//stuff for the thing
}

Related

When i inserting data into mysql it insert two datas, and i dont know why

When i inserting using this code it insert two datas and i downt know how to fix it
$sql = "SELECT Version_id FROM versions ORDER BY Version_id DESC LIMIT 1;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$lastVersion =$row["Version_id"];
}
}
echo($lastVersion);
$lastVersion++;
$sql = "INSERT INTO versions (version)
VALUES ('v$lastVersion')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
While I don't exactly understand what you mean with "two datas", I do see multiple issues with your code.
First of all it is horribly inefficient and prone to race conditions. It's also quite wrong, in that it doesn't do what you want it. Not to mention should be replaced with native database functionality.
Most of these can be fixed by simply changing the version_id field to a AUTO_INCREMENT. This will automatically give the new record the next available ID in the set, exactly as what you're trying to do. Then you can retrieve this ID by using "lastInsertId()"
That'll make all of the code in your post superflous, and only require you do do something like this when actually inserting data:
$sql = "INSERT INTO `version`(`setting`, `date`) VALUES (:setting, :date)";
$stmt = $db->prepare ($sql);
$res = $stmt->execute ($data);
$newID = $db->lastInsertId ();
After this the new version ID is stored in the $newID variable.
Of course, if you want to UPDATE the version ID for some reason, then INSERT is the wrong command to use. Also, why use an entire table for what's basically a simple version number? In short, your whole table doesn't make a whole lot of sense for me.
I recommend explaining the rationale behind it, so that we can possibly come up with some better solutions you can use.

Call a PHP function inside of a while loop

I have a function which gets a particular set of users from a table where a particular WHERE condition is meet.
I need to send each of them a message.
So, I used another function to send the message. And called that function inside he following while loop
while($user= mysqli_fetch_assoc($users_set)){
send_message($user['email']);
}
So, the problem is, the function is called only just one time. (Only with the last value of the loop)
How to fix this problem and make the function called with each value of the loop...
This is the full code...
$query = "SELECT * ";
$query .= "FROM user ";
$query .= "WHERE confirmed = 0";
$user_set = mysqli_query($db_conx, $query);
confirm_query($user_set);
while($user = mysqli_fetch_assoc($user_set)){
send_message($user['email']);
}
Here is the send message function....
function send_message($email){
global $db_conx;
$invitee_user = get_user_by_email($email);
$query5 = "INSERT INTO notification(";
$query5 .= "description, user_id";
$query5 .= ") VALUES(";
$query5 .= "'You have been confirmed'";
$query5 .= ", {$invitee_user['id']}";
$query5 .= ")";
$result5 = mysqli_query($db_conx, $query5);
if($result5){
//$_SESSION["message"] = "Notification sent". \mysqli_error($db_conx);
return "OK";
}else{
//$_SESSION["message"] = "Failed to send notification". mysqli_error($db_conx);
}
}
Here is the code for confirm_query()
function confirm_query($result_set){
if(!$result_set){
die("Fatal Error Occured : Database Query Failed Report this error");
}
}
I would just boil this down to one query and get rid of all the looping stuff
INSERT INTO notification (description, user_id)
SELECT 'You have been confirmed', user_id
FROM user
WHERE confirmed = 0
Your current logic is really convoluted.
You query the user table to get the user email field, then pass that email as parameter to your function only to then turn around and (I presume) look up the user ID based on email (when you already had this information from your initial query), then you make insert.
This means that for every record you return from first query, you need to do 2 queries to insert to the notification table. So if you had 100 results you would end up doing a total of at least 201 queries to complete the insertions.
Using my approach you make 1 query regardless of how many rows are affected.
One takeaway that you should get from this is that, anytime you see yourself trying to do some sort of nested querying, you should recognize this as an anti-pattern (a coding pattern that you do not want to typically use). There is usually a better approach that can be taken if you rethink how you are writing your queries.

Check if an user is in a database

I have developed a game with Javascript and when the user finishes it, I must save his record in a database. Here you see the code:
$temp = $_POST['playername']; //username
$text = file_get_contents('names.txt'); //list with all usernames
//this text file contains the names of the players that sent a record.
$con=mysqli_connect("localhost","username","pass","my_mk7vrlist");
if (stripos(strtolower($text), strtolower($temp)) !== false) {
//if the username is in the list, don't create a new record but edit the correct one
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
} else {
//The username is not in the list, so this is a new user --> add him in the database
mysqli_query($con, "INSERT INTO `mk7game` (`playername`,`record`,`country`,`timen`) VALUES ('".$_POST['playername']."', '".$_POST['dadate']."', '".$_POST['country']."', '".$_POST['time_e']."')");
file_put_contents("names.txt",$text."\n".$temp);
//update the list with this new name
}
//Close connection
mysqli_close($con);
When I have a new user (the part inside my "else") the code works correctly because I have a new row in my database.
When the username already exists in the list, it means that this player has already sent his record and so I must update the table. By the way I cannot edit the record on the player that has alredy sent the record.
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
It looks like this is wrong, and I can't get why. I am pretty new with PHP and MySQL.
Do you have any suggestion?
You're missing quotes around $temp in the UPDATE statement:
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game`
SET `record` = '".$_POST['dadate']."'
WHERE `mk7game`.`playername` = '".$temp."'
^ ^
LIMIT 1 ") or die(mysqli_error($con));
However, it would be better to make use of prepared statements with parameters, rather than inserting strings into the query.
Escape your user input!
$temp = mysqli_real_escape_string($con, $_POST['playername']);
Make sure to stick your mysqli_connect() above that
$select = mysqli_query($con, "SELECT `id` FROM `mk7game` WHERE `playername` = '".$temp."'");
if(mysqli_num_rows($select))
exit("A player with that name already exists");
Whack that in before the UPDATE query, and you should be good to go - obviously, you'll need to edit it to match your table setup

Creating an "update" page MYSQL/PHP

I'm currently trying to make a page via php which allows the user to update data in my database. I'm experiencing two problems: first when I run my code I get the "Error: Query was empty", however updates were made to the database and this leads me to my second problem. Fields that were left empty (a user doesn't have to enter data into all the fields if they only have one or two things to update) become blank after the updates are made. This is because my current script updates all elements, but is there any way I can have it where if the user leaves an input field blank, nothing gets changed when the database is updated?
Here is my code:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$color = $_POST['color'];
$number = $_POST['number'];
// need id to be filled and need at least one other content type for changes to be made
if (empty($id) || empty($lastname) and empty($firstname) and empty($major) and empty($gpa)) {
echo "<font color='red'>Invalid Submission. Make sure you have an ID and at least one other field filled. </font><br/>";
} else {
// if all the fields are filled (not empty)
// insert data to database
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
// display success message
echo "<font color='blue'>Data updated successfully.</font>";
// Close connection to the database
mysql_close($con);
}
}
To answer your question, you need to catch the query's result and check for errors on that.
$query = mysql_query(/*query*/);
if (!$query)
//error handling
Be sure to read up on SQL injections, as per my comment.
To better help you understand the behavior you were seeing, I will explain to you what was wrong with your code:
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
That first part was executing a MySQL query, regardless of that fact that you did not assign it's return value to a variable.
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
The second part was attempting to run a query by passing the first parameter $sql which has not been set, and the second parameter $con which also appears to not have been set. The first query you ran executed just fine while the second one could never execute. Your solution:
$result = mysql_query(
"UPDATE students
SET lastname = '$lastname', firstname = '$firstname',
favoritecolor = '$color', favoritenumber = '$number'
WHERE id = '$id'"
);
if (!$result) {
throw new Exception('Error: ' . mysql_error());
// or die() is fine too if that's what you really prefer
}
if (!mysql_query($sql,$con)) Here $sql and $con are not defined. Should you be running mysql_query twice?
Few guesses:
There is no mysql connect function I assume it's called elsewhere
Print out your query string. I've always found explicitly denoting what is a string and what is a variable by 'SELECT * FROM '.%tblvar.';'; to be much more debug friendly.

Passing variables from php to mysql query and displaying

Can anyone tell me how to pass the php values $value_aid and $value_tradeid to my sql query res3 please ?
<?php
//error_reporting(E_ALL);
///////////////////////Connect to the database and close the connection when finished///////////////////////////////
include ("dbconnect.php");
///////////////////////////////// Gather and Display area_id //////////////////////////////
$res=mysql_query("SELECT area_id FROM pc_test WHERE postcodes = '".$_POST['postcode']."'");
while ($row = mysql_fetch_array($res))
{
// This works !!
//echo("$row[area_id]");
$value_aid="$row[area_id]";
echo("$value_aid");
}
////////////////// Gather and Display postcodes relating to area_id ////////////////////////
$res3=mysql_query("SELECT trade_id FROM trade WHERE trade_type = '".$_POST['trade_type']."'");
while ($row3 = mysql_fetch_array($res3))
{
// And this works !!
echo("\n$row3[trade_id]");
$value_tradeid="$row3[trade_id]";
}
/**************************************** Gather the query information ********************************************/
//************!!!!!!!!!!!!!!!! This part does not work as the variable values are not being passed !!!!!!!!!!!**********//
$res2=mysql_query("SELECT first_name, last_name, phone_mobile, postcode, trade_type FROM customer WHERE area_id = '$value_aid' && trade_id = '$value_tradeid'");
/**************************************** DISPLAY QUERY RESULTS HERE *********************************************/
while ($row2 = mysql_fetch_array($res2))
{
echo("<TABLE align='center' border = '1' bgcolor = 'A7E3F6'><TH><strong>SEARCH RESULTS<strong></TH>");
echo("<TR><TD><strong>Name :<strong>\n$row2[first_name]\n$row2[last_name]</TD></TR>");
echo("<TR><TD><strong>Phone :<strong>\n$row2[phone_mobile]</TD></TR>");
echo("<TR><TD><strong>Postcode :<strong>\n$row2[postcode]</TD></TR>");
echo("<TR><TD><strong>Trade Type :<strong>\n$row2[trade_type]</TD></TR></TABLE>");
}
/*********************** If no matching records in my table...DISPLAY MESSAGE HERE ******************************/
if (mysql_num_rows($res2) == 0) {
echo ("<strong><br><br>No one is advertising for this area just yet, sorry.<br>We will have tradesmen advertising here very soon.</strong>");
}
//include ("db_close.php");
?>
first of all, dont pass variables you get from the user (_POST, _GET, ...) directly into Database queries without escaping them (e.g. mysql_real_escape_string($_POST['name']) this leads to massive security problems (SQL Injection)
to assign a variable with the value of a nother variable you simply use:
$value_tradeid = $row['trade_id'];
Variables doesnt need to be capsuled as strings, but array keys should !
On the queries which dont work, why you dont escape the strings, like you have done in the others obove.
$res2=mysql_query("SELECT first_name, last_name, phone_mobile, postcode, trade_type FROM customer WHERE area_id = '".$value_aid."' && trade_id = '".$value_tradeid."'");
you should also read about PDO and Prepared Statements.

Categories