table does not exists mysql but it does for loop - php

I hava weired problem here with mysql database and php.
In the php, it gets the table names and then loops through the tables. Takes the rows and then send the variables to a function. I am using for loops to do this.
The problem is that I have 7 tables. If table 2 and 3 contain rows then it loops through 2 and does everything correctly. and it does not give table does not exists error for table 1. but for table 3-7 it gives all as table not exists.
but if I remove rows in table 2 then it loops through 3 and works correctly, and gives no error for 1 and 2. but for table 4-7 it gives table not exists err.
Basically it only loops through one table with rows and gives errors for all following tables. I don't understand is that a connection problem to mysql or something else.
Below is the snippet of my code:
<?php
$hostname_localhost ="localhost";
$username_localhost ="xxxxxxx";
$password_localhost ="xxxxxxxxx";
$database_xxxxxxxxxx ="xxxxxxxxx";
$database_yyyyyyyyyyy ="yyyyyyyyyy";
$database_zzzzz = "zzzzz";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
$get_all_tables = mysql_query("SHOW TABLES FROM xxxxxxxxx");
$table_names = array();
while($row = mysql_fetch_array($get_all_tables, MYSQL_NUM)) {
array_push($table_names,$row[0]);
}
mysql_select_db($database_xxxxxxx, $localhost);
for ($i=0; $i<sizeof($table_names); $i++){
$table = trim($table_names[$i]);
$get_tag = mysql_query("SELECT * FROM $table");
if ($get_tag){
while($get_tag_infos = mysql_fetch_array($get_tag)){
$similarity = $get_tag_infos['similarity'];
//........... and many other variables
if ($similarity == 20){
get20(many variables);
}
if ($similarity == 40){
get40(many variables);
}
if ($similarity == 60){
get60(many varibales);
}
if ($similarity == 80){
get80(many variables);
}
if ($similarity == 100){
get100(many variables);
}
}
}
else{
echo '</br> error! </br>'.mysql_error().mysql_errno();
}
}
function get20(many variables){
// performs a insert function to mysql
}
function get40(many variables){
// performs a insert function to mysql
}
function get60(many variables){
// performs a insert function to mysql
}
function get80(many variables){
// performs a insert function to mysql
}
function get100(many variables){
// performs a insert function to mysql
}
?>

The problem is connection with database. after first table find your connection with has been changed by inner connection. So use different variables for connections. I am setting a code which is running perfectly. I have tested.
<?php
//conection:
$link = mysqli_connect("localhost","root","pass","test") or die("Error " . mysqli_error($link));
//consultation:
$query = "show tables" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = mysqli_query($link, $query);
//display information:
while($row = mysqli_fetch_array($result)) {
echo $row["Tables_in_test"] . "<br>";
$link2 = mysqli_connect("localhost","root","pass","test") or die("Error " . mysqli_error($link));
$query2 = "select * from ".$row['Tables_in_test'] or die("Error in the consult.." . mysqli_error($link2));
$result2 = mysqli_query($link2, $query2);
while($row2 = mysqli_fetch_array($result2)) {
echo "<pre>";
print_r($row2);
echo "</pre>";
}
}
?>

Related

When row is empty in PHP it should not display anything. When there is something in it, it should display input

