Check if a row exists in another table using mysqli - php

I am trying to select a row in one table and if it does exists in the second table,do something and if it doesn't,copy the values from table one into the second.
The problem is that,once it finds match (a row that is present in the first and second table),it shows errors for all other rows that did not match.
This is the error
Notice: Trying to get property of non-object in C:\wamp\www\loans.php on line 26
This is my code
<?php
//error_reporting(0);
$mysqli = new mysqli("localhost", "root", "123456", "test");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "select dest_msisdn,text_message,service_id,sender_name from incoming_sms";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$dest_msisdn = $row['dest_msisdn'];
$text_message = $row['text_message'];
$service_id = $row['service_id'];
$sender_name = $row['sender_name'];
/**
Transactions
*/
$m = $mysqli->query("SELECT tel from transactions where tel = $dest_msisdn")->fetch_object()->message;
if(empty($m)){
$ti = "insert into transactions(message,tel) values($text_message,$dest_msisdn)";
$mysqli->query($ti);
}
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
I want to insert rows that i find in table one and are not in table two.

I suggest you check the rows yielded before accessing any properties that the result yields:
$m = $mysqli->query("SELECT tel, message from transactions where tel = $dest_msisdn");
// hi! im missing ^^
// you are accessing the property "message" but its not a selected column in your query
if($m->num_rows <= 0) {
$ti = "insert into transactions(message,tel) values($text_message,$dest_msisdn)";
$mysqli->query($ti);
}

When you chain like that you are assuming there will always be a row. When there isn't a row you cant get the property from it. That's why you get the error. So do something like this:
$r = $mysqli->query("SELECT tel from transactions where tel = $dest_msisdn");
if ($r->num_rows == 0) {
$ti = "insert into transactions(message,tel) values($text_message,$dest_msisdn)";
$mysqli->query($ti);
}

This doesn't answer your question directly, but it will fix your problem and probably solve some others.
The way you are going about inserting (where you first SELECT and then loop through the results in PHP, then SELECT from another table, then INSERT) seems unnecessarily complex. You can get rid of your PHP loop and just execute the INSERT in a single SQL statement without all the PHP overhead. Let your DB do the work for you.
All of this:
$query = "select dest_msisdn,text_message,service_id,sender_name from incoming_sms";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$dest_msisdn = $row['dest_msisdn'];
$text_message = $row['text_message'];
$service_id = $row['service_id'];
$sender_name = $row['sender_name'];
/**
Transactions
*/
$m = $mysqli->query("SELECT tel from transactions where tel = $dest_msisdn")->fetch_object()->message;
if(empty($m)){
$ti = "insert into transactions(message,tel) values($text_message,$dest_msisdn)";
$mysqli->query($ti);
}
}
/* free result set */
$result->free();
Could be changed to just this:
$mysqli->query("INSERT INTO transactions(message,tel) SELECT text_message, tel FROM transactions INNER JOIN incoming_sms on transactions.tel = incoming_sms.dest_msisdn")

Related

How can I use mysqli to SELECT and both DELETE and RETURN a single row based on WHERE condition

