Newbe, MySQL query skips first entry - no duplicate fetch_array - php

trying to get my head around this MySQL jibberish, lol - now I do not normally ask for help but on this one I think I do need a shove.
I have searched for the answers to this however the solutions are all based around the askers duplication of the fetch_array command, however I have not done this but still this code skips the first entry.
Can someone point out what I have done here that causes this to skip...?
code:
$link = mysqli_connect('localhost','person','password', 'database'); // connect to database
if (!$link) { die('Could not connect to MySQL: ' . mysqli_connect_error()); } // problem, then die
$sql = "SELECT * FROM id_info_db"; // Query construct
$result = mysqli_query($link, $sql); //query action
while ( $row = mysqli_fetch_array($result) ) { // print out rows
echo "User: " . $row["username"]. " - Password: " . $row["password"]. " " . $row["email"]. "<br>"; }
mysqli_close($link);

For some reason I had a loose /body tag at the end? why I don't know but it generated this result. Now I have deleted it the output is correct.
A remnant that should have been deleted that throws up an unfathomable error. Lol

Related

Tutorial issues using INSERT INTO without adding a row to database for certain entries

I am following the last part of the following video tutorial "How to create a database website with PHP and mySQL 07 - Add in input form" :
https://www.youtube.com/watch?v=MGIG00d1Xzc&list=PLhPyEFL5u-i0zEaDF0IPLYvm8zOKnz70r&index=7
At the end here is my code, for the inserting portion to the database for the new_jokes.php script (everything up to this point of the series I have gotten to work fine so far)
Basically I am getting the seemingly classic "INSERT INTO" not working although all my syntax looks correct. Am I missing something obvious here? I get no errors, just the row isn't added.
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question
$new_joke_answer </h2>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES
(NULL, '$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
include "search_all_jokes.php";
?>
Return to the main page
Here is the db_connect.php code as requested:
<?php
// four variables to connect the database
$host = "localhost";
$username = "root";
$user_pass = "usbw";
$database = "test";
// create a database connection instance
$mysqli = new mysqli($host, $username, $user_pass, $database);
?>
Here is search_all_jokes.php (which has minor error checking):
// if there are any values in the table, select them one at a time
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "SELECT JokeID, Joke_question, Joke_answer FROM Jokes_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "JokeID: " . $row["JokeID"]. " - Joke_question: " .
$row["Joke_question"]. " " . $row["Joke_answer"]. "<br>";
}
} else {
echo "0 results";
}
?>
Also here is the table structure screenshot viewed in myPHPAdmin:
I added error capturing into new_jokes.php inspired by this Stack Overflow post:
INSERT INTO SYNTAX ERROR
And get the following 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 't jump.' )' at line 1localhost via TCP/IP
Thank you everyone for helping out with this! Syntax can really throw a wrench in everything. I also will read up on prepared statements since that also could have prevented the issue. The ultimate help to this I found the solution to by adding the function referenced here for MySQLi real_escape_string to clean the single quote I had within the answer I was submitting to my joke table:
(Can a kangaroo jump higher than the empire state building? Of course, the empire state building can't jump.)
As shown in the documentation #miken32 linked as a comment here it is says: "But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)"
But now the code for this part 7 of the tutorial on you tube I found works and adds it into a row on the database table, then displaying the full new table on the next webpage. I spent a good while shooting in the dark on while the answer ended up being fairly simple. Again special thanks to #miken32 for pointing me the right direction.
Here is my completed code that ended up working to at least achieve the goal of the tutorial:
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
$new_joke_question = $mysqli->real_escape_string($new_joke_question);
$new_joke_answer = $mysqli->real_escape_string($new_joke_answer);
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question $new_joke_answer
</h2>";
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES (' ',
'$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
if ($mysqli->query($sql) === TRUE) {
echo 'users entry saved successfully';
}
else {
echo 'Error: '. $mysqli->error .'<br>';
}
include "search_all_jokes.php";
?>
Return to the main page

Google SQL PHP No Data Showing - Connected

I am struggling to view some data via PHP. I have a SQL database with Google. I am struggling to extract the data and desperately need some help!
The PHP keeps saying there is 0 records, even though there is a number of records within the 'timing' database and 'events' table.
If anyone has any ideas why this is not working I would be very grateful!
<?php
$link = new mysqli('IP_ADDRESS:3306','root','PASSWORD',timing);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully ';
$sql = "SELECT event_id FROM events";
$result = $link->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Event ID</th><th>Event Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["event_id"];
}
echo "</table>";
}
else {
echo "0 results";
}
mysql_close($link);
?> 
Ok i think i got it. From PHP.net:
OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the mysqli_connect_error() function or the mysqli->connect_error property as in the preceding examples.
This means $link in your code will always be a MySQLi resource, and that it will always cast to true. What you need to do is to check your resource object for errors properly, like this:
if ($link->connect_error)
die('Connect Error: ' . $link->connect_error);
Unless timing is a defined constant, and it looks like that is not the case, being that a string you should wrap it in quotes or double-quotes. A non-defined constant should cast to a string in any case, but since i can't see any other error in your code that might be what is causing your issue. Try changing
$link = new mysqli('IP_ADDRESS:3306','root','PASSWORD',timing);
to
$link = new mysqli('IP_ADDRESS:3306', 'root', 'PASSWORD', 'timing');

