PHP mySQL xampp fatal error - php

When i run my php file with the following code:
<?php
//configurution of server
$serve = mysql_connect('localhost', 'root', 'password');
if (!$serve) { echo 'error' ; }
$db = mysql_select_db('record', $serve);
//action to include
if($_GET['action'] == 'include') {
$name = $_GET ['name'];
$lastname = $_GET['lastname'];
$SQL = "insert into user (name, lastname) VALUES ('$name', '$lastname')";
$re = mysql_query($SQL, $serve);
}
//action list
if($_GET['action'] == 'userlist') {
$SQL = "SELECT * FROM user";
$re = mysql_query($SQL, $serve);
$num = mysql_num_rows($re);
if($num > 0) {
//view screen
while ($Line = mysql_fetch_object($re)) {
echo "<b>Name: </b> {$Line->name} <b><br></b>
<b>Lastname: </b> {$Line->lastname} </br><hr>";
}
}
else {
echo 'no user recorded';
}
}
?>
This error appears:
Fatal error: Call to undefined function mysql_connect() in C:\xampp\htdocs\xampp\record\www\connect.php on line 5
I have ran the php file below to check my extension list to see if '[xx] => mysql' is displayed which it isn't. I have added 'extension=php_mysql.dll' to 'php.ini' and restarted apache & mysql but this still isn't working. I have also added 'C:\xampp\php\ext' into the 'path' environmental variable. I have checked the internet but can't seem to find a solution to my problem, can anyone please help me. Thank-you.
<?php // extensions_list.php
$list = get_loaded_extensions();
$list2 = array_map('strtolower',$list);
sort($list2);
echo '<pre>'.print_r($list2,true).'</pre>';
?>

mysql_xxx functions are deprecated, use mysqli_xxx or PDO instead.
http://php.net/manual/en/function.mysqli-connect.php
http://php.net/manual/en/book.pdo.php

Currently the use of mysql_connect function is not advisable because it is deprecated. Use mysqli or pdo instead.
For example:
$connection = new mysqli($dbhost,$username,$password,$dbname);
$query = "SAMPLE QUERY";
$connection->query($query);
or
Look here for PDO

Related

SQL prepared statements. PHP

May be this question will be sort of "stupid-questions", but still...
I'm new to PHP and SQL and I can't understand what I am doing wrong here:
if(isset($_POST[$logButton])) //Checking for login button pressed
{
//Retrieving information from POST method
$uid = $_POST['login'];
$upwd = $_POST['password'];
//SQL Connection
$mysqli = new mysqli('localhost', 'root', '', 'students');
if(!$mysqli)
{
echo "<h1 class='h1A'>Problem accured while connecting to the DB. " . mysqli_error($mysqli) . "</h1>"; //!!!Delete displaying error msg after dev.
}else
{
$sql = "SELECT * FROM login_data WHERE login = ? AND password = ?"; //SQL query
$stmt = $mysqli->prepare($sql) or die("error1"); //No error
$stmt->bind_param('ss', $uid, $upwd) or die("error2");//No error
$stmt->execute() or die("error3");//Giving DB query. No error
$result = $stmt->fetch() or die("error4".mysqli_error($mysqli)); //Putting query's result into assoc array. !!!Delete displaying error msg after dev. No error
echo print_r($result); //It prints out "11" ? ? ?
if(count($result['id']) < 1) //If no rows found.
{
echo "<h1 class='h1A'>Couldn't find account. Please, recheck login and password.</h1>";
die();
}elseif($result['id'] > 1)//If more then 1 row found.
{
echo "<h1 class='h1A'>Caught 9090 error. Contact the administrator, please.".mysqli_error($mysqli)."</h1>";
die();
}elseif($result['id'] == 1) //If only one row's been found.
{
$_SESSION['isLoggedIn'] = true;
redirectTo('/index.php'); //Declared function.
die();
}
}
}
Here is a part of handler function in lib.php file. This file is included to the html-page and the function is used. No errors displayed and when I print_r $result - it prints out 11. Can't get it.
Well, use print_r without echo :
print_r($result);
or pass second parameter to print_r function so it can return string:
echo print_r($result, true);
See http://php.net/manual/en/function.print-r.php for more info.

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";
}
?>