How can I do a mysqli php query so a SELECT request both RETURNS the row AND DELETES the same row in the MySQL DB?
This php script works fine to query and return a single row based on max numerical zipcode (an example) but my modifications do not complete the delete row:
<?php
echo phpversion();
// Create connection
$con = mysqli_connect("localhost", "mysqluser", "mysqlpass", "mysqldb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Select all from designated assigned bot
$sql = "SELECT * FROM mysqltable WHERE zipsize=( SELECT max(zipsize) FROM mysqltable ) LIMIT 1;";
// Confirm there are results
if ($result = mysqli_query($con, $sql)) {
// We have results, create an array to hold the results
// and an array to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each result
while ($row = $result->fetch_object()) {
// Add each result into the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
I tried adding this line in various places to delete the row to no success using Id, which is a unique code for every row in the table (also tried with $result and $resultArray instead of $row):
$delsql= mysqli_query($conn,"DELETE FROM mysqltable WHERE Id= $row['Id']");
If you want to select the data and then immediately delete that selected data then you need to run two separate queries. I don't really know why you have so much unnecessary code there, but I would do it this way:
<?php
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli("localhost", "mysqluser", "mysqlpass", "mysqldb");
$mysqli->set_charset('utf8mb4'); // always set the charset
// Select all from designated assigned bot
$sql = 'SELECT * FROM mysqltable WHERE zipsize=( SELECT max(zipsize) FROM mysqltable ) LIMIT 1';
$resultArray = $con->query($sql)->fetch_all(MYSQLI_ASSOC);
echo json_encode($resultArray);
// now delete
$sql = 'DELETE FROM mysqltable WHERE zipsize=( SELECT max(zipsize) FROM mysqltable ) LIMIT 1';
$resultArray = $con->query($sql);
If you don't need nested arrays and you only ever fetch a single row then you can replace fetch_all(MYSQLI_ASSOC) with fetch_assoc() instead.
Careful! These queries can have unexpected results due to the possibility of selecting a different row than the one you delete unless you specify ORDER BY.
If you have a primary/unique key in the table to uniquely identify the rows you are selecting/deleting then you can store the list of ids and then execute a WHERE IN() query.
For example:
// Select all from designated assigned bot
$sql = 'SELECT * FROM mysqltable WHERE zipsize=( SELECT max(zipsize) FROM mysqltable )';
$resultArray = $con->query($sql)->fetch_all(MYSQLI_ASSOC);
echo json_encode($resultArray);
// get all ids from our array
$ids = array_column($resultArray, 'Id');
// now delete
$sql = 'DELETE FROM mysqltable WHERE Id IN('.str_repeat('?,', count($ids) - 1) . '?)';
$stmt = $con->prepare($sql);
$stmt->bind_param(str_repeat('s', count($ids)), ...$ids);
$stmt->execute();

Use PHP loop to fetch tables data from the table which contain names of database tables

I have table named category which contain names of other tables in the same database. I want to fetch table names from category table and then fetch data from each table from db. So far I have this code below:
$db = new mysqli('localhost', 'root', '', 'db_cat');
if($db){
// $q = "SELECT TABLE";
// $echo = $db->query($q);
// echo $echo;
// $result = $db->query("SHOW TABLES");
$qCat="SELECT * FROM product_category";
$cat_query= $db->query($qCat) or die(mysql_error());
while ($fetch= $cat_query->fetch_object())
{
$cat_id=$fetch->id;
$category=$fetch->category;
$p_cat=str_replace(" ","_",strtolower($category).'_categories');
//if(strlen($category)>22){$fine_product_name= substr($service, 0,19).'...';}else{ $fine_product_name=$category;}
$result = $db->query("SHOW TABLES");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
}
The second query must be different.
$result = $db->query("SELECT * FROM $category");
while($row = $result->fetch_array()){
$tables[] = $row[0];
}
print_r($tables);
First of all your design to connect to a database is not that good, Please check the below code for a proper way of connecting to it.
<?php
$con=mysqli_connect("localhost","root","","db_cat");
//servername,username,password,dbname
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: ".mysqli_connect_error();
}
?>
Here is a sample code of getting data from a table ( where this table name is in another table).
$get_table_name ="SELECT TableName FROM table_name";
$get_name=mysqli_query($con,$get_table_name);
$count=0;
while($row_name=mysqli_fetch_array($get_name)){
$count++;
$tbName=$row_name['TableName'];
$_SESSION['table_name'][count]=$tbName;
}
This will show you how to fetch data from one table. You can use a For loop to get all the tables
$table=$_SESSION['table_name'][1];
$get_table ="SELECT * FROM $table";
.... // Normal way of fetching data
You can try to adjust your code according to this and improve it.
For further reference please refer http://php.net/manual/en/book.mysqli.php

Mysqli select and count by

i have the following code. When i run into phpmyadmin the result returns correctly 9 rows of users and a column called |count(*) with the count next to each user. Whats wrong on my while and cant return me the count? It returns just the user when in php code
<?php
if ($result = $mysqli->query("SELECT n.user, count(*) AS count_user FROM metadata n group by n.user")) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
printf ($row['user'], $row[count]);
}
}
/* free result set */
?>
hi if i understand correctly your Question try this :
<?php
$mysqli = new mysqli("localhost", "root", "root", "test");
if (mysqli_connect_errno()) {
printf("Échec de la connexion : %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT name FROM users ORDER BY name")) {
/* get num rows */
$row_cnt = $result->num_rows;
while($row = mysqli_fetch_assoc($result)) {
printf($row['name']);
}
printf('Nombre of line %s',$row_cnt);
$result->close();
}
$mysqli->close();
You have used wrong index. you gave alias count_user in your query so you must use it when you fetch.
Just change this
printf ($row['user'], $row[count]);
to
printf ($row['user'], $row['count_user']);

i want to execute a saved query in the database

I want to execute a query that i saved in my database like this:
ID | NAME | QUERY
1 | show_names | "SELECT names.first, names.last FROM names;"
2 | show_5_cities | "SELECT cities.city FROM city WHERE id = 4;"
Is this possible ?
I am kinda noob in php so plz explain if it is possible.
If I understand you correctly, you have your queries saved in the database in a table and you want to execute those.
Break the problem down: you have two tasks to do:
Query the database for the query you want to run.
Execute that query.
It's a bit meta, but meh :)
WARNING: the mysql_ functions in PHP are deprecated and can be dangerous in the wrong hands.
<?php
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
die('Could not connect to mysql');
}
if (!mysql_select_db('mysql_dbname', $link)) {
die('Could not select database');
}
$name = "show_5_cities"; // or get the name from somewhere, e.g. $_GET.
$name = mysql_real_escape_string($name); // sanitize, this is important!
$sql = "SELECT `query` FROM `queries` WHERE `name` = '$name'"; // I should be using parameters here...
$result = mysql_query($sql, $link);
if (!$result) {
die("DB Error, could not query the database\n" . mysql_error(););
}
$query2 = mysql_fetch_array($result);
// Improving the code here is an exercise for the reader.
$result = mysql_query($query2[0]);
?>
if you did create a stored procedure/function you can simply use:
mysql_query("Call procedure_name(#params)")
Thats will work. reference here: http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
Querying the table to get the query, then executing that query and looping through the results and outputting the fields
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$RequiredQuery = intval($_REQUEST['RequiredQuery']);
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $sql);
if ($row = mysqli_fetch_assoc($result))
{
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $row['QUERY']);
while ($row2 = mysqli_fetch_assoc($result))
{
foreach($row2 AS $aField=>$aValue)
{
echo "$aField \t $aValue \r\n";
}
}
}
?>
just open the Table and get the individual query in a variable like
$data = mysql_query('SELECT * FROM <the Table that contains your Queries>');
while(($row = mysql_fetch_row($data)) != NULL)
{
$query = $row['Query'];
mysql_query($query); // The Query from the Table will be Executed Individually in a loop
}
if you want to execute a single query from the table, you have to select the query using WHERE Clause.

