Using multi_query doesn't give the desired output - php

I am trying to query two tables from a database, while using fetch_assoc() (instead of fetch_row()). The code is below and I am not getting any data from this query. I managed to query the first table, then added some code to query the second one and now I am not getting any output. Any help will be appreciated.
$mysqli = mysqli_connect($servername, $username, $password, "6dwxnmkq", 3314);
if(!$mysqli){
die('Connection failed!');
}
$sql = "SELECT IndexJedlo, Jedlo, Cena, Priloha FROM `jedalny_listok`";
$sql .= "SELECT index, polievka, cena FROM `polievky`";
$jedla = array(8);
$ceny = array(8);
$index = array(8);
$polievky = array(2);
$polievkyCeny = array(2);
$polievkyIndex = array(2);
$i = 0;
if ($mysqli->multi_query($sql)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
if($i == 0){
array_push($jedla, $row['Jedlo']);
array_push($ceny, $row['Cena']);
array_push($index, $row['IndexJedlo']);
}else{
array_push($polievky, $row['polievka']);
array_push($polievkyCeny, $row['cena']);
array_push($polievkyIndex, $row['index']);
}
}
$result->free();
}
if ($mysqli->more_results()) {
$i = $i + 1;
}
} while ($mysqli->next_result());
}
$mysqli->close();

Related

SQL - Why I have a duplicated row if im checking that unique id exists?

I found a duplicated row in my table
> image from my table
But in my code, I check if "unique_id" key exists, then update this row, else, create..
I am very noob with sql and I made some functions to make more easy my life... this is my "send_score.php" file
<?php
header('Content-Type: text/plain');
header("Access-Control-Allow-Origin: *");
include "../../functions.php";
$servername = "xxx";
$database = "xxx";
$username = "xxx";
$password = "xxx";
$tabla = "xxx";
$unique_key = $_POST['unique_key'];
$nick = $_POST['nick'];
$puntos = $_POST['puntos'];
$con = sql_connect($servername, $username, $password, $database);
if ( sql_check_row($con,$tabla,"unique_key","'".$unique_key."'") ) {
//if exists, replace
if ( sql_update_row($con,$tabla,"nick",$nick,"unique_key",$unique_key) && sql_update_row($con,$tabla,"sc",$puntos,"unique_key",$unique_key) ) {
echo "OK UPDATE";
exit;
}
else {
echo "BAD UPDATE";
exit;
}
}
else {
//if not exists, create
$arr_key = array("unique_key","nick","sc");
$arr_val = array("'".$unique_key."'","'".$nick."'",$puntos);
if ( sql_insert_row($con,$tabla,$arr_key,$arr_val) ) {
echo "OK INSERT";
exit;
}
else {
echo "BAD INSERT";
exit;
}
}
sql_close($con);
?>
and here is the functions that im using here
function sql_connect($servername, $username, $password, $database) {
return mysqli_connect($servername, $username, $password, $database);
}
function sql_close($con) {
return mysql_close($con);
}
function sql_check_row($con,$table,$key,$value) {
$sql = mysqli_query($con, "SELECT * FROM ".$table." WHERE ".$key." = ".$value);
if( mysqli_num_rows($sql) ) {
return true;
}
else {
return false;
}
}
function sql_update_row($con,$table,$key_set,$value_set,$key_where,$value_where) {
$sql = mysqli_query($con,"UPDATE ".$table." SET ".$key_set." = '".$value_set."' WHERE ".$key_where." = '".$value_where."';");
if ($sql) {
return true;
}
else {
return false;
}
}
function sql_insert_row($con,$table,$key_arr,$value_arr) {
$keys = "(";
for ( $i = 0; $i < sizeof($key_arr); $i++ ){
if ($i != 0) {
$keys .= ",";
}
$keys .= $key_arr[$i];
}
$keys .= ")";
$query = "INSERT INTO ".$table." ".$keys." VALUES (";
for ( $i = 0; $i < sizeof($value_arr); $i++ ){
if ($i != 0) {
$query .= ",";
}
$query .= $value_arr[$i];
}
$query .= ");";
$sql = mysqli_query($con,$query);
if ($sql) {
return true;
}
else {
return false;
}
}
According to me, it shouldn't create a new row because a row already exists with the same "unique_id" and in the image, both rows have exactly the same "unique_id"... why???
A simply strategy here is to write the values of column "unique_key"
in an array and then test if the new value exist with "in_array()".
If the value exists you update. If not you insert a new row:
<?php
$all_unique_ids = array();
$con = sql_connect($servername, $username, $password, $database);
$stmt = $con->prepare("SELECT `unique_key` FROM `".$tabla."`");
$stmt->execute();
foreach ($stmt->get_result() as $row)
{
$all_unique_ids[] = $row['unique_key'];
}
mysqli_close($con);
if(in_array($unique_id, $all_unique_ids))
{
sql_update_row(.....);
}
else
{
sql_insert_row( ......);
}
?>
Your code has a race condition. Two requests to the same page at the same time with the same unique_id will check the database at the same time and both get back the same result. Namely that the given unique_id is not in the database.
Both requests will then each INSERT a row with the same unique_id. This is why databases allow you to give a column a unique constraint.

