I need some help with this code:
<?php
include("config.php");
$Servico=implode(" ", $_POST['service']);
$con=mysqli_connect("","","",""); //I hid the info here
if (mysqli_connect_errno())
{
echo "Falhou a conexão ao MySQL: " . mysqli_connect_error();
}
$to = mysqli_query($con,"SELECT Email FROM utilizadores WHERE Nome LIKE '%$Servico%'");
$row = mysqli_fetch_assoc($to);
$row['Email'];
foreach ($row as $destino)
{
echo $destino;
}
?>
The array is created in other code, by selecting one or more users that exists in the database. Then it creates the array with the users selected.
When my array have only a name, it retrieves the email correctly, but when i have more than one, it gives me:
Warning: Invalid argument supplied for foreach() in /home/a5301436/public_html/criartarefa.php on line 49
Can someone help me?
Here's how to do it using IN.
$con=mysqli_connect("","","",""); //I hid the info here
if (mysqli_connect_errno())
{
echo "Falhou a conexão ao MySQL: " . mysqli_connect_error();
}
$Servico=implode(", ", array_map(function($s) use ($con) {
return "'" . mysqli_real_escape_string($con, $s) . "'";
}, $_POST['service']));
$to = mysqli_query($con,"SELECT Email FROM utilizadores WHERE Nome IN ($Servico)");
while ($row = mysqli_fetch_assoc($to)){
echo $row['Email'];
}
Related
I have some troubles with visualization of the date in a query with php. Here is the code:
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "alternanza";
// connessione al server sql
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die("errore nella connessione");
} else {
echo "connessione avvenuta correttamente <Br/>";
}
// recupero dati passati dal form
$nome = $_POST["nome"];
$cognome = $_POST["cognome"];
$dal = $_POST["dal"];
$al = $_POST["al"];
$query = "select NomeS, CognomeS, Specializzazione, Denominazione
from studente, azienda, attivitàformativa
where CodFiscaleS=KCodFiscaleS and CodAzienda=KodAzienda and Data_inizio='$dal'
and Data_fine='$al' and CognomeS='$cognome' and NomeS='$nome'";
$risultato = mysqli_query($conn, $query);
if (!$risultato) {
echo " errore di comando <br/>";
exit();
}
while ($riga = mysqli_fetch_array($risultato))
if ($riga) {
echo "nome: " . $riga['NomeS'] . " <br/>";
echo "cognome: " . $riga['CognomeS'] . " <br/>";
echo "periodo stage dal: " . $riga['Data_inizio'] . " <br/>";
echo "al: " . $riga['Data_fine'] . " <br/>";
echo "presso azienda: " . $riga['Denominazione'] . " <br/>";
echo "con specializzazione: " . $riga['Specializzazione'] . " <br/>";
}
mysqli_close($conn);
echo " connessione chiusa";
?>
The errors I viewed are:
Notice: Undefined index: Data_inizio(date) in
C:\xampp\htdocs\scuola18\attestato.php on line 38 periodo stage dal:
Notice: Undefined index: Data_fine in
C:\xampp\htdocs\scuola18\attestato.php on line 39 al:
Do you know something about?
You have missed Data_fine and Data_inizio in your select query. Your select query should look like this
select NomeS, Data_fine, Data_inizio, CognomeS, Specializzazione, Denominazione
from studente, azienda, attivitàformativa
where CodFiscaleS=KCodFiscaleS and CodAzienda=KodAzienda and Data_inizio='$dal'
and Data_fine='$al' and CognomeS='$cognome' and NomeS='$nome'
However, I suggest you to use parepared statements to prevent from sql injections
I have a php file (with simple_HTML_Dom) which scrape all the URLs of a CSV file.
He extract all the info I need, and all OK, but now I want to add all these results on my MySQL table.
I want each result adds in one row in MySQL table.
That's the code I have so far:
<?php
require 'libs/simple_html_dom/simple_html_dom.php';
set_time_limit(0);
function scrapUrl($url)
{
$html = new simple_html_dom();
$html->load_file($url);
$names = $html->find('h1');
$manufacturers = $html->find('h2');
foreach ($names as $name) {
echo $name->innertext;
echo '<br>';
}
foreach ($manufacturers as $manufacturer) {
echo $manufacturer->innertext;
echo '<br>';
echo '<hr><br>';
}
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
//print_r($csv); // Verás que es un array donde cada elemento es array con una de las url.
foreach ($csv as $linea) {
$url = $linea[0];
scrapUrl($url);
}
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach ($csv as $linea) {
$sql = "INSERT INTO productos (nombre, nombreFabricante) VALUES($name, $manufacturer)";
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
EDIT: I have updated the code. I have added also the price variable.
The error shown in the output is this one:
Notice: Undefined variable: name in C:\xampp\htdocs\bootstrap\csv2.php on line 69
Notice: Undefined variable: manufacturer in C:\xampp\htdocs\bootstrap\csv2.php on line 69
Error: INSERT INTO productos (nombre, nombreFabricante) VALUES(,)
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' 'https://url.com/es/product1.html', )' at line 1
How can I solve the error for the Notice: Undefined variable: name & price?
I want to add the $name and $manufacturer variables which are inside the function, to my MySQL table
I'm not sure where you define $name so you'll need to check that it's valid.
foreach ($csv as $linea) {
$sql = "INSERT INTO productos (name, manufacturer) VALUES('$name', '{$linea[0]}')";
print ("<p> $sql </p>");
if ($conn->query($sql) === TRUE) {
echo "Items added to the database!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
Try this code , Hope you are collecting each value separately but your need is to insert each set of result in the mysql table as a new row , try the below but it's a rough one make it as per your need.
require 'libs/simple_html_dom/simple_html_dom.php';
set_time_limit(0);
function scrapUrl($url)
{
$ar_name =array();
$ar_man = array();
$html = new simple_html_dom();
$html->load_file($url);
$names = $html->find('h1');
$manufacturers = $html->find('h2');
foreach ($names as $name) {
$ar_name[] = $name->innertext;
}
foreach ($manufacturers as $manufacturer) {
$ar_man[] = $manufacturer->innertext;
}
for($i=o;$i<sizeof($ar_name);$i++)
{
$sql = "INSERT INTO table(name, manufacturer)
VALUES ($ar_name[$i],$ar_man[$i])";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
//echo $url;
}
$rutaCSV = 'csv/urls1.csv'; // Ruta del csv.
$csv = array_map('str_getcsv', file($rutaCSV));
I want to fetch database value in html tag, is it possible ?? I can fetch database value in textbox using this code
$con = mysqli_connect("localhost", "root", "", "hct_db"); // Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$client_id = mysqli_real_escape_string($con, $_POST['client_id']);
$result = mysqli_query($con, "SELECT * FROM client where client_id = '" . $client_id . "'");
while ($row = mysqli_fetch_array($result)) {
<input class="form-control" name="client_id1" value="<?php echo( htmlspecialchars( $row['address'] ) ); ?>" />
Try this (it will fill your input boxes with the value)
<?php
$con = mysqli_connect("localhost", "root", "", "hct_db"); // Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$client_id = mysqli_real_escape_string($con, $_POST['client_id']);
$result = mysqli_query($con, "SELECT * FROM client where client_id = '" . $client_id . "'");
echo '<form action="" method="post">';//openning upthe
while ($row = mysqli_fetch_array($result)) {
echo '<p>'.( htmlspecialchars( $row['address'] ) ).'</p>';
}
Yes, you can do it. At first, retrieve your data using query and keep it an array and then echo it.
yes you can try this and pls try something before posting a question...
<?php
$con=mysqli_connect("localhost","root","","hct_db"); // Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} // escape variables for security
$client_id = mysqli_real_escape_string($con, $_POST['client_id']);
$result = mysqli_query($con,"SELECT * FROM client where client_id = '".$client_id."'");
while($row = mysqli_fetch_array($result)) { //this is my retrieve code, what to do next ? ?>
<? echo $row[0]; ?> // href tag
<h2><? echo $row[0]; ?></h2> //h tag
<p><? echo $row[0]; ?></p> //p tag
//and so on
<?}?>
comment for further querys...
For the code below added, i am not getting any result printed.
$con = #mysqli_connect("localhost","root","","temp");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query="SELECT * FROM `login`";
echo $query;
$result=#mysqli_query($query) or die(mysql_error());
while($row=mysqli_fetch_array($result))
{
echo $row["username"];
}
Try the below code it will work
//conection:
$con = mysqli_connect("localhost","root","","temp") or die("Error " . mysqli_error($con));
//consultation:
$query = "SELECT * FROM login" or die("Error in the consult.." . mysqli_error($con));
//execute the query.
$result = $con->query($query);
//display information:
while($row = mysqli_fetch_array($result)) {
echo $row["username"] . "<br>";
}
Use this code as it is.
$con=mysqli_connect("localhost","root","","temp");
$result = mysqli_query($con,"SELECT * FROM login");
while($row = mysqli_fetch_array($result))
{
echo $row["username"];
}
// use this code and plz check your db name
$host='localhost';
$user='root';
$pass='';
$db_name='temp';
$con=mysqli_connect($host,$user,$pass,$db_name);
if($con)
{
echo "db connect succecssfully";
}
$slt="select * from login";
$query=mysqli_query($slt,$con);
while($row=mysqli_fetch_array($query))
{
echo $row["username"];
}
<?php
$con=mysqli_connect("localhost","root","","temp");
// Here localhost is host name, root is username, password is empty and temp is database name.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
$result = mysqli_query($con,"SELECT * FROM login");
while($row = mysqli_fetch_array($result)) {
echo $row["username"] . "<br>";
}
mysqli_close($con);
?>
Use this. it may solve your problem.
//connection
$con = mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
I am trying to search some data from a database. The search works fine, however if I click on search without entering anything into the form, it displays all the data on the database. Anyway I can fix this?
This is my php code.
$link=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_selected = mysqli_select_db($link,"AnimalTracker1");
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysqli_error($link));
}
$searchKeyword = $_POST['find']; // Sanitize this value first !!
$sql=mysqli_query($link, "Select * FROM Locations WHERE `Animal_Type` LIKE '%$searchKeyword%' ");
if ($sql == FALSE)
{
die($sql." Error on query: ".mysqli_error($link));
}
while($result = mysqli_fetch_array($sql))
{
echo $result ['Animal_Type'];
echo "<br>";
echo $result ['Latitude'];
echo "<br> ";
echo $result ['Longitude'];
echo " <br>";
echo $result ['Seen'];
echo " <br> ";
echo $result ['Time'];
echo "<br> ";
echo "<br> ";
}
//}
?>
Just make sure $searchKeyword has a (valid) value
$link=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_selected = mysqli_select_db($link,"AnimalTracker1");
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysqli_error($link));
}
// checks to see if $_POST['find'] is actually set.
if ( array_key_exists('find',$_POST) )
{
$searchKeyword = $_POST['find']; // Sanitize this value first !!
// sanitize $searchKeyword here
}
// checks to see if $searchKeyword has no value, or just contains empty space
if ( empty(trim($searchKeyword)) )
{
echo "You must enter a search term";
}
else
{
$sql=mysqli_query($link, "Select * FROM Locations WHERE `Animal_Type` LIKE '%$searchKeyword%' ");
if ($sql == FALSE)
{
die($sql." Error on query: ".mysqli_error($link));
}
while($result = mysqli_fetch_array($sql))
{
echo $result ['Animal_Type'];
echo "<br>";
echo $result ['Latitude'];
echo "<br> ";
echo $result ['Longitude'];
echo " <br>";
echo $result ['Seen'];
echo " <br> ";
echo $result ['Time'];
echo "<br> ";
echo "<br> ";
}
}
?>
Try removing the "%" from either the back or the front of the $searchKeyword in the query and I guess it should do the work.
"%" is used when match all or none. So if you send an empty string it will return the whole database.