Variables undefined error in latest version of localhost (vertrigo_230)

Below mentioned PHP code was perfect on vertrigo_222 (and also on livehost).
Now I am trying to upgrade my localhost to vertrigo_230.
I am facing following undefined variable error or warning:
Here is code (line # 30 is mentioned):
<?php
ob_start();
session_start();
include_once("PHP_Code/db_connection.php");
if(isset($_REQUEST['data']))
$data = $_REQUEST['data'];
//Fetch All Important Information from Database in Variables
if($_SESSION['id'] && $_SESSION['pw']) //Login Must for This Informatiion
{
if(isset($_REQUEST['city_id']))
{
if($_REQUEST['city_id'])
{
$city_id = $_REQUEST['city_id'];
}
else
{
$query = "SELECT * FROM cities WHERE user_id = '$_SESSION[id]'";
$c = mysql_query($query) or die(mysql_error()." in query $query");
$city = mysql_fetch_array($c);
$city_id = $city['city_id'];
}
//Setting Current/Opened City in Session
$_SESSION['city_id'] = $city_id;
}
}
//Secure Page
if($data == "") //Line # 30
$data = "loginPage";
Please give me some solution.
define the $data as global variable and you have to use mysqli insted because mysql Officially deprecated
ob_start();
session_start();
include_once("PHP_Code/db_connection.php");
$data = '';
//your code

My MySQL database is not updating?

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..";
}

MySql error with a query

I'm writing a web application and now I have a problem
This is my database_connect.php:
<?php
$host = 'xy';
$user = 'xy';
$pass = 'xy';
$db = 'xy';
$dbconnect = mysql_connect($host, $user, $pass) or die("error");
mysql_select_db($db) or die("error");
?>
I am trying to establish connection to the database and insert some data with the following code:
<?
function addChapter(){
?>
<form method="post" action="">
<br>
<input name="chapter" type="text" value="Naslov">
<br><br>
<input type="submit" name="submit" value="Potrdi">
</form>
<?php
if( isset($_POST['submit']) ){
$chapter = mysql_real_escape_string($_POST['chapter']);
if( $_GET['stran'] == 'fizika' ){
$table = 'tblphysics';
}else if( $_GET['stran'] == 'kemija' ){
$table = 'tblchemistry';
}
$chapter_id_query = mysql_fetch_assoc( mysql_query("SELECT chapter_id FROM ".$table." ORDER BY chapter_id DESC LIMIT 1") );
$chapter_id = $chapter_id_query['chapter_id'] + 1;
if( ($chapter != "") && ($chapter_id != "") ){
$sql = "INSERT INTO ".$table." (chapter, version, chapter_id) VALUES ('$chapter', '1', '$chapter_id')";
$neki = mysql_query($sql, $dbconnect) or die("<p class=\"msg warning\">Napaka pri ustvarjanju poglavja.</p>");
echo '<p class=\"msg done\">Poglavje uspešno dodano.</p>';
//mysql_close($dbconnect);
}
}
}
?>
I am getting the following error:
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/a4896862/public_html/functions.php on line 81
Line 81 is
$neki = mysql_query($sql, $dbconnect) or die("<p class=\"msg warning\">Napaka pri ustvarjanju poglavja.</p>");
I know I should be using PDO or mysqli, but this will be just temporary, but it needs to work so i can continue
Anyone has any idea what is going wrong? It is causing no problem when reading from the database.
Try removing the $dbconnect argument, since the first query works as intended without it (did it ?).
$neki = mysql_query($sql) or die('...');
But, seriously, I doubt that solving issues in some outdated mess will be faster than starting database_connect.php all over. You will get much more quality answers if you use technologies that are still supported.
It seems that you don't include your database_connect.php in your second file (that contains the function). Try adding the following line before function addChapter() :
include 'database_connect.php'; // This is correct if the files are in the same directory...
Try removing the second paramater $dbconnect as it may not be in scope.
Does it work without it?

Categories