php echo data from certain id

EDIT: I'm sorry I was unclear, I try to explain it right this time.
I have this data in a database table called tMenu:
id page_nl text
1 index_1 index1_text
2 index_2 index2_text
3 index_3 index3_text
These are 3 pages on my website called (in this case) index_1, index_2 and index_3. I have programmed it is such a way that each page shows there index1_text.
What I want now is to show page_nl in a menu. The code I have now is:
$qh = mysql_query('SELECT id, page_nl FROM tMenu ORDER BY id');
$row = mysql_fetch_array($qh);
$id = 'id';
<? echo $row['page_nl']; $id=="1" ;?>
<? echo $row['page_nl']; $id=="2" ;?>
<? echo $row['page_nl'];?>
In the way it is now it shows only page_nl from id 1, but I want that the next link shows page_nl from id 2. I hope my question is more clear now.
Your question isn't very clear - are you asking for something like this
$sql = "select * from yourtable where id = 1";
$result = mysql_query($sql);
//I am assuming there are more than 1 rows for ID 1
while($row = mysql_fetch_assoc($result)) {
echo $row['page_nl'];
}
OR ============================
$sql = "select * from yourtable"; //Select All
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
if($row['id'] == 1)
{
echo $row['page_nl'];
}
}
Presuming you mean database table, you need a routine to connect to the database then fetch the info:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "databasename"); // database name
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM table_name"; // put table name here
$result = $mysqli->query($query);
/* numeric array */
/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["id"], $row["page_nl"]);
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
?>
You need to use a foreach($var as $key =>$value) loop

Categories