function getConnection() {
$con = new mysqli('localhost','root','','shop');
if($con->connect_errno!=0){return null;};
$con->query("SET NAMES utf8");
return $con;}
function getRed(){
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = mysqli_query($con, $sql);
$row = mysqli_num_rows($result);
if($row["red"] == ""){
echo "";
}else{
while($row = mysqli_fetch_assoc($result)){
echo "<input type='image' src=" . $row["red"]. ">";
}
mysqli_close($con);}}
In PHP I have row "red" filled with link to MShirt/redshirt.png. This code should create an input with this image but if is empty shouldn't create input. Now, this doesn't work even with a filled row.
You have a number of problems with your code, but the main one is that mysqli_num_rows() does not return data. It tells you how many records were fetched from the database into PHP.
You don't need mysqli_num_rows() in your code.
You don't need mysqli_close($con);, especially not inside of the loop.
You don't need the while loop. This is an old way of iterating. Use foreach instead.
You don't need if/else and echo "". You only need the positive condition.
Here is your code fixed:
function getConnection() {
// enabler error reporting, create an instance and set the correct charset
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli('localhost', 'root', '', 'shop');
$con->set_charset('utf8mb4');
return $con;
}
function getRed() {
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = $con->query($sql);
foreach ($result as $row) {
if ($row["red"] != "") {
echo "<input type='image' src=" . $row["red"] . ">";
}
}
}
The function mysqli_num_rows() returns only the count of results returned by your query, the mysqli_fetch_assoc() is the one going through the results. I would suggest taking the mysqli_close($con); outside the if statement as shown.
<?php
function getConnection() {
$con = new mysqli('localhost','root','','shop');
if($con->connect_errno!=0){return null;};
$con->query("SET NAMES utf8");
return $con;}
function getRed(){
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = mysqli_query($con, $sql);
$rowCount = mysqli_num_rows($result);
if($rowCount > 0) {
while($row = mysqli_fetch_assoc($result)){
if(isset($row["red"]) && $row["red"] != "") {
echo "<input type='image' src=" . $row["red"]. ">";
}
}
}
mysqli_close($con);
}
I don't know what this input should work for, but I assume you want to simply embed an image. Use it like this:
$result = mysqli_query($con, $sql);
while ($row= mysqli_fetch_assoc($result)) {
echo '<img src="' . $row['red']. '" />';
}
mysqli_num_rows is used to count how many rows are in the result, it returns the number of rows which you can not read like an array...
$result = mysqli_query($con, $sql);
$row_count = mysqli_num_rows($result);
echo $row_count.' rows in result.';
while ($row = mysqli_fetch_assoc($result)) {
echo '<img src="' . $row['red']. '" />';
}
Please make sure to understand basic HTML before getting into PHP and MySQL, also do not do database queries without getting to know proper security standards.

Error in counting the rows from the database using php for pagination

I am trying to learn pagination using php and mysql. I have created a function to count the rows in the table to store it and use it in the pagination function but no result occurs and I am unable to understand the problem in the code.
function get_row_count() {
$connect = connect();
$sql = "SELECT COUNT(*) AS rows From class";
$d = mysqli_query($connect, $sql);
$c = mysqli_num_rows($d);
if ($c == true) {
$row = mysqli_fetch_assoc($result);
return $row['rows'];
} else {
echo "<script>alert('error')</script>";
}
}
}

mysqli_free_result() expects parameter 1 to be mysqli_result, null given in

I just migrated a site from one domain to another domain (and another host). I made sure that all links were replaced and exported/imported my database. The migration seemed to have worked, but for some reason I am getting an error on my new domain that I did not get on my old domain (with, as far as I know, the same code).
My error is: "Warning: mysqli_free_result() expects parameter 1 to be mysqli_result, null given in path on line 84". I looked at the other StackOverflow questions that address this error, but I have not found a solution yet.
This is my code:
<?php
session_start();
// 1. Create a database connection
$dbhost =
$dbuser =
$dbpass =
$dbname =
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection occurred.
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
// 2. Perform database query
if (empty($_SESSION['order'])) {
$query = "INSERT INTO `orders` (`order_id`) VALUES (NULL)";
$result = mysqli_query($connection, $query);
// Test if there was a query error
if (!$result) {
die("Database query failed.");
}
// 3. Use returned data (if any)
$order_id_recent = mysqli_insert_id($connection);
$_SESSION['order'] = $order_id_recent;
}
$size = $_POST["size"];
$paper = $_POST["paper"];
$type = $_POST["type"];
$quantity = $_POST["quantity"];
// 2. Perform database query
$query2 = "SELECT product_id FROM product WHERE product_type = '$type' AND size = '$size' AND paper = '$paper'";
$result2 = mysqli_query($connection, $query2);
// Test if there was a query error
if (!$result2) {
die("Database query failed.");
}
// 3. Use returned data (if any)
while($row = mysqli_fetch_assoc($result2)) {
$product_id = $row['product_id'];
}
$order_id = $_SESSION['order'];
// 2. Perform database query
$order_id = $_SESSION['order'];
$query3 = "SELECT * FROM order_item WHERE order_id = '$order_id' AND product_id = '$product_id'";
$result3 = mysqli_query($connection, $query3);
// Test if there was a query error
if (!$result3) {
die("Database query failed.");
}
while($row = mysqli_fetch_assoc($result3)) {
$itemexistrows = mysqli_num_rows($result3);
}
if ($itemexistrows > 0) {
$query4 = "UPDATE order_item SET quantity = quantity + '$quantity' WHERE product_id = '$product_id' AND order_id = '$order_id'";
$result4 = mysqli_query($connection, $query4);
if (!$result4) {
die("Database query failed.");
} else {
echo 'The item has been added to your cart. <a class="text-red" href="viewcart.php">View your cart</a></div>.';
}
} else {
$query5 = "INSERT INTO `order_item`(`order_item_id`, `product_id`, `quantity`,`order_id`) VALUES (NULL,'$product_id','$quantity','$order_id')";
$result5 = mysqli_query($connection, $query5);
if (!$result5) {
die("Database query failed.");
} else {
echo 'The item has been added to your cart. <a class="text-red" href="viewcart.php">View your cart</a></div>.';
}
}
// 4. Release returned data
mysqli_free_result($result);
// 5. Close database connection
mysqli_close($connection);
?>
The weird thing is that my website still seems to work. These lines of code are part of a shopping cart module and the shopping cart seems to get updated.
I suspect that $_SESSION['order'] is not empty and thus $result is not set as it does not seem to be addressed inside the same if statement.
The following would almost certainly make the problem go away.
if(isset($result) && $result!=null){
// 4. Release returned data
mysqli_free_result($result);
}
Or, as suggested in comments, and probably better:
if(isset($result) && is_resource($result)){
// 4. Release returned data
mysqli_free_result($result);
}

