My MySQL database is not updating? - php

I'm trying to update my datebase from a php archive but i can't:
Before you ask: The names from db are written correctly and the if works too...
<?php
if(isset($_GET["ans"]) && isset($_GET["name"]))
{
include("con.php");
$con = con();
$answer = $_GET["ans"];
$nam = $_GET["name"];
if($answer="firefly" ||$answer="Firefly" ||$answer="FIREFLY")
{
$le=2;
$sc=50;
$update = "UPDATE User SET Level='$le', Score='$sc' where Name = '$nam'";
mysql_query($update,$con);
// header("Location: lv1b.php?n=$nam");
}
else {
echo "try again..." ;
}
}
?>*
This is the con.php...
<?php
function con()
{ $server="localhost"; $user="root"; $pass="";
$con= mysql_connect($server, $user,$pass);
mysql_select_db("games"); return $con;
}

Your if statement currently is assigning values, not testing equality, you can also skip the three tests by using one of the case conversion functions... so instead the if line should be:
if(strtolower($answer)=="firefly") {
Next up - as pointed out in comments - you're using the out-of-date MySQL library, you should rather be using MySQLI or PDO
Also you're wide open to SQL injection, you should be escaping any value you're using in MySQLi see mysqli_real_escape_string. In your example this means escaping the value of $nam
A potential alternative script-fragment (using MySQLi and the above if statement changes) might look something like:
<?php
$mysqli = new mysqli("localhost", /*username*/"root", /*pass*/"", /*dbname*/);
$name=$mysqli->real_escape_string($_GET["name"]);
if (strtolower($_GET["ans"])=="firefly") {
if (!$mysqli->query("UPDATE user SET level='2',score='50' ".
"WHERE name='$name'")) {
echo "query failed";
} else {
echo "Updated"
}
$mysqli->close();
} else {
echo "try again..";
}

Related

php function with mysqli

This is my fonction.php :
<?php
function connect(){
$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
?>
But it does not works with my code when I want to call this function :
<?php
include("fonctions.php");
?>
<html>
<form name="inscription" method="post" action="form.php">
xxx : <input type="text" name="xxx"/> <br/>
xxx: <input type="text" name="xxx"<br/>
<input type="submit" name="valider" value="OK"/>
</form>
<?php
if (isset ($_POST['valider'])){
$titre=$_POST['xxx'];
$auteur=$_POST['xxx'];
connect();
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
}
?>
</body>
</html>
Before I was using mysql_connect and it was more simple, my fonction was like this :
<?php
function connect(){
$base = mysql_connect ('localhost', 'root', '');
mysql_select_db ('MaBase', $base) ;
}
?>
What is the best way to create a good include with my mysql params ? THanks all for any help.
Include obligatory statement about using PDO or mysqli and prepared statements when using variables in your SQL statements...
You aren't passing your function a SQL statement to use, or otherwise defining $sql in the function.
function connect($sql){
For defining it, and then to call it
$sql_statement="select foo from bar where bee=1";
$res=connect($sql_statement);
You'll also need your function to return some sort of value.
What I've done is create a generic function that takes a SQL statement and an array of positional parameters, the function then uses PDO and prepared statement to execute the query using the parameters, and then returns an array with appropriate data. $ret[0] is a bool to indicate success, if false then [2..N] contain(s) error message(s), if true then [2..N] contains returned record set for a select, number of rows affected for update, delete, and last_insert_id for an insert statement (detected by using regular expression on the query string)
This is written once, and require_once()'d all across 15 web apps for the college I work at.
To this you i suggest you to use OOP approach i am just suggesting this with my own way you can try it with different ways no problem in my answer i am using two class first class does all the database connection and mysqli real escape conversion and staff other class is query class it's handle all the querying staff
database.class.php
//databaseconnection
class DatabaseConnections{
function connect($databaseNaem){
try{
return $connection=mysqli_connect("localhost","user","password",'database');
}catch(Exception $e){
echo 'Message:'.$e->getMessage();
}
}
function CloseConnection($dataObject){
if(mysqli_close($dataObject)){
return 1;
}else{
echo "coudn't Close the Database Connection";
}
}
function convert($connection , $vari){
return mysqli_real_escape_string($connection,$vari);
}
}
//queryclass
class Query{
function queryNoresult($stmt){
if($stmt->execute()){
return 1;
}
}
function queryNumOfRows($stmt){
$stmt->execute();
$result = $stmt->get_result();
return mysqli_num_rows($result);
}
function QueryResult($stmt){
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
function illcallothers($stmt,$callto){
if($callto == 1){
return $this->queryNoresult($stmt);
}if ($callto==2) {
return $this->queryNumOfRows($stmt);
}
if($callto == 3){
return $this->QueryResult($stmt);
}
}
}
as you can see at the end i have created a function call illcallothers and this function takes what you want do with your query it's takes only 2 parameters
Created statement
The function number
there 3 option in this
if you call $query->illcallothers($stmt,1) this call the function
only for execute best for delete and insert because it's return 1 if
it's success
if you call $query->illcallothers($stmt,2) this call the function that return number of rows that returned nothing else best for check it data is availbe before using while
if you call $query->illcallothers($stmt,3) this will return result set from your query
Now lets go to your problem execution
//first you have to require the database file
require_once('database.class.php');
//Then you have to create object from them
$mymainObj = new DatabaseConnections();//obj from database
$connetion = $mymainObj->connect('databasename');//this will return a connection Object
$stmt = $connection->stmt_init(); //then the statement you need the connection object to this
$query = new Query();//object from the query class
//i am not going to put form part in here it will get messy
$titre= $mymainObj->convert($connection,$_POST['xxx']);//calling mysqli realescape funciton in databaseconnection
$auteur=$mymainObj->convert($connection,$_POST['xxx']);
//now you have create the sql
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES(?,?)';//when using stmt this how we tell mysql that we have this much parameters and then we pass them after preparing
if($stmt->prepare($sql)){
$stmt->bind_param('ss',$title,$author);
if($query->illcallothers($stmt,1)){
echo "Query Success";
}
}
It should be,
<?php
function connect(){
$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
return $conn;
}
}
?>
Your query should be,
<?php
if (isset($_POST['valider'])){
$titre=$_POST['xxx'];
$auteur=$_POST['xxx'];
$connection = connect();
if($connection != false){
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
$result=$connection->query($sql);
if($result){
echo "done";
}else{
echo "faild";
}
}
}
?>
You should take a tour/learn the basics of OOP
It seems like all the above answers missed that you have two variables with the same name:
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
Both are called $xxx
IF YOU thought that the names of your public variables shoulden't be shown publicly here, and changed them to 'xxx', then please edit your question and don't change them to the same name (e.g change to $name and $password for example)

Checking to see if ID is already in database, if it is don't INSERT it again

When I run the page with an empty database, it will insert the data correctly. When I run the page again, it displays there is already an ID in the database, but it inserts it anyway. Not sure how or why but I've tried every combination of booleans inside the if statements and cant get it to chooch correctly.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database:
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Ask the database for some sweet, sweet data:
$stmt1 = "SELECT orderID FROM orders";
$result = $mysqli->query($stmt1);
//flag (we want to believe that there are no similar IDS so lets make it true):
$flag = true;
//while we got some data, display that shit
while ($row = $result->fetch_assoc()) {
//asign data to variable:
$rowOrderID = $row['orderID'];
//Does it match? if it does set the flag to false so it doesnt get inserted.
if ($rowOrderID == $orderID) {
echo "Row ID" . $row["orderID"] . " Passed ID: " . $orderID . "<br>";
echo "This order is already in the database" . "<br>";
$flag = false;
}
}
//hand the flag over to who ever needs it
return flag;
}
.
if (checkOrderID($orderID) == true) {
//some mysql insert logic here
}
Why are you making this complicated. just do something like this:
$con=mysqli_connect("localhost","root","","price");
$check_query = mysqli_query($con,"SELECT * FROM orders WHERE orderID = $orderID");
if (mysqli_num_rows($check_query) == 0) {
//mysql insert logic here
}
(Noted of course you are going to have your connection logic as well)
Note: You are using Mysqli in object oriented manner but in this example i have not used object oriented manner of DB connection. The connection variable $con must be passed to mysqli_query() method.
Also... random side note, but it's generally a good idea to have a password for your root mysql user.
Here better and short, but please try to use DB connection globally not inside your mothod and try to use prepared statements. But except those you can use following code.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database: I suggest use global DB connection
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//gets recodrs based on $orderID passed to this method
$stmt1 = "SELECT * FROM orders where orderID=$orderID"; //Try to use prepared statement
$result = $mysqli->query($stmt1);
//Store number of rows found
$row_count = $result->num_rows;
if($row_count>0){
return true;
}
else{
return false;
}
}

mysql error: not a valid mysql resource

I have a problem when i try to check if email is alredy registered. can someone help? I have this error:
mysql_fetch_array(): supplied argument is not a valid MySQL result resource in line...
($record =mysql_fetch_array($result); )
<?php
$nome = $_REQUEST["nome"];
$cognome = $_REQUEST["cognome"];
$psw = $_REQUEST["psw"];
$email = $_REQUEST["email"];
$nikName = $_REQUEST["nikName"];
$conn = mysql_connect("host,name","userName","Password","databaseName");
if(!$conn) {
echo "connessione non satabilita";
} else {
if(!mysql_select_db("databaseName",$conn)) {
echo "database non trovato";
} else {
$sql = "select * from utenti where User='$email'"; //costruzione comando di ricerca
$result = mysql_query($sql,$conn); //assegnazione risultati
$record =mysql_fetch_array($result); //estrazione primo risultato
if(!$record) {
$sql = "INSERT INTO User (UserId, Nome, Cognome, Email, Username, Password, TimeStamp) VALUES (NULL,'$nome','$cognome','$email','$nikName','$psw', NULL)";
$result=mysql_query($sql);
if($result) {
echo "utente registrato correttamente";
} else {
//Error
echo "errore registrazione, riprovare più tardi";
}
echo "<br />";
echo "utente registrato";
} else {
echo "utente gia registrato";
}
}
}
?>
Before this gets out of hand.
$conn = mysql_connect("host,name","userName","Password","databaseName");
You're using 4 parameters rather than 3.
Sidenote: 4 parameters is mysqli_ syntax http://php.net/manual/en/function.mysqli-connect.php
Be careful though, those different MySQL APIs do not intermix. So you cannot have mysql_ with mysqli_ should you decide to change it to that.
The manual http://php.net/manual/en/function.mysql-connect.php states:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
the fourth is for something else.
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored.
So, just remove the 4th parameter.
Sidenote: This is questionable "host,name" (with the comma). Double check it as to what your host (if hosted) has provided you with. Most of the time, that should read as "localhost".
As stated, you're open to SQL injection.
Use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
As for the rest of your code:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Also add or die(mysql_error()) to mysql_query().
About you're wanting to check if an email exists; you may be better off using mysql_num_rows().
I.e.:
$sql = "select * from utenti where User='$email'";
$result = mysql_query($sql,$conn) or die(mysql_error($conn));
if(mysql_num_rows($result) > 0)
{...}
else {...}
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Also, this doesn't help you:
if(!mysql_select_db("databaseName",$conn)){
echo "database non trovato";
}
This does:
if(!mysql_select_db("databaseName",$conn)){
die ('Can\'t use the database : ' . mysql_error());
}
In order to get the real error, should there be one.
Reference:
http://php.net/manual/en/function.mysql-select-db.php
As mentioned above there is a syntax error with mysql_connect(); where you're trying to use invalid number of params. The best way is to make a config.php file and then use it whenever you need it. This is a basic connection code in PDO.
<?php
$host = "localhost";
$database = "yourdbnamehere";
$username = "yourusernamehere";
$password = "yourpasswordhere";
try {
$dbo = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
You will need a solution like this. But you must switch towards PDO or MySQLi to ensure that your code stays valid in long run as well as you will be able to write secure and stable code.
Go through these at first:
http://php.net/manual/en/book.pdo.php
http://php.net/manual/en/book.mysqli.php
An example code for you solving your current problem:
<?php
$nome = $_REQUEST["nome"];
$cognome = $_REQUEST["cognome"];
$psw = $_REQUEST["psw"];
$email = $_REQUEST["email"];
$nikName = $_REQUEST["nikName"];
try{
$pdo = new PDO('mysql:dbhost=hostname; dbname=databaseName', 'userName', 'Password');
} catch (PDOException $e) {
echo "Error connecting to database with error ".$e;
die();
}
// check for email
$sql = $pdo->prepare("select * from utenti where User= ?");
$sql->bindParam('1', $email);
$sql->execute();
/* if you aren't hashing the password,
then do it first
$psw = PASSWORD_HASH($psw, PASSWORD_DEFAULT);
*/
// Insert if email not registered
if($sql->rowCount() == 0) {
$insert = $pdo->prepare("INSERT INTO User (Nome,Cognome,Email,Username,Password) VALUES (?, ?, ?, ?, ?)");
$insert->bindParam('1', $nome);
$insert->bindParam('2', $cognome);
$insert->bindParam('3', $email);
$insert->bindParam('4', $nikName);
$insert->bindParam('5', $psw);
$insert->execute();
if($insert->rowCount() > 0) {
echo "utente registrato correttamente";
} else {
echo "errore registrazione, riprovare più tardi";
}
} else {
echo "utente gia registrato";
}
?>

MySQLi present still not connecting to database

I ran var_dump(function_exists('mysqli_connect')); and it returned boolean true.
I am running the following code
<?php
$connect=mysqli_connect("localhost","root","root","dbname") or die("Unable to Connect");
$showtablequery="SHOW TABLES FROM dbname";
$query_result=mysqli_query($showtablequery);
while($showtablerow = mysqli_fetch_array($query_result))
{
echo $showtablerow[0]." ";
}
?>
It did not do anything. It did not print anything on the result webpage.
When I use mysql functions instead then it works fine.
What do I need to do to use mysqli function?
Oop
<?php
$mysqli = new mysqli("localhost","root","root","dbname") or die("Unable to Connect");
$showtablequery="SHOW TABLES FROM dbname";
$query_result=$mysqli->query($showtablequery);
while($showtablerow = $mysqli->fetch_array($query_result))
{
echo $showtablerow[0]." ";
}
?>
Even if you connected successfully, it cannot query the database without connection informatiokn.
Procedural
<?php
$connect=mysqli_connect("localhost","root","root","dbname") or die("Unable to Connect");
$showtablequery="SHOW TABLES FROM dbname";
$query_result=mysqli_query($connect, $showtablequery);
while($showtablerow = mysqli_fetch_array($query_result))
{
echo $showtablerow[0]." ";
}
?>
Instead of
$query_result=mysqli_query($showtablequery);
use
$query_result=$connect->query($showtablequery);
and instead of
$showtablerow = mysqli_fetch_array($query_result);
use
$showtablerow = $query_result->fetch_array();

mysql query in a function... not working

I made this function. It's actually one of the first functions I've ever made. However, I can't get it to execute.
$con is defined, i just didn't paste it. In fact, all of the variables are defined.
function cleanse() {
$cleansesql = "Select * FROM rated_teams WHERE server='$server' AND name='$myteam' AND opposition='$opposer'";
$result = mysqli_query($con, $cleansesql)
or die('A error occured: '.mysqli_error());
while (($row = mysqli_fetch_array($result))) {
if ($row['server'] == $server && $row['name'] == $myteam && $row['opposition'] == $opposer && $row['myscore'] == $myscore && $row['oscore'] == $oscore && $row['location'] == $location) {
echo "There is a Match.";
} else {
echo "There are no matches";
}
}
}
And this is how I'm calling it.
if ($solo == "solo" || $solo == "Solo" || $solo == "SOLO") {
echo $solo." <br />";
if (!empty($myscore)) {
echo $myscore." <br />";
if (!empty($oscore)) {
echo $oscore." <br />";
if (!empty($location)) {
echo $location." <br />";
cleanse();
}
}
}
}
Maybe I'm not calling it correctly. I just need someone who knows more than me to help... that'll be most of you hahaha.
Pass the information to your cleanse function, like $con (given that you've created your connection to the database prior to calling this function), $server, $myteam and $opposer so it can work with it.
So the definition of your function would become:
function cleanse($con, $server, $myteam, $opposer) { ... }
And you'd call it this way:
cleanse($con, $server, $myteam, $opposer);
Notice that you are using a variable $con which is the connection to MySQL.
You have not created a connection to MySQL prior to the query.
I suggest reading the basic PHP manuals on using mysqli.
Remeber the follwing:
You need to connect to SERVER
You need to choose the DB u work against
You will execute queries against that DB.
2 is not mandatory.
Campari is right - that is why your function is not working, however:
You are duplicating your code. The function does not need to check if there is a match between your test criteria and the output of the sql because the database does that for you. What your sql says is "fetch all the results that match all of my criteria" then your function says "check all the results match my criteria" this is slow and not required. If you write your sql properly, there is rarely any need for further checking or merging of data in PHP.
function cleanse($connection, $server, $myteam, $opposer)
{
$cleansesql="Select * FROM rated_teams WHERE server=? AND name=? AND opposition=?";
$stmnt=$connection->prepare($cleansesql);
$stmnt->bind_param("sss",$server,$myteam,$opposer);
$stmnt->execute();
$stmnt->store_result();
return $stmnt->num_rows;
}
This (untested) function I've written for you should return the number of rows in rated_teams that match all of the criteria in your variables. It is also safe to input user-entered data as it uses prepared statements and is thus not susceptible to SQL injection.

Categories