Assistance with PHP and MYSQL

I have code here that is supposed to print a html table from my mysql database. When I open the page in my web browser, it is a blank page.
<html>
<body>
<?php
$connection = mysql_connect('localhost', 'admin', 'may122000');
mysql_select_db('contacts');
$query = "SELECT * FROM users";
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
echo "</table>";
mysql_close();
?>
</body>
</html>
Remove password
Enable error output
When you use mysql_fetch_array you will get the resulting array with numeric indices.
mysql_fetch_assoc will give you an associative array, like you want.
Note: mysql_* is deprecated.
while($row = mysql_fetch_assoc($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
If you still want to use mysql_fetch_array you'll have to pass a second parameter:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
First of all user mysqli or PDO and mysqli_fetch_assoc() so you have only associative array. Blank page is probably result of a hidden error, that's stored in your error.log on your server - take a look at it and get back to us.
I prefer using PDO or mysqli but anyway , Are u sure Your connection is established ? to check this and check other connections and query :
if (!connection)
die(mysql_error());
try this and feedback me
Improvements - some of which already mentioned in other post but all put together in one form:
<?php
$connection = mysqli_connect('localhost', 'admin', '****', 'contacts');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT first_name, last_name, phone FROM users";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
echo "<table>"; // start a table tag in the HTML
while($row = mysqli_fetch_array($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
echo "</table>";
mysqli_close($connection);
?>
So, first off the MySQL_* has been upgraded to Mysqli, with some minor reformatting,
The select * has been replaced with selecting only the needed columns.
The closing statement has been correctly set.
Firstly if your connection fails an error catch will output this to the screen. Remove this upon product launch or public launch of the page.
A (Rather rudimentary) error catch has been put in that if the SQL Query is bad that an error is outputted. Again, this should be removed in production but will help you with finding SQL errors.
If No SQL errors return the you have either an empty table in your database, or some sort of PHP error but from the code sample given the most likely error is that your PHP doesn't run MySQL and would only run PDO or MySQLi.
You also said "when I open the page in my browser it is a blank page", if the Source of the page is blank - as in it DOES NOT show
<html>
etc, then this is a sign the PHP execution failed and you have bad PHP, as detailed in your error log file.
The most likely cause of this from the code sample given is, as stated already, your PHP version does not support MySQL.
If your
<table>
Tag appears in your HTML source code then this is a sign that the While clause is not running which means your Datbase table is empty and there is no data to output.
Hope this helps. But first point of call is to upgrade to MySQLi :)

MySQL not returning error in PHP

Got this line in my database class,
$return = mysql_fetch_array($data) or
$this->dberror("Error fetching data<br/>" . mysql_error());
but all the site puts out is: Error fetching data
Try this: echo("Error: " . mysql_error($con));
Replace $con with your connection variable.

php syntax error - beginner

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]}"

Categories