PHP returns only the first row from table

<?php
$connection = mysqli_connect("localhost","user","password");
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
$db_select = mysqli_select_db($connection, "database");
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$numeUser = mysqli_query($connection, "select * from table order by column_name");
$utilizator = mysqli_fetch_array($numeUser);
$numeUtilizator = $column_name[1];
$nume = $column_name[2];
$rol = $column_name[5];
$actiune = $column_name[8];
$firstNames = $numeUtilizator;
$lastNames = $nume;
$productNames = $rol;
$actions = $actiune;
$data = array();
$i=0;
while($i < count($firstNames))
{
$row["firstname"] = $firstNames;
$row["lastname"] = $lastNames;
$row["productname"] = $productNames;
$row["quantity"] = $actions;
$data[$i] = $row;
$i++;
}
header("Content-type: application/json");
echo "{\"data\":" .json_encode($data). "}";
?>
I have the code above and I can`t figure why it returns me only the first row from database. It does not show them all. Does anyone please what am I missing?
Thank you very much. Cheers!
A part from the fact that there is no javascript but php.
The mysql_fetch_array (deprecated, no longer exist in php 7) needs to be called in a while loop, look at the documentation, there is your problem, you're only fetching the 1st row.
Another thing, that code is messy, search google for model view controller or model view presenter.
You should never use SELECT * when querying, only select the columns you are going to use.

PHP/MySQL Problem

Why does this only print the sites specific content under the first site, and doesn't do it for the other 2?
<?php
echo 'NPSIN Data will be here soon!';
// connect to DB
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to DB');
$dbname = 'npsin';
mysql_select_db($dbname);
// get number of sites
$query = 'select count(*) from sites';
$result = mysql_query($query) or die ('Query failed: ' . mysql_error());
$resultArray = mysql_fetch_array($result);
$numSites = $resultArray[0];
echo "<br><br>";
// get all sites
$query = 'select site_name from sites';
$result = mysql_query($query);
// get site content
$query2 = 'select content_name, site_id from content';
$result2 = mysql_query($query2);
// get site files
// print info
$count = 1;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "Site $count: ";
echo "$row[0]";
echo "<br>";
$contentCount = 1;
while ($row2 = mysql_fetch_array($result2, MYSQL_NUM)) {
$id = $row2[1];
if ($id == ($count - 1)) {
echo "Content $contentCount: ";
echo "$row2[0]";
echo "<br>";
}
$contentCount++;
}
$count++;
}
?>
The problem is that you assume that once your finished looking for the row with the same id as the site row, that it'll reset the $result2 query to the beginning. This means that after you find your first row (unless you were to sort the two queries), that the second pass of the while loop wouldn't have any results left. You should consider caching the inner while loop first and then using an array lookup to get the value.
An even better solution would involve a join from sites to content which wouldn't require this complex matching process. Joins are a VERY important part of SQL, I highly suggest learning how to use them. http://dev.mysql.com/doc/refman/5.0/en/join.html

Categories