review system with function in variable

so basically I am trying to create a little thing where it outputs stars, based on the database saved rating integer. The problem is it does not seem to put the number I from the database, in the variable. Here is the code I used:
<?php
$productID = 100;
$con = mysqli_connect("localhost", "root", "", "example");
function connect()
{
$con = mysqli_connect("localhost", "root", "", "example");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating
FROM reviews
-- JOIN stockitemstockgroups USING (StockItemID)
-- JOIN stockgroups USING (StockGroupID)
WHERE reviewID = '5'
";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0)) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo $row["rating"];
}
} else {
echo "error";
}
}
$value = getStars($con);
echo $value;
for ($x = 1; $x <= $value; $x++) {
echo '<div class="rating"><span>★</span></div>';
}
?>
I'm having trouble finding a duplicate, though I'm sure this is one. You aren't returning anything from your function, so $value doesn't have a value.
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating FROM reviews WHERE reviewID = 5";
$result = $con->query($sql);
if ($result && ($result->num_rows > 0)) {
// output data of first row
$row = $result->fetch_assoc();
return $row["rating"];
} else {
return false;
}
}
As a general rule, never echo from a function. Also, no need for a loop over what will presumably be a single result.

multiple row saving to DB table

I have to save more than one row of data into database table.
I wrote this code for that. But when i run this code, two rows will be saved into two rows of db table, but every other row is same as the last row data.
i.e. that is the last row data is overwriting every other row data.
$values = array();
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
You aren't resetting your values array inside the loop so values[0] and values[1] will always have the first to values.
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
$values = array();
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
On a sidenote I would recommend looking into the PDO extension and parameterised queries as mysql_ is deprecated and the above code is vulnerable to SQL injection
You are mixing mysql and mysqli:
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db("dbname");
if (mysqli_query($sql)) {
echo "inserted";
} else {
echo "fail";
}

Can't we call $result as variable in php

i have query in my php code
$dbc = mysqli_connect('localhost', 'root','', 'delivery')
or die('Error connecting to MySQL server.');
$count = "SELECT MAX(id_pelanggan) FROM pelanggan";
$result = mysqli_query($dbc, $count)
or die('Error select query');
if (empty($result)) {
$id_pelanggan = 1;
}
else {
$id_pelanggan = $result + 1;
}
and the result was
Object of class mysqli_result could not be converted to int in C:\xampp\htdocs\delivery\addcustomer.php
whereas in mysql id_pelanggan datatype is int.
can anyone help me to make it works?
You try to assign your query to $id_pelanggan variable instead of the value from your query.
Fetch the result using *_fetch array() of your query
I've changed your if() condition because your $result won't be empty no matter what happens. The number of result maybe.
Put this and replace your if else condition:
if(mysqli_num_rows($result) == 0){ /* IF FOUND 0 RESULT */
$id_pelanggan = 1;
}
else {
while($row = mysqli_fetch_array($result)){
$maxid = $row["id_pelanggan"];
}
$id_pelanggan = $maxid + 1;
} /* END OF ELSE */
Simple fetch the result and increment it. You can do this by -
$count = "SELECT MAX(id_pelanggan) as max_id_pelanggan FROM pelanggan";
$result = mysqli_query($dbc, $count)
or die('Error select query');
if (empty($result)) {
$id_pelanggan = 1;
}
else {
$data = mysqli_fetch_assoc($result);
$id_pelanggan = $data['max_id_pelanggan'] + 1;
}

Echo text only if MySQL value matches

I have two rows in my MySQL data that I would like to have code echoed only if the MySQL row data is equal to '1' (as opposed to '0'). Here's the code so far, which seems to have some severe errors:
$query = "SELECT 162, 164 FROM search WHERE title = $title";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row()) {
if ($row["162"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
if ($row["164"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
}
$result->close();
}
$mysqli->close();
As it says in the code above the two rows are "162" and "164" in the database.
Use:
if ($row["162"] == 1)
Instead of:
if ($row["162"] = 1)
and:
if ($row["164"] == 1)
I tried for you something like this if it gives you some idea:
$host = "localhost";
$user = "myusername";
$pass = "mypassword";
$database = "WorldEngine";
$mysqli = new mysqli($host, $user, $pass, $database);
$title = "My Good News";
$query = "SELECT `162`, `164` FROM search WHERE title = '$title';";
if ($result = $mysqli->query($query)) {
$i = 0;
while ($row = $result->fetch_row()) {
if ($row["162"] == 1) {
echo '<div id="162link' . $i . '">1.6.2</div>';
}
if ($row["164"] == 1) {
echo '<div id="164link' . $i . '">1.6.4</div>';
}
$i++;
}
$result->free();
}
$mysqli->close();
The index $i is appended to the div ID in order to produce unique DOM element ID's in the HTML document. I would also suggest you to change your numerical column names into alphabet-starting names like c162, c164, ...
Hope this will help you.

Categories