Cant seem to get this query to work [duplicate] - php

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
This query was working on mij older login script, But now that i have this new login script, my code had to change a litlle, Wich i cant seem to pull off. Im think the troubles are in the end where the if user is online is checked...
This is my code
<?php
session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php
function pay_credits() {
mysqli_query("UPDATE `tbl_users` SET `credits`=`credits`-'1' WHERE `watching`='1' AND `credits`>'0' AND userID=:uid");
}
?>
<?php
pay_credits();
?>
The top script is working fine, But the function pay_credits doesnt work, Ive tried changing mysql to mysqli as i hear alot over that it has deprecated and stuff, But still no result, Ive also been reading about pdo but i have no knowledge of this. Any help is welcome, I also like to learn so maybe you can explain what you`ve done a litlle. Thnx :)

First: if you read mysqli_query manual, you'll see that mysqli_query takes two arguments. First is link and second is a query string.
Do you see a link in your pay_credits function? Nope.
Second: I noticed that you use PDO::FETCH_ASSOC and then suddenly switch to mysqli.
PDO and mysqli are totally different APIs and you should choose which one you use.

You use pay_credits() without settings, your function mysqli_query need a params for db connection.

Related

How to make my search engine safe? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I have been making a search engine for my website and just got it completed i am using an ajax request to search the database and wanted to know how i can make it safe from any injections?
Search.ajax.php
<?php
$db = new mysqli('localhost', 'root', 'root', 'social');
$search = $_POST['search'];
$query = mysqli_query($db, 'SELECT * FROM users WHERE username LIKE "'.$search.'"');
if (mysqli_num_rows($query) < 1) {
echo "<b>No results found for <i>".$search."</i></b>";
}else{
while ($r = mysqli_fetch_assoc($query)) {
$user = $r['username'];
echo '<div>Go to <a href="profile.php?user='.$user.'">'.$user.'</p></div>';
}
}
?>
I am searching the database for users that have the username of what they put in the search box. i need help making it so no one can search alert(test); if they search this it will show up an alert box here is an example of it.here is a photo of when someone puts in script tags
Firstly, you will need https to make sure you protect users from hackers by using firewalls and other required security tools.
Secondly, you need to use htaccess to change extensions, say show user .html instead of .php
Thirdly, encrypted values instead of plain text.
There are a lot more issues to take care of but its too complex and broad.

Trying to make a maintenance mode with PHP and a database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Okay so I am running into an issue with my code since no matter what I change it to, it stays on the index page?
Here is my code
<?php
// Maintenance mode
$system = (mysql_query("SELECT * FROM system"));
if($system['maintenance'] == 1)
{
header('Location: /maintenance');
exit;
}
?>
I want it so if maintenance = 1 it would send you to the maintenance.php page but it doesn't can anyone help me with this? I tried,
if(!$system['maintenance'] == 1)
which works but I have this code in my maintenance.php page
<?php
$system = (mysql_query("SELECT * FROM `system`"));
if(!$system['maintenance'] == 0)
{
header('Location: /index');
exit;
}
?>
What I thought would send me back to the index page once that in the database it shows it is a 0 or that's what I want it to do. Can anyone please explain why my code isn't working?
I am a beginner php, mysql, and C++ coder / programmer so please try to explain it the easiest way possible.
I fixed it thanks to #Script47.
New code and works
<?php
$system = mysql_query("SELECT * FROM system");
$results = mysql_fetch_array($system);
if($results['maintenance'] == 1)
{
header('Location: /maintenance');
exit;
}
?>
The reason I do not need an extension for maintenance is because I have it set in .htaccess to ignore them, but for everyone to know it's a php file.
You need to actually fetch your results from the database. Look in to the link I provided. I will update my post with code.
<?php
$system = mysql_query("SELECT * FROM system");
$results = mysql_fetch_row($system);
if($results[yourColumnKey] == 1)
{
header('Location: /maintenance.php');
exit;
}
?>
http://php.net/manual/en/function.mysql-fetch-row.php
Edit 1
Your code is prone to SQL injection, you are still using MySQL even though it has been deprecated, you should use either MySQLi or PDO with prepared statements.
Edit 2
You don't seem to be specifying a file extension on your header();.
header('Location: /maintenance');
--^
What is maintenance? A PHP file? A HTML file? You need to specify an extension too.
As you are a self-described beginner, it's probably best to learn how to do this using mysqli instead of using old deprecated code.
Below does essentially the same thing, but will last past the current version of php. It's a good habit to get into. (note if you are going to use any variables in your query, you will want to look up Prepared Statements
$conn = new mysqli($host, $username, $password, $dbname);
$system = $conn->query("SELECT maintenance FROM `system`");
while ($row = $system->fetch_assoc()) {
if($row['maintenance'] == 1) {
header('Location: /maintenance');
exit();
}
else {
header('Location: /index');
exit();
}
}

PHP echo ID after register on mysql database [duplicate]

This question already has answers here:
How do I get the last inserted ID of a MySQL table in PHP?
(16 answers)
Closed 7 years ago.
Hello guys I have this php code to register building data in a game that I'm developing. This code work fine.
What I like to know is how can I echo the auto increased ID of the object that I registered using this code when the register function successful.
<?php
$db = "database";//Your database name
$dbu = "username";//Your database username
$dbp = "password";//Your database users' password
$host = "localhost";//MySQL server - usually localhost
$dblink = mysql_connect($host,$dbu,$dbp);
$seldb = mysql_select_db($db);
if(isset($_GET['oid']) ){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$name = strip_tags(mysql_real_escape_string($_GET['oid']));
$sql = mysql_query("INSERT INTO `$db`.`building` (`id`,`oid`) VALUES ('','$oid');");
if($sql){
//The query returned true echo the newly registered id
echo '????';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'Fail to save data';
}
}else{
echo 'Fail-No object owner ID';
}
mysql_close($dblink);//Close off the MySQL connection to save resources.
?>
Please help me.
Use mysql_insert_id()
if($sql){
//The query returned true echo the newly registered id
echo mysql_insert_id($dblink);
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'Fail to save data';
}
Notes:
Here is reasoning of why you should not use Mysql but mysqli extension for php
MySQL vs MySQLi when using PHP
From PHP developers:
It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

MySQLi - property access is not allowed yet [duplicate]

This question already has answers here:
mysqli + xdebug breakpoint after closing statement result in many warnings
(6 answers)
Closed 2 years ago.
Im' getting this warning "property access is not allowed yet" when trying to close mysqli connection. WHY?
$mysqli = new mysqli ( $database ["dbUri"], $database ["dbUserName"], $database ["dbPassword"], $database ["dbSchema"], $database ["dbPort"] );
$mysqli->autocommit(FALSE);
$con = $mysqli;
$rowsAffected = /* completes insert using $con */;
if ($rowsAffected==0) {
throw new Exception("Insert of new record failed");
}
$insertId = $con->insert_id;
$con->commit();
$con->close();
BTW, the insert is successful and I have the correct value in $insertId. Commit works well too, but it's the close that triggers the warning.
I hid the code in /* completes insert using $con */ section as it is long and irrelevant (the sql works). So unless you think it is relevant I only included the rest.
I looked at similar questions but other posts refer to the connection not being established. However, my connection works. PLEASE see the point about "insert is successful".
As far as my analysis of this intermittent problem has concluded (at least in my case), this is some kind of bug in either the mysqli extension or the PHP debugger (XDebug), since it only happens when I breakpoint/single-step the program, but not when simply running the same code without breakpointing/single-stepping any code before the page rendering has completed.
Does it still happen for you if you don't breakpoint or single-step any code before the page rendering is complete?

MySQLi Commands out of sync, with simple query() function

I can't figure out why I'm getting the Commands out of sync; you can't run this command now error. I can't seem to find a way to fix this.
As you can probably see from the code, I need to execute TWO SQL statements. One to check if the password is correct, and the other, which runs only if the previous one returns true, to store all user data in session variables.
Here is my code:
$check_pw_query = $conn->query("CALL checkPassword('{$username}', '{$password}')");
$check_pw_fetched = $check_pw_query->fetch_assoc();
$check_pw_query->close();
if($check_pw_fetched['password_correct']) {
unset($check_pw_fetched);
if(!$get_user_data = $conn->query("CALL getUserData('{$username}')")/*->fetch_assoc()*/) {
echo $conn->error;
}
$_SESSION["user_username"] = $username;
$_SESSION["user_id"] = $get_user_data["id"];
$_SESSION["user_name"] = $get_user_data["name"];
$_SESSION["user_email"] = $get_user_data["email"];
$_SESSION["user_type"] = $get_user_data["type"];
$conn->close();
unset($conn);
send_home(false);
}
Help is much appreciated.
Thank you
Ok, as there were no real helpfully answers, I'll answer it myself, to hopefully help someone else with the same problem.
The problem is that, whenever you call a stored procedure, it will output one more result that defined anywhere. So if your procedure returns 1 value, php will get 2. The last one is only there to tell you that there are no more values. BUT you have to deal with that one as well to free the connection ($conn in my example).
So, that you do is, simply, add this to your code, right after the $check_pw_query->close(); :
$conn->next_result();
And there you have it. It will now work perfectly fine.

Categories