Alright. I have searched and searched for an answer, but I just could not find it.
I am writing a simple php script that takes the url information and runs it through a MySQL query to see if a result comes up. I try to echo the variable holding the query out, but nothing shows up. I know there must be a result because if I enter the query manually in MySQL it displays my desired result.
$result = mysqli_query("SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
I have tried to echo out both the $result and $data. But there is nothing displayed. I am so new to programming, and this is my first StackOverflow post, so forgive me if I am making huge errors.
Actually mysqli_query() requires two parameters... check the following sample example ..
<?php
$conn = mysqli_connect('localhost','root','','your_test_db');
$_GET['page'] = 1;
$result = mysqli_query($conn,"SELECT * FROM your_table WHERE id = '" . $_GET['page'] . "'");
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
?>
As you have stated you are just in a learning phase, it is okay to code these sort of queries just to learn yourself but do not code these kind of queries as these queries are vulnerable so i would suggest you to use prepare queries or PDO...
Also never use SELECT * in your queries, this is a bad practice, only deal with the fields which you requires in return.
Also, you can always check whether your database is connected or not. So that you have a better idea.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
you have not mentioned whether you are following OOP structure or not .. so i would suggest you to check error_reporting() and connect database on the same page to check the things around ..
Also you can check whether you without WHERE condition for now "SELECT * FROM your_table just to make sure whether you are getting atleast all the records or not.
The problem is that you're not setting up the connection in the query. mysqli_query() requires two parameters.
Make the connection first:
$conn = mysqli_connect("localhost", "user", "password", "dbname");
Now execute the query:
$result = mysqli_query($conn,"SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
NOTE: Your code is heavily vulnerable to MySQL injections. Use MySQLi or PDO Prepared statements.
Also, you should use mysqli_errno() to find out your query bugs.
Edit:
Also do this:
while($row=mysqli_fetch_assoc($result)){
//do the result output.
}
Related
I have a problem with my PHP code.
I am trying to make a level create function for a small game project me and another person are working on.
My code works.. but generates a lot of duplicates.
Here's the code: (Don't laugh at me for how vulnerable this is, this will be fixed eventually, THIS IS JUST TEST CODE AND WILL NEVER BE ON A PUBLIC SERVER IN ANY CIRCUMSTANCE, OK?)
$mysqli = new mysqli("localhost", "Username", "Password", "sys");
$SqlQuery = "INSERT INTO levels (levelname, levelauthor, leveldata)
VALUES(\"" . $_GET["levelName"] . "\", \"" . $_GET["levelAuthor"] . "\", \"" . $_GET["levelData"] . "\");";
$query2 = "SELECT * FROM levels WHERE leveldata = \"" . $_GET["levelData"] . "\";";
//echo "SELECT * FROM levels WHERE leveldata = \"" + $_GET["levelData"] + "\";";
$uresult = $mysqli->query($SqlQuery, MYSQLI_USE_RESULT);
$res2 = $mysqli->query($query2, MYSQLI_USE_RESULT);
if ($uresult) {
while ($row = $res2->fetch_assoc()) {
//This should always work. Lol
echo "(SUC)|ID:" . $row["levelid"];
}
}
After running this code, I expected to just check my database and be able to see the test I wrote, without duplicates.
I started the PHP development server and went to:
http://localhost/Create.php?levelName=PHPTest&levelAuthor=Test3&levelData=[snip]
I expected to see something along the lines of "(SUC)|ID:4" (there were 3 entries in the database at the time), but I saw this:
(SUC)|ID:4(SUC)|ID:5(SUC)|ID:6(SUC)|ID:7(SUC)|ID:8(SUC)|ID:9(SUC)|ID:10(SUC)|ID:11
This was unexpected. I thought it was just an error in my code (keep in mind, the last one had a broken ID grabbing system, but worked), and that it would work, but then, I went to check the database, and saw a ton of duplicates with the same data.
Does anyone know how to fix this code?
Obvious question but autocommit is enabled on database?
Do you have some open transaction?
Use this to check open transactions on MySQL.
i am very new at MYSQL and after i created this script to update a row in the table of a MYSQL Database and run it i get this error
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '265'', Employer_VAT_number = ''45698'', Employer_Name = ''Namtax_Ltd'', Employer' at line 3
here is the code
// username and password sent from form
$Numb=$_POST["Numb"];
$VAT=$_POST["VAT"];
$Name=$_POST["Name"];
$Addr=$_POST["Addr"];
$PO=$_POST["PO"];
// To protect MySQL injection (more detail about MySQL injection )
$Numb = stripslashes($Numb);
$VAT = stripslashes($VAT) ;
$Name = stripslashes($Name) ;
$Addr = stripslashes($Addr) ;
$PO = stripslashes($PO) ;
$Numb = "'" . mysql_real_escape_string($Numb) . "'";
$VAT = "'" . mysql_real_escape_string($VAT) . "'";
$Name = "'" . mysql_real_escape_string($Name) . "'";
$Addr = "'" . mysql_real_escape_string($Addr) . "'";
$PO = "'" . mysql_real_escape_string($PO) . "'";
$sql=("UPDATE $tb1_name SET Employer_Registration_Number ='".$Numb."', Employer_VAT_number = '".$VAT."', Employer_Name = '".$Name."', Employer_Address = '".$Addr."', Employer_Postal_Address = '".$PO."' WHERE Employer_Name = '".$Name."' ");
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Successfully Updated";
mysqli_close($con);
?>
</body>
This here:
$Numb = "'" . mysql_real_escape_string($Numb) . "'";
Firstly, that isn't proper syntax and you're using mysqli_ to connect with, least I sure hope you are.
Those different MySQL APIs do not intermix with each other.
That should read as:
$Numb = mysqli_real_escape_string($con,$Numb);
while doing the same for the rest of your variables, following the same method outlined here.
Footnotes:
Seeing you didn't post what $tb1_name is, doubt that would be causing an issue. But just for the sake of argument, wrap that variable in ticks, just so if your table name changes to something containing a hyphen or a space, or anything that MySQL will complain about.
UPDATE `$tb1_name` SET...
Plus, since you didn't mention which MySQL API you're using to connect with, make sure it is in fact mysqli_ and not mysql_ or PDO.
It doesn't look like it, but I have to be 100% sure.
Your connection should resemble something like this:
$con = mysqli_connect("yourhost","user","pass","your_DB")
or die("Error " . mysqli_error($con));
Again, those different MySQL APIs do not intermix with each other.
Consult (PHP: Choosing an API - Manual): https://php.net/mysqlinfo.api.choosing
"I am very new at MYSQL..."
Seeing you're new to this:
Use mysqli with prepared statements, or PDO with prepared statements.
Additional notes. (as an edit)
I noticed another question you posted earlier:
https://stackoverflow.com/q/30191388/
where you said "Thank you it worked " in the answer given https://stackoverflow.com/a/30191647/
I don't get that.
How could that possibly work where you're using if (!mysqli_query($con,$sql))?
You'll need to show us the way you're connecting with here.
If you truly want to see if your query was successful, use mysqli_affected_rows().
if(mysqli_affected_rows($con)){
echo "Successfully updated.";
}
else{
echo "Not updated.";
}
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: Error reporting should only be done in staging, and never production.
I am new to PHP and I have faced an interview some days ago. They gave me a PHP code to find out the errors and bad programming practices. I have pointed out some of the errors and bad practices. But I am not sure about all the bugs in the code. Can you please help me to find out the exact answer, so I can improve my answer in the next interviews.
My suggestions are:
Include an external PHP file based on user request is not a good practice
HTML is mixed with PHP, not using MVC architecture style
Writing connection query in same file
is_authorized() function is not defined
mysql_connect is deprecated, can use mysqli
Here is the code
<?php
function output()
{
// Check authorization
if(is_authorized())
{
$authorized = true;
include('/path/to/' . $_REQUEST['module'] . '.php');
}
echo "<ul>";
$conn = mysql_connect( "mysql.foo.org:324", "root", "root" );
mysql_select_db( "conteol", $conn ); // selects a database
$q = " SELECT * FROM main WHERE id > " . $_GET["id"]. ";";
$res = mysql_query( $q, $conn);
while( $row = mysql_fetch_assoc( $res ) )
{
echo "<li>".$row['description']."</li>";
}
echo "</ul><br><ul>";
$q = " SELECT * FROM main WHERE id < " . $_GET["id"]. ";";
$res = mysql_query( $q, $conn);
while( $row = mysql_fetch_assoc( $res ) )
{
$authorized = true;
include('/path/to/' . $_REQUEST['module'] . '.php');
echo "<li>".$row['description']."</li>";
// Display the status if it is authorized, othewise display N/A
echo "<li>".$row['description']. "(" .
$authorized ? $row['status'] : "N/A" . ")</li>";
}
echo "</ul>";
}
?>
Some more thoughts:
Using $_GET['id'] directly in an SQL query is not a good idea. You should probably call intval() on it.
Using $row['description'] directly for output is not a good idea. You should probably call htmlspecialchars() on it.
$authorized=true; is set in the code in the while loop without calling is_authorized()
include('/path/to/' . $_REQUEST['module'] . '.php'); is called in the while loop. Should be called outside the loop. Maybe, include_once() is a better idea.
The whole code is executed even if is_authorized() returns false.
I could add some more to that list:
Poor/inconsistent indentation
Inconsistent formatting
Undescriptive variables name
Security vulnerability using $_REQUEST in include
Open to SQL injections using $_GET in SQL queries
Being somebody who has interviewed for new PHP developers myself, it is the security issues that I would have really been looking for.
Formatting/indentation is terrible
$_REQUEST should never be used, always use the method-specific array
No error checking for mysql connection
No SQL injection protection
Do not use include, use include_once
Double MYSQL query for basically the same check: using WHERE id != $id would also work
Authorisation in second loop is always set to true
Displaying "N/A" for something you don't have access to is pointless.
I need start using the mysqli extension but I'm finding all kinds of conflicting info depending on how all the info is that I'm trying to use.
For example, my header connects to a 'config.php' file that currently looks like this:
<?php
$hostname_em = "localhost";
$database_em = "test";
$username_em = "user";
$password_em = "pass";
$em = mysql_pconnect($hostname_em, $username_em, $password_em) or trigger_error(mysql_error(),E_USER_ERROR);
?>
But when I go to php.net I see that I should be using this but after updating everything I get no database.
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
?>
I also went through and added an "i" to the following code in my site and again no luck:
mysql_select_db($database_em, $em);
$query_getReview =
"SELECT
reviews.title,
reviews.cover_art,
reviews.blog_entry,
reviews.rating,
reviews.published,
reviews.updated,
artists.artists_name,
contributors.contributors_name,
contributors.contributors_photo,
contributors.contributors_popup,
categories_name
FROM
reviews
JOIN artists ON artists.id = reviews.artistid
JOIN contributors ON contributors.id = reviews.contributorid
JOIN categories ON categories.id = reviews.categoryid
ORDER BY reviews.updated DESC LIMIT 3";
$getReview = mysql_query($query_getReview, $em) or die(mysql_error());
$row_getReview = mysql_fetch_assoc($getReview);
$totalRows_getReview = mysql_num_rows($getReview);
And here's the only place on my display page that even mentions mysql so far:
<?php } while ($row_getReview = mysql_fetch_assoc($getReview)); ?>
I did see something at oracle that another stackoverflow answer pointed someone to that updates this stuff automagically, but I have so little code at this point it seems like overkill.
Adding an i to any mysql function won't make it a valid mysqli function. Even if such function exists, maybe the parameteres are different. Take a look here http://php.net/manual/en/book.mysqli.php and take some time to check mysqli functions. Maybe try some examples to become familiar with the way things work. I also reccomend you to choose either object oriented code, either procedural. Don't mix them.
I just made the switch to mysqli lately, took me a few hours to wrap my head around it. It works well for me, hope it will help you out a bit.
Here the function to connect to the BD:
function sql_conn(){
$sql_host = "localhost";
$sql_user = "test";
$sql_pass = "pass";
$sql_name = "test";
$sql_conn = new mysqli($sql_host, $sql_user, $sql_pass, $sql_name);
if ($sql_conn->connect_errno) error_log ("Failed to connect to MySQL: (" . $sql_conn->connect_errno . ") " . $sql_conn->connect_error);
return $sql_conn;
}
This will return a Mysqli Object that you can use to make you request afterward. You can put it in your config.php and include it or add it at the top of your file, whatever works the best for you.
Once you have this object, you can use it to make your query against the object like so: (in this case, if an error came up it will be outputted in the error_log. I like having it there, you can echo it instead.
//Use the above function to create the mysqli object.
var $mysqli = sql_conn();
//Create the query string (truncated for the example)
var $query = "SELECT reviews.titl ... ... ted DESC LIMIT 3";
//Launch the query on the mysqli object using the query() method
if(!($results = $mysqli->query($query))){
//It it fails, log the error
error_log(mysqli_error($mysqli));
}else{
//Manipulate your data.
//here it depends on what you retunr, a single value, row or a list of rows.
//Example for a set of rows
while ($record = $results->fetch_object()){
array_push($array, $record);
}
}
//Just to show, this will output the array:
print_r($array);
//Close the connection:
$mysqli->close();
So basically, in mysqli, you create an object and use the method to work your way out.
Hope this helps. Once you figured it out, you will most likely enjoy mysqli more that mysql. I did anyway.
PS: Please note that this was copy/pasted from existing, working code. Might have some typo, and might forgot to change a var somewhere, but it's to give you an idea of how mysqli works. Hope this helps.
I'm a beginner and trying to get a handle on php. I have been getting a syntax error that I can't seem to solve. I'll show you the code below and some of the fixes I've tried. If anyone has another idea that would be wonderful. Thank you:)
$subject_set = mysql_query("SELECT * FROM subjects", $connection);
if(!$subject_set){
die("Database query failed: " . mysql_error());
}
while($subject = mysql_fetch_array($subject_set)) {
echo "<li> {$subject['menu_name']} </li>";
}
$page_set = mysql_query("SELECT * FROM pages WHERE id_subjects = {$subject["id"]}", $connection);
if(!$page_set){
die("Database query failed: " . mysql_error());
}
echo "<ul class='pages'>";
while($page = mysql_fetch_array($page_set)) {
echo "<li> {$page['menu_name']} </li>";
}
echo "</ul>";
I get: Database query failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near " at line 1
I know the problem is at {$subject["id"]} because I got content back and no error when I put "WHERE id_subjects = 1". I've tried:
{$subject['id']}
{$subject[\"id\"]}
But have gotten the same error...
try
$page_set = mysql_query("SELECT * FROM pages WHERE id_subjects = '".$subject["id"]."'", $connection);
if(!$page_set){
die("Database query failed: " . mysql_error());
}
BTW. you should really move away from mysql_* functions. They are being deprecated, move to PDO or mysqli_*, which are a lot safer as well (you are now vulnerable to sql injection)
If you read back to your post, you can clearly see what's going wrong here.
"SELECT * FROM pages WHERE id_subjects = {$subject["id"]}"
As you can see "id" is not connected to the rest of the rest. That is because with the " you close the string.
To fix this simply use
"SELECT * FROM pages WHERE id_subjects = " . $subject["id"]
Or if you really want to put the variable within the string you can use a single quoted string for the key:
"SELECT * FROM pages WHERE id_subjects = {$subject['id']}"
Personally I am a fan of the first solution. But that is just my opinion.
Well when the while loop finishes looping through, it will have exhausted all the results. $subject['id'] won't have any information simply because $subject no longer has any more entries.
I'm guessing you want to list all the subjects first, then all the pages underneath each subject.
Using mySQL isn't going to be pretty but here's what you want to do. (As Bono said use PDO or mysqli, but here's a solution in psuedocode that will work with mySQL).
loop through first query
print subject name
select pages using subject id
loop through pages under that subject id
print page names
You don't need any quotes when inside a quoted string, just use
"SELECT * FROM pages WHERE id_subjects = {$subject[id]}"